Measured Move Projections

Uncle_the_shooter · study · 388 行 · 点赞 159 · 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/
// © Uncle_the_shooter
 
//@version=6
indicator("Measured Move Projections", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=50, max_bars_back=2050)
 
// =====================================================================
// INPUTS
// =====================================================================
const string G_SW  = "Swings"
pivotLength = input.int(20, "Pivot Length", minval=1, group=G_SW,
     tooltip="Number of bars required on each side to confirm a swing high or low. Higher values capture larger swings and ignore minor noise.")
maxK        = input.int(20, "Max Moves to Keep", minval=1, maxval=50, group=G_SW,
     tooltip="Number of most recent moves in each direction used to build the projections. The current move is tracked live, so its start point and the projections may shift until the swing is confirmed.")
 
const string G_PR  = "Projection"
showUpFan   = input.bool(true, "Upward Targets", group=G_PR,
     tooltip="Projects past upward moves. While price is rising, they start from the low where the current move began. While price is falling, they start from the lowest price of the current decline.")
showDnFan   = input.bool(true, "Downward Targets", group=G_PR,
     tooltip="Projects past downward moves. While price is falling, they start from the high where the current move began. While price is rising, they start from the highest price of the current advance.")
priceOnly   = input.bool(false, "Price Only (horizontal levels)", group=G_PR,
     tooltip="Off: each past move is projected as a vector (price change over its duration in bars), showing both the target price and when it would be reached.\nOn: only the target price levels are shown as horizontal lines.")
extBars     = input.int(3, "Level Extension Past Last Bar", minval=0, maxval=200, group=G_PR,
     tooltip="How many bars to the right of the last candle horizontal levels extend. Applies to all levels in Price Only mode and to the level lines of expired targets.")
 
const string G_MM  = "Measured Moves (Zigzag)"
showHist    = input.bool(true, "Lines  •  Transparency", inline="mm", group=G_MM)
histTransp  = input.int(40, "", minval=0, maxval=100, inline="mm", group=G_MM,
     tooltip="The recent swings the projections are based on, drawn on the price chart.")
showHistLbl = input.bool(true, "Δ Labels", group=G_MM)
 
const string G_ACT = "Active Targets"
actVec      = input.bool(true, "Vectors  •  Transparency", inline="av", group=G_ACT)
actVecT     = input.int(40, "", minval=0, maxval=100, inline="av", group=G_ACT,
     tooltip="Targets not yet reached, with time still remaining.")
actDot      = input.bool(true, "Dots  •  Transparency", inline="ad", group=G_ACT)
actDotT     = input.int(25, "", minval=0, maxval=100, inline="ad", group=G_ACT,
     tooltip="Dot marking the end of each target. Hover over a dot to see the move size, its duration in bars and the date the original move started.")
actLbl      = input.bool(false, "Δ Labels", group=G_ACT)
 
const string G_HIT = "Hit Targets (price already reached)"
hitVec      = input.bool(true, "Vectors  •  Transparency", inline="hv", group=G_HIT)
hitVecT     = input.int(50, "", minval=0, maxval=100, inline="hv", group=G_HIT,
     tooltip="Targets the current move has already reached, shown as dashed lines.")
hitDot      = input.bool(true, "Dots  •  Transparency", inline="hd", group=G_HIT)
hitDotT     = input.int(75, "", minval=0, maxval=100, inline="hd", group=G_HIT)
hitLbl      = input.bool(false, "Δ Labels", group=G_HIT)
 
const string G_EXP = "Expired Targets (time ran out)"
expVec      = input.bool(true, "Vectors  •  Transparency", inline="ev", group=G_EXP)
expVecT     = input.int(40, "", minval=0, maxval=100, inline="ev", group=G_EXP,
     tooltip="Targets whose time window has passed without price reaching them, shown as dotted lines in the Expired color (gray by default).")
expDot      = input.bool(true, "Dots  •  Transparency", inline="ed", group=G_EXP)
expDotT     = input.int(40, "", minval=0, maxval=100, inline="ed", group=G_EXP)
expLvl      = input.bool(true, "Level Line  •  Transparency", inline="el", group=G_EXP)
expLvlT     = input.int(40, "", minval=0, maxval=100, inline="el", group=G_EXP,
     tooltip="Extends the price level of each expired target past the last bar (see Level Extension Past Last Bar), so it can still be used as a reference level.")
