CIT ZigZag Projection

citdates · study · 221 行 · 点赞 473 · TradingView 原页

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

Pine Script

//@version=6
// CIT ZigZag Projection: projects the current zigzag leg by the average and median size and length of the past legs
// in the same direction. A zigzag on highs and lows turns when price reverses by the deviation % from its extreme.
// When the last confirmed pivot is a low (the zigzag points up), the up-leg in progress is projected from that low:
//   average  = low x (1 + the average % gain of all completed up-legs), reached after their average number of bars
//   median   = the same with the medians
// (points down: the down-leg from the last high, by the past down-legs). A table lists the legs counted, their average
// and median % move and length, how far the current leg has come against the median, and its rank: the share of
// past legs it has already outgrown in size and in time (Early < 50%, Typical, Long >= 80%, Extreme >= 95%) (Table position: bottom right by default).
// Quarterly Dow (TVC:DJI 3M) with 35%, legs since 1974: 4 up-legs, average +366% in 41 bars, median +369% in 46.5;
// from the March 2020 low (18,214) average ~84,900 around mid 2030, median ~85,400 around late 2031.
// Automatic deviation: autoMult x the average true range % over autoLen bars (3 x 50: ~30-35% quarterly Dow, ~3-4%
// daily index ETFs, ~6-12% daily stocks). Projections are averages of past legs, not forecasts; few legs make them rough. For information only.
indicator("CIT ZigZag Projection", overlay = true, max_lines_count = 500, max_labels_count = 500)
 
devPct = input.float(35.0, "Reversal deviation (%)", minval = 0.5, step = 0.5, tooltip = "How far price must reverse from its extreme to confirm a pivot. Quarterly Dow: ~35%. Daily stocks: 5-10%.")
showZZ = input.bool(true, "Draw the zigzag lines")
showAvg = input.bool(true, "Project by the average leg")
showMed = input.bool(true, "Project by the median leg")
minLegs = input.int(2, "Fewest past legs to project", minval = 1)
zzColor = input.color(color.new(color.orange, 0), "Zigzag color (down legs)")
upColor = input.color(color.new(color.teal, 0), "Projection color (up)")
dnColor = input.color(color.new(color.red, 0), "Projection color (down)")
showTable = input.bool(true, "Show the statistics table")
sinceYear = input.int(0, "Count legs since (year, 0 = all)", minval = 0, tooltip = "Use only the legs that start in or after this year, e.g. 1974 for the quarterly Dow's modern legs.")
autoDev = input.bool(false, "Automatic reversal deviation", tooltip = "Instead of the fixed %: a multiple of the average true range as a % of price (the bar's high-low range with gaps, over the last bars below). Adapts to each symbol and time frame: about 30-35% on the quarterly Dow, 3-4% on daily index ETFs, 6-12% on daily stocks.")
autoMult = input.float(3.0, "Auto: ATR multiple", minval = 0.5, step = 0.5)
autoLen = input.int(50, "Auto: average over bars", minval = 5)
tablePos = input.string("Bottom right", "Table position", options = ["Top right", "Top left", "Bottom right", "Bottom left", "Middle right"])
zzUpColor = input.color(color.new(color.green, 0), "Zigzag color (up legs)")
 
// ---- the reversal deviation: fixed, or automatic (autoMult x the average true range %, the running average until autoLen bars) ----
float trPct = na(close[1]) ? (high - low) / close * 100 : ta.tr(true) / close[1] * 100
float trSma = ta.sma(trPct, autoLen)   // every bar (not inside the ternary)
float trCum = ta.cum(trPct) / (bar_index + 1)
float trAvg = bar_index + 1 >= autoLen ? trSma : trCum
float dev = autoDev ? autoMult * trAvg : devPct
 
// ---- zigzag on highs and lows ----
var int dir = 0                  // 1 = up-leg in progress (last pivot a low), -1 = down-leg (last pivot a high)
var float extPrice = na          // the running extreme of the leg in progress
var int extBar = na
var int extTime = na
var float pivPrice = na          // the last confirmed pivot
var int pivBar = na
var int pivTime = na
var upGain = array.new_float()   // completed up-legs: % gain and bars
var upBars = array.new_int()
var dnGain = array.new_float()   // completed down-legs: % fall (negative) and bars
var dnBars = array.new_int()
 
