Typical Move Zones

getphantomflow · study · 389 行 · 点赞 200 · TradingView 原页

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

Pine Script

//@version=6
indicator("Typical Move Zones", shorttitle = "Typical Move", overlay = true, behind_chart = false, max_lines_count = 200, max_labels_count = 80)
 
// How it works
// 1. A turning point is a bar whose high (or low) is the most extreme of the bars on both sides of it.
// 2. A move is the distance between two neighboring turning points, as a percent of where it started.
// 3. From the latest turning point a zone is drawn in the direction of the move in progress.
//    Its near edge is the median size of recent moves in that direction ("Typical"): about half ended before it.
//    Its far edge is their 80th percentile ("Stretched"): about 1 in 5 went past it.
// A turning point is only known a few bars after it happens, so the zone appears after the turn, never on it.
// If price trades back through the latest turning point, the move before it did not end there.
// It is measured again from its own start. If the next opposite turning point comes after that break,
// the move is recorded as ending at the furthest price it reached.
// The zone describes what recent moves did. It does not say what the next one will do.
 
const string G_MOVES   = "Moves"
const string G_LOOK    = "Look"
const int    MIN_MOVES = 5
const int    BANDS     = 5    // steps in the zone's fade
const int    METER     = 8    // segments in the summary box meter
const int    AHEAD     = 8    // bars the zone runs past the latest bar
 