expLbl      = input.bool(false, "Δ Labels", group=G_EXP)
 
const string G_MED = "Median Vector"
showMedian  = input.bool(false, "Line  •  Width", inline="md", group=G_MED)
medWidth    = input.int(3, "", minval=1, maxval=6, inline="md", group=G_MED,
     tooltip="Bold line showing the typical move: median size and median duration of the stored moves.")
showMedLbl  = input.bool(false, "Label", group=G_MED,
     tooltip="Shows the median move size, its duration in bars and 'now', the percentage of the median move the current move has already completed.")
 
const string G_BOX = "Target Box"
showBox     = input.bool(true, "Box  •  Transparency", inline="bx", group=G_BOX)
boxTransp   = input.int(85, "", minval=0, maxval=100, inline="bx", group=G_BOX,
     tooltip="Zone where past moves typically ended: price range (vertical) and time range (horizontal) between the lower and upper percentile. In Price Only mode it is drawn as a horizontal price band.")
showBoxLbl  = input.bool(true, "Label", group=G_BOX)
boxPct      = input.int(25, "Lower Percentile", minval=0, maxval=49, group=G_BOX,
     tooltip="25 = middle 50% of moves (25th to 75th percentile). 10 = middle 80% (P10–P90). 0 = full range (smallest to largest move).")
 
const string G_ST  = "Colors & Text"
upClr       = input.color(color.rgb(6, 162, 47), "Up  •  Down", inline="clr", group=G_ST)
downClr     = input.color(color.rgb(207, 23, 23), "", inline="clr", group=G_ST)
expClr      = input.color(color.gray, "Expired", group=G_ST,
     tooltip="Color of expired targets: vectors, dots and level lines. Default: gray.")
textClr     = input.color(color.rgb(119, 118, 118), "Text  •  Transparency", inline="txt", group=G_ST)
textTransp  = input.int(0, "", minval=0, maxval=100, inline="txt", group=G_ST)
dateFormat  = input.bool(true, "Date Format DD.MM.YYYY", group=G_ST,
     tooltip="Date format used in tooltips. On: DD.MM.YYYY. Off: MM/DD/YYYY.")
 
// =====================================================================
// STATE
// =====================================================================
var float[] movesUp   = array.new<float>()   // price change of each upward move (low -> high)
var float[] barsUp    = array.new<float>()   // duration of each upward move in bars
var int[]   timeUp    = array.new<int>()     // start time of each upward move
var line[]  histUpL   = array.new<line>()
var label[] histUpLb  = array.new<label>()
 
var float[] movesDown  = array.new<float>()  // price change of each downward move (high -> low)
var float[] barsDown   = array.new<float>()  // duration of each downward move in bars
var int[]   timeDown   = array.new<int>()    // start time of each downward move
var line[]  histDownL  = array.new<line>()
var label[] histDownLb = array.new<label>()
 
var line[]     projLines  = array.new<line>()
var label[]    projLabels = array.new<label>()
var box[]      projBoxes  = array.new<box>()
 
color transpClr = color.new(color.black, 100)
color txtClr    = color.new(textClr, textTransp)
 
// Pivots
ph        = ta.pivothigh(high, pivotLength, pivotLength)
pl        = ta.pivotlow(low, pivotLength, pivotLength)
isNewPH   = not na(ph)
isNewPL   = not na(pl)
pivotBar  = bar_index - pivotLength
 
// =====================================================================
// HELPERS
// =====================================================================
f_dateText(int t) =>
    dFmt = dateFormat ? "dd.MM.yyyy" : "MM/dd/yyyy"
    tFmt = timeframe.isintraday ? " HH:mm" : ""
    " • " + str.format_time(t, dFmt + tFmt, syminfo.timezone)   // exchange time zone
 
f_delta(float mv) =>
    "Δ " + str.tostring(mv, format.mintick)
 
f_tip(float mv, int nb, int t) =>
    f_delta(mv) + " • " + str.tostring(nb) + " bars" + f_dateText(t)
 
maxLookback = 2000
 
// Highest high (findHigh = true) or lowest low (findHigh = false) over bar offsets [o1, o2].
// Returns [price, bar_index, time]. On ties the most recent bar is used.
f_extreme(int o1, int o2, bool findHigh) =>
    float p = na
    int   i = na
    int   t = na
    int   a = math.max(0, o1)
    int   b = math.min(o2, math.min(bar_index, maxLookback))
    if a <= b
        for off = a to b
            float v = findHigh ? high[off] : low[off]
            if na(p) or (findHigh ? v > p : v < p)
                p := v
                i := bar_index - off
                t := time[off]
    [p, i, t]
 