confirm(float price, int bar, int t, bool isHigh) =>
    // a leg ends at (price, bar): record it (if it starts in or after sinceYear), draw it
    if not na(pivPrice) and year(pivTime) >= sinceYear
        float chg = price / pivPrice - 1
        int bars = bar - pivBar
        if isHigh
            array.push(upGain, chg)
            array.push(upBars, bars)
        else
            array.push(dnGain, chg)
            array.push(dnBars, bars)
    if showZZ and not na(pivPrice)
        line.new(pivBar, pivPrice, bar, price, color = isHigh ? zzUpColor : zzColor, width = 2)
    label.new(bar, price, str.tostring(price, format.mintick), style = isHigh ? label.style_label_down : label.style_label_up, color = color.new(isHigh ? zzUpColor : zzColor, 20), textcolor = color.white, size = size.small)
    [price, bar, t]
 
// Before the first pivot: track the highest high and lowest low; the first 'devPct' reversal sets the direction
var float hi0 = na
var int hi0Bar = na
var int hi0Time = na
var float lo0 = na
var int lo0Bar = na
var int lo0Time = na
if dir == 0
    if na(hi0) or high > hi0
        hi0 := high
        hi0Bar := bar_index
        hi0Time := time
    if na(lo0) or low < lo0
        lo0 := low
        lo0Bar := bar_index
        lo0Time := time
    if high >= lo0 * (1 + dev / 100) and lo0Bar < hi0Bar
        [p, b, t] = confirm(lo0, lo0Bar, lo0Time, false)   // first pivot: the low; up-leg in progress
        pivPrice := p
        pivBar := b
        pivTime := t
        dir := 1
        extPrice := hi0
        extBar := hi0Bar
        extTime := hi0Time
    else if low <= hi0 * (1 - dev / 100) and hi0Bar < lo0Bar
        [p, b, t] = confirm(hi0, hi0Bar, hi0Time, true)    // first pivot: the high; down-leg in progress
        pivPrice := p
        pivBar := b
        pivTime := t
        dir := -1
        extPrice := lo0
        extBar := lo0Bar
        extTime := lo0Time
else if dir == 1
    if high > extPrice
        extPrice := high
        extBar := bar_index
        extTime := time
    if low <= extPrice * (1 - dev / 100)
        [p, b, t] = confirm(extPrice, extBar, extTime, true)   // the high is confirmed: down-leg from here
        pivPrice := p
        pivBar := b
        pivTime := t
        dir := -1
        extPrice := low
        extBar := bar_index
        extTime := time
else
    if low < extPrice
        extPrice := low
        extBar := bar_index
        extTime := time
    if high >= extPrice * (1 + dev / 100)
        [p, b, t] = confirm(extPrice, extBar, extTime, false)  // the low is confirmed: up-leg from here
        pivPrice := p
        pivBar := b
        pivTime := t
        dir := 1
        extPrice := high
        extBar := bar_index
        extTime := time
 
median(array<float> a) =>
    array.size(a) > 0 ? array.median(a) : na
 
medianInt(array<int> a) =>
    float m = na
    if array.size(a) > 0
        f = array.new_float()
        for v in a
            array.push(f, v)
        m := array.median(f)
    m
 
avgInt(array<int> a) =>
    array.size(a) > 0 ? array.avg(a) : na
 
fmtDate(int t) =>
    str.format_time(t, "MMM yyyy", syminfo.timezone)
 
