Obvious Trend v3.2

RaymondChia · study · 186 行 · 点赞 22 · TradingView 原页

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

Pine Script

//@version=6
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © RaymondChia
// ============================================================================
// Obvious Trend v3.2 - one clean view of trend direction
// ============================================================================
// VERSION
//   v3.2 is the first public release. The calculations are unchanged from the earlier working version (v3.1); v3.2 adds this
//   documentation, the wording "trailing stop line" and the always-on information note on the chart.
//
// WHAT IT IS
//   Every candle is coloured green (Up), red (Down) or grey (Neutral), and one trailing reference line is drawn.
//   It simply measures the strength of upward or downward price movement. It is shown for information only:
//   it has NO predictive value and is not a forecast, a recommendation or investment advice.
//   Plain indicator: no orders, no strategy, no backtest and no performance figures.
//
// THE THREE TOOLS, AND THE JOB OF EACH
//   1. Two simple moving averages of the close (fast 10 bars, slow 30 bars)          -> the DIRECTION of the trend
//        Fast above slow: recent prices are above the longer-run average, so the trend points UP.
//        Fast below slow: the trend points DOWN.
//   2. Parabolic SAR (Wilder; start 0.005, step 0.005, maximum 0.05)                  -> where PRICE SITS against its trend
//        SAR below the close: price is holding above the SAR's trailing turning point, which points UP.
//        SAR above the close: it points DOWN. The low acceleration keeps the SAR calm (it flips less often).
//   3. ATR trailing stop (22-bar highest high / lowest low, minus / plus 3 x ATR(10)) -> a REFERENCE LINE only
//        It shows how far price would have to move against the latest Up / Down stretch to break it.
//        It never changes the colour, and it is not an instruction to trade.
//
// HOW THE THREE ARE COMBINED INTO ONE VIEW
//   Tools 1 and 2 each cast one vote, Up or Down. Only those two votes decide the candle colour:
//
//        averages  |  SAR   |  candle
//        Up        |  Up    |  GREEN  = Up
//        Down      |  Down  |  RED    = Down
//        Up        |  Down  |  GREY   = Neutral
//        Down      |  Up    |  GREY   = Neutral
//
//   Grey means the two measures disagree: the strength of the move is weakening (or has not yet built up).
//   It does NOT mean the trend has changed. A direction is shown only when both measures agree, so a
//   disagreement appears as grey instead of as a change of colour.
//   Tool 3 is worked out from the same bars and drawn for the latest Up or Down stretch only (see below).
//   It has no vote.
//
// THE TRAILING REFERENCE LINE (tool 3) IN DETAIL
//   One short horizontal blue line on the latest Up / Down stretch, with its price printed beside it.
//   Up stretch   : highest high of the last 22 bars minus 3 x ATR(10)   (a line below price)
//   Down stretch : lowest low of the last 22 bars plus 3 x ATR(10)      (a line above price)
//   It trails: while the trend continues a line below price never moves down and a line above price never
//   moves up. It starts afresh when the colour flips between Up and Down, or after a close beyond it.
//   The line ends on the last bar of that stretch and reaches a set number of bars left and right.
//   It does not depend on the SAR. A price can cross it: it is a level, not protection.
//
// TIME FRAMES
//   Everything is worked out on the chart's own bars: a daily chart gives the daily reading, a weekly chart
//   the weekly reading, and so on.
//
// LIMITS
//   - The reading of the current, unfinished bar can change until that bar closes.
//   - The first 30 bars of a chart have no reading.
//   - The colours describe how price has behaved. They say nothing about what it will do next.
//
// ORIGIN AND CREDITS - who did what, with thanks
//   Built only from public, textbook methods and written from their published formulas; no code of any other
//   indicator was used.
//   - Parabolic SAR and Average True Range (ATR): J. Welles Wilder Jr., "New Concepts in Technical Trading
//     Systems" (Trend Research, 1978). Both tools, and the acceleration-factor idea behind the SAR, are his.
//   - Volatility trailing stop (the highest high or lowest low of a look-back period, less or plus a multiple of
//     the ATR): the idea is credited to Chuck LeBeau, and it was popularised by Alexander Elder in "Come Into
//     My Trading Room" (John Wiley & Sons, 2002). The 22-bar look-back and the 3 x ATR multiple are commonly
//     published settings.
//   - Simple moving averages and the use of a fast and a slow average to read direction: long-standing public
//     methods of technical analysis with no single author.
//   - Pine Script(R) and the built-in functions ta.sma, ta.sar, ta.atr, ta.highest and ta.lowest: TradingView.
//     Pine Script is a trademark of TradingView, Inc.
//   - How the tools are combined (two votes decide the colour, the trailing line has none), the chosen settings
//     and this code: Obvious Trend.
//   The people named are credited for their methods only. This script is not endorsed by or affiliated with them.
// ============================================================================
indicator("Obvious Trend v3.2", overlay = true, max_lines_count = 100, max_labels_count = 50)
 