// Stores a completed move and draws it on the chart.
// replaceLast: when the same swing is extended, the stored move is updated instead of added again.
f_record(float[] moves, float[] bars, int[] times, line[] hl, label[] hb, float mv, int t, bool replaceLast, int x1, float y1, int x2, float y2, bool up) =>
    float nb  = math.max(1, x2 - x1)
    color clr = color.new(up ? upClr : downClr, histTransp)
    if replaceLast and array.size(times) > 0 and array.last(times) == t
        int last = array.size(moves) - 1
        array.set(moves, last, mv)
        array.set(bars, last, nb)
        if array.size(hl) > 0
            line.set_xy1(array.last(hl), x1, y1)
            line.set_xy2(array.last(hl), x2, y2)
        if array.size(hb) > 0
            label.set_xy(array.last(hb), x2, y2)
            label.set_text(array.last(hb), f_delta(mv))
    else
        if array.size(moves) >= maxK
            array.shift(moves)
            array.shift(bars)
            array.shift(times)
            if array.size(hl) > 0
                line.delete(array.shift(hl))
            if array.size(hb) > 0
                label.delete(array.shift(hb))
        array.push(moves, mv)
        array.push(bars, nb)
        array.push(times, t)
        if showHist
            array.push(hl, line.new(x1, y1, x2, y2, color=clr, width=2))
        if showHistLbl
            array.push(hb, label.new(x2, y2, f_delta(mv), style=up ? label.style_label_down : label.style_label_up,
                 color=transpClr, textcolor=txtClr, size=size.small))
 