// ---- projection on the last bar ----
var line lAvg = na
var line lMed = na
var label tAvg = na
var label tMed = na
var table tb = na
if barstate.islast and not na(pivPrice) and dir != 0
    bool up = dir == 1
    array<float> g = up ? upGain : dnGain
    array<int> n = up ? upBars : dnBars
    int legs = array.size(g)
    line.delete(lAvg)
    line.delete(lMed)
    label.delete(tAvg)
    label.delete(tMed)
    color pc = up ? upColor : dnColor
    float barMs = timeframe.in_seconds() * 1000.0
    if legs >= minLegs
        float gAvg = array.avg(g)
        float gMed = median(g)
        float bAvg = avgInt(n)
        float bMed = medianInt(n)
        if showAvg
            int xb = pivBar + int(math.round(bAvg))
            float yp = pivPrice * (1 + gAvg)
            int tt = time + int(math.round((xb - bar_index) * barMs))
            lAvg := line.new(pivBar, pivPrice, xb, yp, color = pc, style = line.style_dashed, width = 2)
            tAvg := label.new(xb, yp, ((up ? close > yp : close < yp) ? "Average leg (passed): " : "Average leg: ") + str.tostring(yp, format.mintick) + " ~" + fmtDate(tt) + "\n" + (gAvg >= 0 ? "+" : "") + str.tostring(gAvg * 100, "#") + "% in " + str.tostring(bAvg, "#.#") + " bars", style = up ? label.style_label_down : label.style_label_up, color = color.new(pc, 10), textcolor = color.white, size = size.small)
        if showMed
            int xb = pivBar + int(math.round(bMed))
            float yp = pivPrice * (1 + gMed)
            int tt = time + int(math.round((xb - bar_index) * barMs))
            lMed := line.new(pivBar, pivPrice, xb, yp, color = pc, style = line.style_dotted, width = 2)
            tMed := label.new(xb, yp, ((up ? close > yp : close < yp) ? "Median leg (passed): " : "Median leg: ") + str.tostring(yp, format.mintick) + " ~" + fmtDate(tt) + "\n" + (gMed >= 0 ? "+" : "") + str.tostring(gMed * 100, "#") + "% in " + str.tostring(bMed, "#.#") + " bars", style = up ? label.style_label_up : label.style_label_down, color = color.new(pc, 40), textcolor = color.white, size = size.small)
    if showTable
        if not na(tb)
            table.delete(tb)
        tb := table.new(tablePos == "Top right" ? position.top_right : tablePos == "Top left" ? position.top_left : tablePos == "Bottom left" ? position.bottom_left : tablePos == "Middle right" ? position.middle_right : position.bottom_right, 2, 8, bgcolor = color.new(color.black, 20), border_color = color.new(color.gray, 60), border_width = 1)
        float cur = close / pivPrice - 1
        int curBars = bar_index - pivBar
        table.cell(tb, 0, 0, "ZigZag " + (autoDev ? "auto " + str.tostring(dev, "#.#") + "%" : str.tostring(devPct) + "%") + (sinceYear > 0 ? " since " + str.tostring(sinceYear) : ""), text_color = color.white, text_size = size.small)
        table.cell(tb, 1, 0, up ? "Up-leg" : "Down-leg", text_color = pc, text_size = size.small)
        table.cell(tb, 0, 1, "Past legs", text_color = color.silver, text_size = size.small)
        table.cell(tb, 1, 1, str.tostring(legs), text_color = color.white, text_size = size.small)
        if legs > 0
            table.cell(tb, 0, 2, "Average", text_color = color.silver, text_size = size.small)
            table.cell(tb, 1, 2, str.tostring(array.avg(g) * 100, "#") + "% / " + str.tostring(avgInt(n), "#.#") + " bars", text_color = color.white, text_size = size.small)
            table.cell(tb, 0, 3, "Median", text_color = color.silver, text_size = size.small)
            table.cell(tb, 1, 3, str.tostring(median(g) * 100, "#") + "% / " + str.tostring(medianInt(n), "#.#") + " bars", text_color = color.white, text_size = size.small)
            table.cell(tb, 0, 4, "This leg", text_color = color.silver, text_size = size.small)
            table.cell(tb, 1, 4, (cur >= 0 ? "+" : "") + str.tostring(cur * 100, "#") + "% / " + str.tostring(curBars) + " bars", text_color = color.white, text_size = size.small)
            float pPrice = median(g) != 0 ? cur / median(g) : na
            float pTime = medianInt(n) > 0 ? curBars / medianInt(n) : na
            table.cell(tb, 0, 5, "vs median", text_color = color.silver, text_size = size.small)
            table.cell(tb, 1, 5, str.tostring(pPrice * 100, "#") + "% of the move, " + str.tostring(pTime * 100, "#") + "% of the time", text_color = color.white, text_size = size.small)
            // Rank: the share of past legs this one has already outgrown, in size (to its extreme so far) and in time
            float sizeNow = math.abs(extPrice / pivPrice - 1)
            int bigger = 0
            int longer = 0
            for i = 0 to legs - 1
                if math.abs(array.get(g, i)) < sizeNow
                    bigger += 1
                if array.get(n, i) < curBars
                    longer += 1
            float rSize = bigger * 100.0 / legs
            float rTime = longer * 100.0 / legs
            float rTop = math.max(rSize, rTime)
            string tier = rTop >= 95 ? "Extreme" : rTop >= 80 ? "Long" : rTop >= 50 ? "Typical" : "Early"
            color tierColor = rTop >= 95 ? color.red : rTop >= 80 ? color.orange : color.white
            table.cell(tb, 0, 6, "Rank: " + tier, text_color = tierColor, text_size = size.small)
            table.cell(tb, 1, 6, "bigger than " + str.tostring(rSize, "#") + "% of past legs, longer than " + str.tostring(rTime, "#") + "%", text_color = tierColor, text_size = size.small)
        table.cell(tb, 0, 7, "From", text_color = color.silver, text_size = size.small)
        table.cell(tb, 1, 7, str.tostring(pivPrice, format.mintick), text_color = color.white, text_size = size.small)

← 返回列表