string turnInput   = input.string("Medium", "Turn size", options = ["Small", "Medium", "Large"], group = G_MOVES, display = display.none, tooltip = "How clear a turn must be to count. Small catches short swings, Large only the big ones.")
int    sampleInput = input.int(20, "Moves to measure", minval = 8, maxval = 60, group = G_MOVES, display = display.none, tooltip = "How many recent moves in each direction the zone is based on.")
bool   pathInput   = input.bool(true, "Show measured moves", group = G_LOOK, display = display.none, tooltip = "Draws a line through the turning points, so you can see the moves being measured.")
bool   sizesInput  = input.bool(true, "Show move sizes", group = G_LOOK, display = display.none, tooltip = "Tags each finished move with its size, at the turning point where it ended.")
bool   boxInput    = input.bool(true, "Show summary box", group = G_LOOK, display = display.none, tooltip = "The box with the size of the move in progress.")
string boxPosInput = input.string("Auto", "Summary box position", options = ["Auto", "Top right", "Bottom right", "Bottom left"], group = G_LOOK, active = boxInput, display = display.none, tooltip = "Auto puts the box on the right, away from the zone.")
color  upInput     = input.color(#22B892, "Up moves", group = G_LOOK, display = display.none)
color  downInput   = input.color(#F0566A, "Down moves", group = G_LOOK, display = display.none)
 
pct(float value) =>
    str.tostring(value, value < 0.1 ? "0.000" : "0.00") + "%"
 
// A solid tint of a color on the chart background, so tags stay readable over candles.
tint(color base, int strength) =>
    color.from_gradient(strength, 0, 100, chart.bg_color, base)
 
// The color pulled towards the chart's text color, for small text on either theme.
ink(color base) =>
    color.from_gradient(45, 0, 100, base, chart.fg_color)
 
// A size tag is a tinted pill. It is hidden while its turning point no longer marks the end of a move.
dress(label tag, color base, bool hidden) =>
    label.set_color(tag, hidden ? color.new(base, 100) : tint(base, 18))
    label.set_textcolor(tag, hidden ? color.new(base, 100) : ink(base))
 
// The newest sizes in a list, up to the number being measured, leaving out its last skip entries.
recent(array<float> moves, int skip) =>
    int          stop   = moves.size() - skip
    array<float> picked = array.new<float>()
    if stop > 0
        picked := moves.slice(math.max(stop - sampleInput, 0), stop)
    picked
 
// Typical and Stretched sizes of a list of moves, and how many of them ended before one and went past the other.
measure(array<float> moves) =>
    float near   = moves.median()
    float far    = moves.percentile_linear_interpolation(80)
    int   before = 0
    int   past   = 0
    for move in moves
        if move < near
            before += 1
        if move > far
            past += 1
    [near, far, before, past]
 
// One summary box cell on the panel color, merged across to lastCol.
put(table box, int col, int row, int lastCol, string txt, color txtColor, string align, bool bold, color panel) =>
    table.cell(box, col, row, txt, text_color = txtColor, text_size = size.small, text_halign = align, text_formatting = bold ? text.format_bold : text.format_none, bgcolor = panel)
    if lastCol > col
        table.merge_cells(box, col, row, lastCol, row)
 
int len = switch turnInput
    "Small" => 5
    "Large" => 20
    => 10
 
float ph       = ta.pivothigh(high, len, len)
float pl       = ta.pivotlow(low, len, len)
int   pivotBar = bar_index - len
 
// The latest turning point and the one before it.
var int   lastType  = 0   // 1: the latest turn was a high. -1: it was a low. 0: none yet.
var float lastPrice = na
var int   lastBar   = na
var float prevPrice = na
var int   prevBar   = na
var int   turnBar   = na  // the bar on which the latest turning point was confirmed
 
// Sizes of finished moves, in percent of the price they started from. Each list keeps one more than is measured,
// so a move that turns out to be still running can be left out without shrinking the sample.
var array<float> upMoves   = array.new<float>()
var array<float> downMoves = array.new<float>()
 
var array<line>  path  = array.new<line>()
var array<label> sizes = array.new<label>()
 
// The zone of the move in progress.
var float nearPct     = na
var float farPct      = na
var int   endedBefore = 0     // moves in the measured list that ended before the Typical line
var int   wentPast    = 0     // moves in the measured list that went past the Stretched line
var float zoneNear    = na
var float zoneFar     = na
var float extreme     = na
var int   extremeBar  = na
var bool  resumed     = false // price went back through the latest turning point: the move before it is still running
var bool  lost        = false // price also went back through the start of that move: nothing to measure until the next turn
var bool  saidNear    = false
var bool  saidFar     = false
 
// What was known on the bar the new turning point sits on. If the latest turning point was already broken by then,
// the move before it really ended at the furthest price it had reached.
bool  brokenThen  = not na(turnBar) and pivotBar >= turnBar and resumed[len]
float furthest    = extreme[len]
int   furthestBar = extremeBar[len]
 
// One bar can be both a high and a low turn. Keep the side that extends the latest turning point; if it does not, take the other.
int kind = 0
if not na(ph) and not na(pl)
    kind := lastType == -1 ? (pl < lastPrice ? -1 : 1) : lastType == 1 ? (ph > lastPrice ? 1 : -1) : 1
else if not na(ph)
    kind := 1
else if not na(pl)
    kind := -1
float turnPrice = kind == 1 ? ph : pl
 
bool turned  = false   // a turning point was confirmed on this bar, or replaced by a more extreme one
bool newMove = false   // the turning point is of the opposite kind: one move ended and another began
bool shifted = false   // the turning point before it was moved to the furthest price the broken move reached
 
if kind != 0 and turnPrice > 0
    if kind == lastType
        // Same kind as the latest turning point: it only counts if it is more extreme, and then replaces it.
        if kind * (turnPrice - lastPrice) > 0
            lastPrice := turnPrice
            lastBar   := pivotBar
            turned    := true
            array<float> same = kind == 1 ? upMoves : downMoves
            if not na(prevPrice) and same.size() > 0
                same.set(same.size() - 1, math.abs(turnPrice - prevPrice) / prevPrice * 100)
    else
        float fromPrice = brokenThen ? furthest : lastPrice
        int   fromBar   = brokenThen ? furthestBar : lastBar
        if lastType == 0 or kind * (turnPrice - fromPrice) > 0
            if lastType != 0
                if brokenThen
                    array<float> earlier = kind == 1 ? downMoves : upMoves
                    if not na(prevPrice) and earlier.size() > 0
                        earlier.set(earlier.size() - 1, math.abs(fromPrice - prevPrice) / prevPrice * 100)
                    shifted := true
                array<float> ending = kind == 1 ? upMoves : downMoves
                ending.push(math.abs(turnPrice - fromPrice) / fromPrice * 100)
                if ending.size() > sampleInput + 1
                    ending.shift()
                newMove := true
            prevPrice := fromPrice
            prevBar   := fromBar
            lastPrice := turnPrice
            lastBar   := pivotBar
            lastType  := kind
            turned    := true
 
if turned
    resumed := false
    lost    := false
    turnBar := bar_index
 
int   dir    = resumed ? lastType : -lastType   // direction of the move in progress
float origin = lost ? na : resumed ? prevPrice : lastPrice   // the price it started from
 
if turned
    array<float> endedMoves = lastType == 1 ? upMoves : downMoves
    array<float> priorMoves = lastType == 1 ? downMoves : upMoves
    color        endedColor = lastType == 1 ? upInput : downInput
    color        priorColor = lastType == 1 ? downInput : upInput
    string       endedText  = (lastType == 1 ? "+" : "-") + pct(endedMoves.size() > 0 ? endedMoves.last() : na)
    if newMove
        // The move before this one: its tag is shown again, and if it ended further out than first drawn, its line and tag move there.
        if sizesInput and sizes.size() > 0
            dress(sizes.last(), priorColor, false)
        if shifted
            if pathInput and path.size() > 0
                line.set_xy2(path.last(), prevBar, prevPrice)
            if sizesInput and sizes.size() > 0 and priorMoves.size() > 0
                label.set_xy(sizes.last(), prevBar, prevPrice)
                label.set_text(sizes.last(), (lastType == 1 ? "-" : "+") + pct(priorMoves.last()))
        if pathInput
            path.push(line.new(prevBar, prevPrice, lastBar, lastPrice, color = color.new(endedColor, 45), width = 2))
            if path.size() > 80
                line.delete(path.shift())
        if sizesInput
            sizes.push(label.new(lastBar, lastPrice, endedText, style = lastType == 1 ? label.style_label_down : label.style_label_up, color = tint(endedColor, 18), textcolor = ink(endedColor), size = size.small))
            if sizes.size() > 40
                label.delete(sizes.shift())
    else if not na(prevPrice)
        // A more extreme turn of the same kind: the line and the tag of the move that ended here move with it.
        if pathInput and path.size() > 0
            line.set_xy2(path.last(), lastBar, lastPrice)
        if sizesInput and sizes.size() > 0
            label.set_xy(sizes.last(), lastBar, lastPrice)
            label.set_text(sizes.last(), endedText)
            dress(sizes.last(), endedColor, false)
 
    // The zone of the move that starts here.
    array<float> sample = recent(dir == 1 ? upMoves : downMoves, 0)
    if sample.size() >= MIN_MOVES
        [near, far, before, past] = measure(sample)
        nearPct     := near
        farPct      := far
        endedBefore := before
        wentPast    := past
        zoneNear    := lastPrice * (1 + dir * nearPct / 100)
        zoneFar     := lastPrice * (1 + dir * farPct / 100)
    else
        nearPct  := na
        farPct   := na
        zoneNear := na
        zoneFar  := na
 
    // The bars since the turning point have already traded. Find how far they went.
    extreme    := lastPrice
    extremeBar := lastBar
    for i = bar_index - lastBar - 1 to 0
        if dir == 1 ? high[i] > extreme : low[i] < extreme
            extreme    := dir == 1 ? high[i] : low[i]
            extremeBar := bar_index - i
    saidNear := false
    saidFar  := false
else if lastType != 0
    if not resumed and (dir == 1 ? low < lastPrice : high > lastPrice)
        // Price went back through the latest turning point, so the move before it did not end there.
        // If the move in progress had already passed the start of that earlier move, there is no clean start to measure from.
        bool overran = not na(prevPrice) and (dir == 1 ? extreme > prevPrice : extreme < prevPrice)
        resumed := true
        lost    := overran
        dir     := lastType
        origin  := overran ? na : prevPrice
        array<float> sameWay = dir == 1 ? upMoves : downMoves
        array<float> others  = recent(sameWay, 1)   // the moves it was measured against while it ran
        if not na(origin) and others.size() >= MIN_MOVES
            [near, far, before, past] = measure(others)
            nearPct     := near
            farPct      := far
            endedBefore := before
            wentPast    := past
            zoneNear    := origin * (1 + dir * nearPct / 100)
            zoneFar     := origin * (1 + dir * farPct / 100)
            saidNear    := dir == 1 ? lastPrice >= zoneNear : lastPrice <= zoneNear
            saidFar     := dir == 1 ? lastPrice >= zoneFar : lastPrice <= zoneFar
        else
            nearPct  := na
            farPct   := na
            zoneNear := na
            zoneFar  := na
        extreme    := dir == 1 ? high : low
        extremeBar := bar_index
        // The size tag at the broken turning point no longer marks the end of its move, so it is hidden.
        if sizesInput and sizes.size() > 0
            dress(sizes.last(), dir == 1 ? upInput : downInput, true)
    if resumed and not lost and not na(origin) and (dir == 1 ? low < origin : high > origin)
        lost   := true
        origin := na
    if dir == 1 ? high > extreme : low < extreme
        extreme    := dir == 1 ? high : low
        extremeBar := bar_index
 
bool live        = lastType != 0 and not na(origin) and not na(zoneNear)
bool reachedNear = live and (dir == 1 ? extreme >= zoneNear : extreme <= zoneNear)
bool reachedFar  = live and (dir == 1 ? extreme >= zoneFar : extreme <= zoneFar)
 
// Alerts fire once per move, on a closed bar that is at or past the line.
bool alertNear = false
bool alertFar  = false
if barstate.isconfirmed and live
    if not saidNear and (dir == 1 ? high >= zoneNear : low <= zoneNear)
        saidNear  := true
        alertNear := true
    if not saidFar and (dir == 1 ? high >= zoneFar : low <= zoneFar)
        saidFar  := true
        alertFar := true
 
alertcondition(turned and barstate.isconfirmed, "Turning point confirmed", "{{ticker}} {{interval}}: a turning point was confirmed. The zone was redrawn.")
alertcondition(alertNear, "Move reached the typical line", "{{ticker}} {{interval}}: the move in progress reached its typical size.")
alertcondition(alertFar, "Move reached the stretched line", "{{ticker}} {{interval}}: the move in progress reached the stretched line.")
 
// The zone of the move in progress, redrawn on the latest bar.
var array<line>     zoneEdges = array.new<line>()
var array<linefill> zoneBands = array.new<linefill>()
var line            legLine   = na
var label           nearLabel = na
var label           farLabel  = na
var table           box       = na
 
if barstate.islast
    for band in zoneBands
        linefill.delete(band)
    for zoneEdge in zoneEdges
        line.delete(zoneEdge)
    zoneBands.clear()
    zoneEdges.clear()
    line.delete(legLine)
    label.delete(nearLabel)
    label.delete(farLabel)
 
    color        moveColor = dir == 1 ? upInput : downInput
    string       moveWord  = dir == 1 ? "up" : "down"
    array<float> measured  = recent(dir == 1 ? upMoves : downMoves, resumed ? 1 : 0)
    int          counted   = measured.size()
 
    // Past the Stretched line the zone is behind price, so it is not drawn.
    if live and not reachedFar
        int left  = resumed ? prevBar : lastBar   // the bar the move started on
        int right = bar_index + AHEAD
        // The zone sits ahead of the latest bar and fades from the Typical line to the Stretched line.
        for step = 0 to BANDS
            float level = zoneNear + (zoneFar - zoneNear) * step / BANDS
            color tone  = step == 0 ? color.new(moveColor, 10) : step == BANDS ? color.new(moveColor, 35) : color.new(moveColor, 100)
            zoneEdges.push(line.new(bar_index, level, right, level, color = tone, style = step == BANDS ? line.style_dashed : line.style_solid))
            if step > 0
                zoneBands.push(linefill.new(zoneEdges.get(step - 1), zoneEdges.get(step), color.new(moveColor, 58 + step * 7)))
        // Two thin lines lead back to where the move started.
        zoneEdges.push(line.new(left, zoneNear, bar_index, zoneNear, color = color.new(moveColor, 60)))
        zoneEdges.push(line.new(left, zoneFar, bar_index, zoneFar, color = color.new(moveColor, 60), style = line.style_dashed))
 
        // Tags sit past the latest bar and outside the zone: Typical on the side price comes from, Stretched on the far side.
        string sampleText = " of the last " + str.tostring(counted) + " " + moveWord + " moves "
        nearLabel := label.new(right, zoneNear, "Typical", style = dir == 1 ? label.style_label_upper_right : label.style_label_lower_right, color = moveColor, textcolor = #0B1410, size = size.small, tooltip = "Typical: " + str.tostring(zoneNear, format.mintick) + "\n" + str.tostring(endedBefore) + sampleText + "ended before this line.")
        farLabel  := label.new(right, zoneFar, "Stretched", style = dir == 1 ? label.style_label_lower_right : label.style_label_upper_right, color = tint(moveColor, 22), textcolor = ink(moveColor), size = size.small, tooltip = "Stretched: " + str.tostring(zoneFar, format.mintick) + "\n" + str.tostring(wentPast) + sampleText + "went past this line.")
 
    // The move so far, from the latest turning point to its furthest price.
    if pathInput and lastType != 0 and not na(origin) and extremeBar > lastBar
        legLine := line.new(lastBar, lastPrice, extremeBar, extreme, color = moveColor, width = 2, style = line.style_dotted)
 
    table.delete(box)
    if boxInput
        string where = switch boxPosInput
            "Top right"    => position.top_right
            "Bottom right" => position.bottom_right
            "Bottom left"  => position.bottom_left
            => dir == 1 and not na(origin) ? position.bottom_right : position.top_right
        bool  atTop   = where == position.top_right
        color strong  = chart.fg_color
        color quiet   = color.new(chart.fg_color, 25)
        color panel   = tint(chart.fg_color, 5)
        int   split   = 5           // label columns; the value takes the rest
        int   lastCol = METER - 1
        box := table.new(where, METER, 7, border_color = panel, border_width = 2)
 
        // A blank row on the chart-edge side keeps the box clear of the chart's own price line and buttons.
        int spacer = atTop ? 0 : 6
        table.cell(box, 0, spacer, ".", text_color = color.new(strong, 100), text_size = size.large)
        table.merge_cells(box, 0, spacer, lastCol, spacer)
 
        if lastType == 0 or na(origin)
            put(box, 0, 1, lastCol, lastType == 0 ? "Finding turning points" : "Waiting for the next turning point", quiet, text.align_left, false, panel)
        else
            float soFar = math.abs(extreme - origin) / origin * 100
            put(box, 0, 1, split - 1, dir == 1 ? "Up move" : "Down move", ink(moveColor), text.align_left, true, panel)
            put(box, split, 1, lastCol, pct(soFar), strong, text.align_right, true, panel)
            table.cell_set_text_size(box, split, 1, size.normal)
 
            string status = ""
            if na(zoneNear)
                int needed = MIN_MOVES - counted
                status := "Needs " + str.tostring(needed) + " more " + moveWord + (needed == 1 ? " move" : " moves")
            else
                put(box, 0, 2, split - 1, "Typical", quiet, text.align_left, false, panel)
                put(box, split, 2, lastCol, pct(nearPct), strong, text.align_right, false, panel)
                put(box, 0, 3, split - 1, "Stretched", quiet, text.align_left, false, panel)
                put(box, split, 3, lastCol, pct(farPct), strong, text.align_right, false, panel)
 
                // Meter: how far the move has gone towards the Stretched line. The segments from Typical on are the zone.
                int filled    = math.round(math.min(soFar / farPct, 1) * METER)
                int typicalAt = math.round(nearPct / farPct * METER)
                for segment = 0 to lastCol
                    bool  inZone = segment >= typicalAt
                    color lit    = segment < filled ? (inZone ? moveColor : tint(moveColor, 60)) : (inZone ? tint(moveColor, 28) : tint(chart.fg_color, 12))
                    table.cell(box, segment, 4, "", bgcolor = lit, height = 1.4)
 
                int smaller = 0
                for move in measured
                    if move < soFar
                        smaller += 1
                status := reachedFar ? "Bigger than " + str.tostring(smaller) + " of the last " + str.tostring(counted) : reachedNear ? "Past typical size" : str.tostring(math.round(soFar / nearPct * 100)) + "% of a typical move"
 
            put(box, 0, 5, lastCol, status, quiet, text.align_left, false, panel)

← 返回列表