// Projects every stored move from the anchor (ax, ay) as a vector: price change over duration in bars.
// Target states:
//   active  - not reached yet, time remaining (solid)
//   hit     - price has already covered the move (dashed)
//   expired - duration has passed without price reaching the target (dotted, Expired color, level extended past the last bar)
f_fan(float[] moves, float[] bars, int[] times, int ax, float ay, bool up, color clr) =>
    int n = array.size(moves)
    if n > 0 and not na(ax) and not na(ay)
        [ep, ei, et] = f_extreme(0, bar_index - ax, up)
        float extent = na(ep) ? 0.0 : math.max(0.0, up ? ep - ay : ay - ep)
        int   rightX = bar_index + extBars
        int   maxX   = bar_index + 490          // drawings are limited to ~500 bars into the future
        float sgn    = up ? 1.0 : -1.0
        for i = 0 to n - 1
            float mv      = array.get(moves, i)
            int   nb      = math.max(1, math.round(array.get(bars, i)))
            float target  = ay + sgn * mv
            bool  hit     = extent >= mv
            bool  expired = not priceOnly and not hit and ax + nb < bar_index
            bool   vOn = hit ? hitVec  : expired ? expVec  : actVec
            int    vT  = hit ? hitVecT : expired ? expVecT : actVecT
            bool   dOn = (hit ? hitDot  : expired ? expDot  : actDot) and not priceOnly
            int    dT  = hit ? hitDotT : expired ? expDotT : actDotT
            bool   lOn = hit ? hitLbl  : expired ? expLbl  : actLbl
            bool   eOn = expired and expLvl
            if not (vOn or dOn or lOn or eOn)
                continue
            int   xe = priceOnly ? rightX : ax + nb
            float ye = target
            // Targets beyond the drawing limit are clipped along the vector
            if not priceOnly and xe > maxX
                ye := ay + sgn * mv * (maxX - ax) / nb
                xe := maxX
            color  base = expired ? expClr : clr
            string sty  = hit ? line.style_dashed : expired ? line.style_dotted : line.style_solid
            string tip  = f_tip(mv, nb, array.get(times, i))
            if vOn
                array.push(projLines, line.new(ax, priceOnly ? target : ay, xe, ye, color=color.new(base, vT), style=sty, width=1))
            if eOn
                array.push(projLines, line.new(xe, ye, rightX, ye, color=color.new(expClr, expLvlT), style=line.style_dotted, width=1))
            if dOn
                array.push(projLabels, label.new(xe, ye, "", style=label.style_circle, color=color.new(base, dT), size=size.tiny, tooltip=tip))
            if lOn
                array.push(projLabels, label.new(eOn ? rightX : xe, ye, f_delta(mv), style=label.style_label_left,
                     color=transpClr, textcolor=txtClr, size=size.small, tooltip=tip))
        // Target box: percentile range of move size (price) and duration (time)
        if showBox and n >= 2
            float pLo = array.percentile_linear_interpolation(moves, boxPct)
            float pHi = array.percentile_linear_interpolation(moves, 100 - boxPct)
            int   bLo = math.round(array.percentile_linear_interpolation(bars, boxPct))
            int   bHi = math.round(array.percentile_linear_interpolation(bars, 100 - boxPct))
            int   bx1 = priceOnly ? ax : math.min(ax + bLo, maxX - 1)
            int   bx2 = priceOnly ? rightX : math.min(math.max(ax + bHi, bx1 + 1), maxX)
            float yA  = ay + sgn * pLo
            float yB  = ay + sgn * pHi
            string bTxt = showBoxLbl ? "P" + str.tostring(boxPct) + "–P" + str.tostring(100 - boxPct) : ""
            array.push(projBoxes, box.new(bx1, math.max(yA, yB), bx2, math.min(yA, yB),
                 border_color=color.new(clr, math.max(0, boxTransp - 40)), border_width=1,
                 bgcolor=color.new(clr, boxTransp), text=bTxt, text_size=size.small,
                 text_color=txtClr, text_halign=text.align_right, text_valign=up ? text.align_top : text.align_bottom))
        // Median vector: median move size over median duration
        if showMedian
            float mMv = array.median(moves)
            int   mNb = math.max(1, math.round(array.median(bars)))
            float mT  = ay + sgn * mMv
            int   mx  = priceOnly ? rightX : ax + mNb
            float my  = mT
            if not priceOnly and mx > maxX
                my := ay + sgn * mMv * (maxX - ax) / mNb
                mx := maxX
            array.push(projLines, line.new(ax, priceOnly ? mT : ay, mx, my, color=color.new(clr, 0), width=medWidth))
            if showMedLbl
                string pct = mMv > 0 ? str.tostring(math.round(extent / mMv * 100)) + "%" : "-"
                string txt = "med " + f_delta(mMv) + (priceOnly ? "" : " • " + str.tostring(mNb) + " bars") + " • now " + pct
                array.push(projLabels, label.new(mx, my, txt, style=label.style_label_left, color=transpClr, textcolor=txtClr, size=size.normal,
                     tooltip="Median of the last " + str.tostring(n) + " moves. 'now' = percentage of the median move already completed from this starting point."))
 
// =====================================================================
// SWING TRACKING
// Live zigzag: A = start of the current leg, B = its most recent extreme.
// =====================================================================
type Swing
    float pA
    int   iA
    int   tA
    float pB
    int   iB
    int   tB
    bool  up    // true = leg up (A low -> B high)
 
// Completes the current leg A -> B, records it, and starts a new leg from B to (p, i, t).
method startFromB(Swing s, float p, int i, int t) =>
    mv = math.abs(s.pB - s.pA)
    if mv > 0
        if s.up
            f_record(movesUp, barsUp, timeUp, histUpL, histUpLb, mv, s.tA, true, s.iA, s.pA, s.iB, s.pB, true)
        else
            f_record(movesDown, barsDown, timeDown, histDownL, histDownLb, mv, s.tA, true, s.iA, s.pA, s.iB, s.pB, false)
    s.pA := s.pB
    s.iA := s.iB
    s.tA := s.tB
    s.pB := p
    s.iB := i
    s.tB := t
    s.up := not s.up
 
// Handles a pivot confirmed inside the current leg (between A and B).
// In a steady trend a lower high (or higher low) is confirmed only 'Pivot Length' bars later,
// after price has already made a new extreme. The leg A -> B is then split into A -> X -> Y -> B,
// where X is the extreme between A and the pivot, and Y is the opposite extreme between X and B.
method splitLeg(Swing s, int pBar) =>
    float bP = s.pB
    int   bI = s.iB
    int   bT = s.tB
    [xp, xi, xt] = f_extreme(bar_index - pBar + 1, bar_index - s.iA - 1, s.up)
    if not na(xp) and (s.up ? xp > s.pA : xp < s.pA)
        [yp, yi, yt] = f_extreme(bar_index - bI + 1, bar_index - xi - 1, not s.up)
        if not na(yp)
            s.pB := xp
            s.iB := xi
            s.tB := xt
            s.startFromB(yp, yi, yt)
            s.startFromB(bP, bI, bT)
 