// ---------------- Inputs ----------------
gRule = "Trend rule"
fastLen  = input.int(10, "Fast moving average length (bars)", minval = 1, group = gRule)
slowLen  = input.int(30, "Slow moving average length (bars)", minval = 2, group = gRule)
sarStart = input.float(0.005, "SAR start acceleration", minval = 0.0005, maxval = 1.0, step = 0.0005, group = gRule, tooltip = "Parabolic SAR settings. The textbook default is 0.02 / 0.02 / 0.2. A lower acceleration keeps the SAR further from price and flips it less often. Default 0.005 / 0.005 / 0.05 was chosen so that candles are grey for a small share of the time (about 15% on a sample of US stocks).")
sarInc   = input.float(0.005, "SAR acceleration step", minval = 0.0005, maxval = 1.0, step = 0.0005, group = gRule)
sarMax   = input.float(0.05, "SAR maximum acceleration", minval = 0.01, maxval = 1.0, step = 0.01, group = gRule)
 
gLook = "Look"
colorBarsOn  = input.bool(true, "Colour the candles by trend", group = gLook, tooltip = "On: each candle takes the trend colour. This replaces the chart's own up / down candle colours while the indicator is on.")
upColor      = input.color(#1FA855, "Up", group = gLook, tooltip = "Green. On a light chart you may prefer a darker green such as #0B6B35.")
downColor    = input.color(#EF5350, "Down", group = gLook)
neutralColor = input.color(#8A90A0, "Neutral (grey = strength weakening, not a trend change)", group = gLook)
markersOn       = input.bool(false, "Show the Signal (SAR markers)", group = gLook, tooltip = "Off by default: only the coloured candles and the trailing stop line are shown.")
markersWidth    = input.int(2, "Signal marker size (1-5)", minval = 1, maxval = 5, group = gLook)
 
gMa = "Moving averages (drawn on the chart)"
maOn       = input.bool(false, "Show the two moving averages", group = gMa, tooltip = "Off by default. The averages still drive the trend colour when hidden.")
fastColor  = input.color(#FFA500, "Fast average colour", group = gMa)
slowColor  = input.color(#78AAFF, "Slow average colour", group = gMa)
maWidth    = input.int(1, "Average thickness (1-5)", minval = 1, maxval = 5, group = gMa)
 
gStop = "Trailing stop line (reference only)"
stopOn      = input.bool(true, "Show the trailing stop line", group = gStop)
stopAtrLen  = input.int(10, "ATR length (bars)", minval = 1, group = gStop, tooltip = "Standard Wilder ATR, as in ta.atr.")
stopLookback = input.int(22, "Highest high / lowest low lookback (bars)", minval = 2, group = gStop, tooltip = "Up stretch: stop = highest high of this many bars minus the multiple x ATR. Down stretch: lowest low of this many bars plus the multiple x ATR.")
stopMult    = input.float(3.0, "ATR multiple", minval = 0.5, maxval = 10.0, step = 0.1, group = gStop, tooltip = "Larger = the line sits further from price, smaller = closer.")
stopLeft    = input.int(2, "Line reaches left (bars)", minval = 0, maxval = 20, group = gStop, tooltip = "The line is drawn from this many bars before the last bar of the latest Up / Down stretch up to that bar.")
stopRight   = input.int(5, "Line reaches right past the stretch's last bar (bars)", minval = 0, maxval = 20, group = gStop)
stopTrail  = input.bool(true, "Trailing: the stop only tightens, never loosens", group = gStop, tooltip = "On: like a trailing stop, a long stop never moves down and a short stop never moves up while the trend continues. It restarts when the trend flips or after a close beyond the stop. Off: the stop follows the 22-bar high / low and the ATR freely.")
stopHideNeutral = input.bool(false, "Hide the trailing stop line while the latest reading is Neutral", group = gStop, tooltip = "Off: the line stays on the latest Up / Down stretch even after the candles turn grey.")
stopColor   = input.color(#3C82FF, "Trailing stop line colour", group = gStop)
stopWidth   = input.int(3, "Trailing stop line width", minval = 1, maxval = 5, group = gStop)
 
// ---------------- Trend reading ----------------
float fastMa  = ta.sma(close, fastLen)
float slowMa  = ta.sma(close, slowLen)
float sarVal  = ta.sar(sarStart, sarInc, sarMax)
float atrVal  = ta.atr(stopAtrLen)
float hiVal   = ta.highest(high, stopLookback)
float loVal   = ta.lowest(low, stopLookback)
 
bool  ready   = not na(fastMa) and not na(slowMa) and not na(sarVal) and bar_index >= slowLen
int   maDir   = fastMa > slowMa ? 1 : fastMa < slowMa ? -1 : 0
int   sarDir  = sarVal < close ? 1 : sarVal > close ? -1 : 0
int   trend   = ready and maDir != 0 and sarDir == maDir ? maDir : 0
 
color trendCol = trend == 1 ? upColor : trend == -1 ? downColor : neutralColor
 
// ---------------- Candle colours, Signal markers, averages ----------------
barcolor(colorBarsOn and ready ? trendCol : na, title = "Trend colour")
plot(markersOn and ready ? sarVal : na, "Signal", color = trendCol, style = plot.style_circles, linewidth = markersWidth)
plot(maOn ? fastMa : na, "Fast moving average", color = fastColor, linewidth = maWidth)
plot(maOn ? slowMa : na, "Slow moving average", color = slowColor, linewidth = maWidth)
 
// ---------------- Trailing stop line (tool 3) on the latest Up / Down stretch ----------------
// latest Up / Down stretch: its last bar and stop level
float rawStop = trend == 1 ? hiVal - stopMult * atrVal : trend == -1 ? loVal + stopMult * atrVal : na
var float stopLevel = na
var int   stopBar   = na
var int   stopSide  = 0      // direction of the stop that is running now (0 = none)
bool stopReached = (stopSide == 1 and close < stopLevel) or (stopSide == -1 and close > stopLevel)
if stopReached
    stopSide := 0            // a close beyond the stop ends it; the next Up / Down bar starts a new one
if ready and trend != 0 and not na(rawStop)
    if not stopTrail or stopSide != trend or na(stopLevel)
        stopLevel := rawStop
    else
        stopLevel := trend == 1 ? math.max(stopLevel, rawStop) : math.min(stopLevel, rawStop)
    stopSide := trend
    stopBar  := bar_index
 
var line  stopLine  = na
var label stopLabel = na
if barstate.islast and stopOn and not na(stopLevel) and not (stopHideNeutral and trend == 0)
    int x1 = stopBar - stopLeft
    int x2 = stopBar + stopRight
    if na(stopLine)
        stopLine  := line.new(x1, stopLevel, x2, stopLevel, color = stopColor, width = stopWidth)
        stopLabel := label.new(x2, stopLevel, str.tostring(stopLevel, format.mintick), style = label.style_label_left, color = color.new(stopColor, 100), textcolor = stopColor, size = size.normal)
    else
        line.set_xy1(stopLine, x1, stopLevel)
        line.set_xy2(stopLine, x2, stopLevel)
        line.set_color(stopLine, stopColor)
        line.set_width(stopLine, stopWidth)
        label.set_xy(stopLabel, x2, stopLevel)
        label.set_text(stopLabel, str.tostring(stopLevel, format.mintick))
        label.set_textcolor(stopLabel, stopColor)
else if barstate.islast and not na(stopLine)
    line.delete(stopLine)
    label.delete(stopLabel)
    stopLine  := na
    stopLabel := na
 
// ---------------- Information note on the chart ----------------
// Always shown (small, bottom right): what the colours are and are not.
var table infoNote = table.new(position.bottom_right, 1, 1, bgcolor = color.new(color.gray, 100), border_width = 0)
if barstate.islast
    table.cell(infoNote, 0, 0, "Obvious Trend measures the strength of upward or downward price movement.\nNo predictive value.", text_color = color.new(color.gray, 20), text_size = size.small, text_halign = text.align_right)
 
// ---------------- Data window and alerts ----------------
plot(trend, "Trend (1 up, 0 neutral, -1 down)", display = display.data_window)
plot(stopOn ? stopLevel : na, "Latest trailing stop level", display = display.data_window)
 
alertcondition(trend == 1 and trend[1] != 1, "Trend turned UP", "{{ticker}}: Obvious Trend turned UP")
alertcondition(trend == 0 and trend[1] != 0, "Trend turned NEUTRAL", "{{ticker}}: Obvious Trend turned NEUTRAL (strength weakening, not a trend change)")
alertcondition(trend == -1 and trend[1] != -1, "Trend turned DOWN", "{{ticker}}: Obvious Trend turned DOWN")

← 返回列表