Pullback Analyzer

StefanReich · study · 234 行 · 点赞 797 · TradingView 原页

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

Pine Script

// Pullback Analyzer - a trailing stop helper
 
// This indicator measures the biggest pullback encountered during an up or down move.
// You can use the reported percentages to fine-tune your trailing stop.
 
// The reporting is very precise: On higher timeframes, the pullback size cannot be determined exactly from the candles.
// In this case, the script displays a lower and upper bound for this number.
// I suggest that you use the upper bound as your trailing stop callback rate to be sure.
 
// The size of the move itself is always reported as a lower bound.
 
// There is only one parameter, "lookback", which determines how many bars a single move can comprise.
 
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © StefanReich
 
//@version=5
indicator("Pullback Analyzer", overlay=true, max_labels_count = 500, max_lines_count = 500)
 
lookback = input.int(50, minval=5, step=5, tooltip="How many bars to look back when finding moves")
 
vmargin = 1.005 // Vertical margin between labels and candles (0.5%)
 
// add fields here to stay backwards-compatible
 
// extended max/min functions
 
// Extensions of math.min and math.max which, unlike those functions, allow either of the parameters
// to be na (then the other parameter is returned). It's even okay if both parameters are na.
 
maxAllowingNA(float a, float b) => na(a) ? (na(b) ? na : b) : (na(b) ? a : math.max(a, b))
minAllowingNA(float a, float b) => na(a) ? (na(b) ? na : b) : (na(b) ? a : math.min(a, b))
 
// math.min and math.max, but with a direction argument (=invertable).
//
// If direction > 0, the functions behave like minAllowingNA and maxAllowingNA.
// If direction < 0, each function becomes its inverse - min becomes max and max becomes min.
// Result is undefined for direction == 0.
 
directionalMinAllowingNA(float direction, float a, float b) => direction < 0 ? maxAllowingNA(a, b) : minAllowingNA(a, b)
directionalMaxAllowingNA(float direction, float a, float b) => direction < 0 ? minAllowingNA(a, b) : maxAllowingNA(a, b)
 
// Representation of a single move or pullback
// (i.e. a start point and an end point)
type Move
    int startBar      // Bar where move starts (bar index)
    float startPrice  // Price at beginning of move
    int endBar        // Bar where move ends (bar index, inclusive)
    float endPrice    // Price at end of move
 
// Calculate size of move in percent - positive for up moves, negative for down moves
moveSize(Move move) => na(move) ? 0 : (move.endPrice/move.startPrice-1)*100
 
// Draw move as a dotted or solid line with a specified color. Transparency 30% is added.
// Supplying na is okay. Returns the line drawn.
drawMove(Move move, color color, bool dotted) =>
    if not na(move)
        style = dotted ? line.style_dotted : line.style_solid
        line.new(move.startBar, move.startPrice, move.endBar, move.endPrice, xloc.bar_index, style=style, width=4, color=color.new(color, 30))
 
// Convert direction (negative or positive float) to color (red/green)
 
directionToColor(direction) => direction > 0 ? color.green : color.red
 
// MoveFinder - the algorithm's main class that detects moves in a certain direction.
// There are 2 main MoveFinders (upFinder and downFinder).
// Each of these contains 2 nested MoveFinders that detect the pullbacks (pbFinder_lb and pbFinder_ub).
// This way, we can use the same core algorithm for the moves and the pullbacks.
// The MoveFinder remembers both
// -biggestMove - the biggest move found in the lookback interval, and
// -the current move (the biggest move out of all moves which end in the current candle), stored in startBar and startPrice.
 
type MoveFinder
    int direction               // 1 for detecting up moves, -1 for detecting down moves
    bool useUpperBound = false  // If true, we report the move size as an upper bound (otherwise a lower bound)
    int startBar                // First bar of current biggest move
    float startPrice            // Starting price of current biggest move
    Move biggestMove            // Current biggest move as an objecvt
    Move biggestPB_lb           // Current biggest pullback within biggestMove (calculated as lower bound)
    Move biggestPB_ub           // Current biggest pullback within biggestMove (calculated as upper bound)
 
    MoveFinder pbFinder_lb      // A MoveFinder object used to find pullbacks (lower bound), unless we are already in a pullback MoveFinder (then na)
    MoveFinder pbFinder_ub      // Same for upper bound
 
    // Visualization
    label label                 // Label for current move (so it can be updated)
    line line                   // Red/green move line for current move (so it can be updated)
    line pbLine                 // Dotted pullback line for current move (so it can be updated)
 
// Called when a new biggest move is found, for one of those reasons:
// -it's the first move found
// -the current move is the biggest move and has changed or grown
// -the current move is bigger than the previously biggest move and it replaces it
method setBiggestMove(MoveFinder this, Move m) =>
    // Start bar of previously biggest move
    start = na(this.biggestMove) ? na : this.biggestMove.startBar
 
    // Save as biggestMove
    this.biggestMove := m
 
    // If it's a different move (evidenced by a different start bar),
    // we throw away the pullback finders and create new ones for the new move.
    if m.startBar != start
        this.pbFinder_lb := MoveFinder.new(-this.direction, false)
        this.pbFinder_ub := MoveFinder.new(-this.direction, true)
 
    // Grab pullbacks from pullback finders
    if not na(this.pbFinder_lb)
        this.biggestPB_lb := this.pbFinder_lb.biggestMove
        this.biggestPB_ub := this.pbFinder_ub.biggestMove
 
    0 // Just to keep the parser happy (consistent return type)
 