var Swing sw = Swing.new(low, bar_index, time, high, bar_index, time, true)
 
// Confirmed pivot high
if isNewPH
    if sw.up and sw.iB < pivotBar
        // Two consecutive highs: insert the lowest low between them, then the leg up to the highest high since
        [lp, li, lt] = f_extreme(bar_index - pivotBar + 1, bar_index - sw.iB - 1, false)
        if not na(lp)
            sw.startFromB(lp, li, lt)
            [hp, hi, ht] = f_extreme(0, bar_index - li - 1, true)
            if not na(hp)
                sw.startFromB(hp, hi, ht)
                // Price may already have broken below the inserted low
                [lp2, li2, lt2] = f_extreme(0, bar_index - sw.iB - 1, false)
                if not na(lp2) and lp2 < sw.pA
                    sw.startFromB(lp2, li2, lt2)
    else if not sw.up and pivotBar > sw.iB
        // High after the current swing low: a new leg up begins
        [hp, hi, ht] = f_extreme(0, bar_index - sw.iB - 1, true)
        if not na(hp)
            sw.startFromB(hp, hi, ht)
    else if not sw.up and pivotBar > sw.iA and pivotBar < sw.iB
        // Lower high inside the current leg down: split the leg
        sw.splitLeg(pivotBar)
 
// Confirmed pivot low
if isNewPL
    if not sw.up and sw.iB < pivotBar
        // Two consecutive lows: insert the highest high between them, then the leg down to the lowest low since
        [hp, hi, ht] = f_extreme(bar_index - pivotBar + 1, bar_index - sw.iB - 1, true)
        if not na(hp)
            sw.startFromB(hp, hi, ht)
            [lp, li, lt] = f_extreme(0, bar_index - hi - 1, false)
            if not na(lp)
                sw.startFromB(lp, li, lt)
                // Price may already have broken above the inserted high
                [hp2, hi2, ht2] = f_extreme(0, bar_index - sw.iB - 1, true)
                if not na(hp2) and hp2 > sw.pA
                    sw.startFromB(hp2, hi2, ht2)
    else if sw.up and pivotBar > sw.iB
        // Low after the current swing high: a new leg down begins
        [lp, li, lt] = f_extreme(0, bar_index - sw.iB - 1, false)
        if not na(lp)
            sw.startFromB(lp, li, lt)
    else if sw.up and pivotBar > sw.iA and pivotBar < sw.iB
        // Higher low inside the current leg up: split the leg
        sw.splitLeg(pivotBar)
 
// Live update on the current bar.
// For bars that break both sides, a bullish candle is assumed to print its low first, then its high (bearish: the reverse).
bool isGreen = close >= open
for step = 0 to 1
    bool doLow = isGreen ? step == 0 : step == 1
    if doLow
        if not sw.up and low < sw.pB
            sw.pB := low
            sw.iB := bar_index
            sw.tB := time
        else if sw.up and low < sw.pA
            sw.startFromB(low, bar_index, time)     // swing low broken: the leg up ends, a leg down begins
    else
        if sw.up and high > sw.pB
            sw.pB := high
            sw.iB := bar_index
            sw.tB := time
        else if not sw.up and high > sw.pA
            sw.startFromB(high, bar_index, time)    // swing high broken: the leg down ends, a leg up begins
 
// =====================================================================
// PROJECTIONS (redrawn on the last bar)
// =====================================================================
if barstate.islast
    while array.size(projBoxes) > 0
        box.delete(array.pop(projBoxes))
    while array.size(projLines) > 0
        line.delete(array.pop(projLines))
    while array.size(projLabels) > 0
        label.delete(array.pop(projLabels))
 
    // Targets in the direction of the current leg start from its origin (A);
    // targets in the opposite direction start from its latest extreme (B).
    if showUpFan
        f_fan(movesUp, barsUp, timeUp, sw.up ? sw.iA : sw.iB, sw.up ? sw.pA : sw.pB, true, upClr)
    if showDnFan
        f_fan(movesDown, barsDown, timeDown, sw.up ? sw.iB : sw.iA, sw.up ? sw.pB : sw.pA, false, downClr)

← 返回列表