// Update a MoveFinder with the latest candle (core function). Does not update the nested pullback finders.
method updateCore(MoveFinder this) =>
    d = this.direction // We will need the direction a lot, so we call it "d". So d is 1 (finding up moves) or -1 (finding down moves)
 
    // The end of the current candle's wick that is furthest in the move direction
    extreme = d > 0 ? high : low
 
    // Find the end of the current candle that is lowest in an up move (or highest in a down mvoe)
    otherExtreme = d > 0 ? low : high
 
    // Replace start price of current move with current candle's open if this enlarges the move
    start = directionalMinAllowingNA(d, this.startPrice, open)
 
    // true if this candle's wicks change the move's start price
    newLow = na(this.startPrice) or d*otherExtreme < d*this.startPrice
 
    // Begin move here if there is no move yet
    bar1 = nz(this.startBar, bar_index)
 
    // If we are in "upper bound" mode, we assume that the current candle touched its low first and then its high in an up move,
    // or its high first and then its low in a down move. This way, we get the biggest move size compatible with the candle.
    // (This distinction is necessary to handle historic candles properly without the help of realtime bars.)
    if this.useUpperBound and newLow
        start := otherExtreme
        bar1 := bar_index
 
    // Calculate new move size including current candle
    move = d*(extreme/start-1)*100
 
    // Is it the new biggest move? Then replace biggestMove.
    if move > moveSize(this.biggestMove)*d
        this.setBiggestMove(Move.new(bar1, start, bar_index, extreme))
 
    // Use current candle as new move start if its wick is further back in the move direction
    if newLow
        this.startBar := bar_index
        this.startPrice := otherExtreme
 
// Prepare MoveFinder for a new move (reset all fields)
method flush(MoveFinder this) =>
    this.biggestMove := na
    this.biggestPB_lb := na
    this.biggestPB_ub := na
    this.startBar := na
    this.startPrice := na
    this.pbFinder_lb := MoveFinder.new(-this.direction, false)
    this.pbFinder_ub := MoveFinder.new(-this.direction, true)
    this.label := na
    this.line := na
    this.pbLine := na
 
// Display the current move, replacing its previous visualization if necessary
method showMove(MoveFinder this) =>
    move = this.biggestMove
    if not na(move) // Check if there is a move to display
        // Delete the move's exiting visualization (if any)
        label.delete(this.label)
        line.delete(this.line)
        line.delete(this.pbLine)
 
        // Calculate colors, draw move line
        color = directionToColor(this.direction)
        pbColor = directionToColor(-this.direction)
        this.line := drawMove(move, color, false)
 
        // Show the pullback
        pb = this.biggestPB_lb
        if not na(pb)
            //drawMove(pb, pbColor, true) // Use this to draw the pullback as a slanted line (hard to see though)
 
            // Display pullback as dotted line at a small distance from candle
            y = pb.endPrice/math.pow(vmargin, this.direction)
            this.pbLine := line.new(pb.startBar, y, pb.endBar, y, width=2, color=color.gray, style=line.style_dotted)
 
        // Render the label text
        pb_lb = str.tostring(math.abs(moveSize(this.biggestPB_lb)), "0.00") // Pullback size lower bound
        pb_ub = str.tostring(math.abs(moveSize(this.biggestPB_ub)), "0.00") // Pullback size upper bound
 
        pbExact = pb_lb == pb_ub // true if lower and upper bound are identical
        pbText = pbExact ? pb_lb : pb_lb + "%-" + pb_ub // Combine lower and upper bound as text
        moveSize = str.tostring(math.abs(moveSize(move)), "0.0") + "%" // Move size as text
        txt = (this.direction > 0 ? "+" : "-") + moveSize + " (pb " + pbText + "%)"
        moveKind = this.direction > 0 ? "upmove" : "downmove"
        tooltip = "A " + moveSize + " " + moveKind + " occurred with a maximum pullback"
          + (pbExact ? " of " + pb_lb + "% (marked with gray dots)" : " between " + pb_lb + "% and " + pb_ub + "%\n(go to lower timeframe for a more precise reading)")
 
        // Create label pointing to end of move
        this.label := label.new(move.endBar, move.endPrice*math.pow(vmargin, this.direction), txt, tooltip=tooltip,
          style=(this.direction > 0 ? label.style_label_down : label.style_label_up),
          color=color, textcolor=color.white)
 
// Flush (end) the current move when lookback limit is reached.
method enforceLookback(MoveFinder this) =>
    if not na(this.biggestMove)
        if this.biggestMove.startBar <= bar_index-lookback
            this.flush()
 
// Update a MoveFinder with the latest candle (wrapper function). Also updates the nested pullback finders, if any.
method update(MoveFinder this) =>
    // Update the pullback finders
    if not na(this.pbFinder_lb) // If we have one, we also have the other
        this.pbFinder_lb.updateCore()
        this.pbFinder_ub.updateCore()
 
    // Update the move finder itself
    this.updateCore()
 
    // Update visualization
    this.showMove()
 
    // End move if lookback limit reached
    this.enforceLookback()
 
// The main MoveFinders, one for each direction.
// Note how the 2 embedded MoveFinders have opposite direction so they can find pullbacks.
var MoveFinder upFinder = MoveFinder.new(1, pbFinder_lb=MoveFinder.new(-1), pbFinder_ub=MoveFinder.new(-1))
var MoveFinder downFinder = MoveFinder.new(-1, pbFinder_lb=MoveFinder.new(1), pbFinder_ub=MoveFinder.new(1))
 
// Update the move finders (and nested pullback finders)
upFinder.update()
downFinder.update()

← 返回列表