Uptrend Dip Finder

TheSimplePortfolio · study · 160 行 · 点赞 23 · 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/
// © BeikabuOyaji (original "ADX and DI", open-source on TradingView, 2015)
// © oridahari (Uptrend Dip Finder: new trend states, dip finder, stats and alerts)
// v2 draft: no below-MA dip marks, 20-bar stats horizon, fixed uptrend filter, weak-trend dots off by default.
//
// Uptrend Dip Finder: a trend-strength meter that also marks short pullbacks inside strong uptrends.
// The DI+, DI- and ADX math is the original "ADX and DI" by BeikabuOyaji, kept intact (switchable smoothing for parity checks).
// The 2-period RSI pullback rule is a classic published by Larry Connors (RSI below 10 while price is above its 200-day average).
// New in this version:
//   1. Pine v6. Five plain-word trend states (STRONG UP, UP FADING, NO TREND, DOWN FADING, STRONG DOWN) shown as coloured columns.
//   2. Trend age: how many bars the current direction has lasted.
//   3. Dip finder: "DIP" label on the price chart when a short sell-off (RSI 2 below 10) hits a stock that is above its 200 MA
//      AND was in a strong uptrend just before the dip started. Optional small dot for dips when the trend was weak.
//      Below the 200 MA the script gives no dip signals at all.
//   4. A live "Now" readout, alerts for every signal and state change, and a stats table that scores past signals
//      against any bar on the same chart (forward return after N bars, % of times up).
//   5. No repainting: only chart-timeframe data, signals are final at the bar close.
//@version=6
indicator("Uptrend Dip Finder", shorttitle = "Uptrend Dip Finder", overlay = false, max_labels_count = 500)
 
// ───────── Inputs ─────────
grpA   = "Trend strength (original ADX and DI)"
len    = input.int(14, "ADX / DI length", minval = 1, group = grpA)
th     = input.float(20.0, "Trend threshold (ADX)", minval = 1, group = grpA, tooltip = "ADX below this = NO TREND (chop).")
smooth = input.string("Original (SMA of DX)", "ADX smoothing", options = ["Original (SMA of DX)", "Wilder (RMA of DX)"], group = grpA, tooltip = "The original script smooths DX with an SMA. Wilder's classic ADX uses an RMA.")
showDI = input.bool(false, "Show the original DI+ / DI- lines", group = grpA)
 
grpD    = "Dip rules"
// The uptrend filter is fixed on purpose: price above the 200-bar SMA AND the trend strong and up 5 bars before the dip.
maLen   = 200
look    = 5
rsiLen  = input.int(2, "Dip RSI length", minval = 2, group = grpD)
rsiMax  = input.float(10.0, "Dip when RSI is below", minval = 1, maxval = 50, group = grpD)
 
grpS      = "Display and stats"
showWeak  = input.bool(false, "Show weak-trend dips (small dot)", group = grpS)
showNow   = input.bool(true, "Show the Now readout", group = grpS)
showTbl   = input.bool(true, "Show stats table", group = grpS)
fwdN      = input.int(20, "Stats: bars after the signal", minval = 1, maxval = 100, group = grpS)
startT    = input.time(timestamp("2000-01-01T00:00:00"), "Stats start", group = grpS)
 
// ───────── Original ADX and DI math (BeikabuOyaji), v6 syntax ─────────
TrueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))
DirectionalMovementPlus  = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0
DirectionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0
 
float SmoothedTrueRange = 0.0
SmoothedTrueRange := nz(SmoothedTrueRange[1]) - (nz(SmoothedTrueRange[1]) / len) + TrueRange
float SmoothedDirectionalMovementPlus = 0.0
SmoothedDirectionalMovementPlus := nz(SmoothedDirectionalMovementPlus[1]) - (nz(SmoothedDirectionalMovementPlus[1]) / len) + DirectionalMovementPlus
float SmoothedDirectionalMovementMinus = 0.0
SmoothedDirectionalMovementMinus := nz(SmoothedDirectionalMovementMinus[1]) - (nz(SmoothedDirectionalMovementMinus[1]) / len) + DirectionalMovementMinus
 
DIPlus  = SmoothedDirectionalMovementPlus / SmoothedTrueRange * 100
DIMinus = SmoothedDirectionalMovementMinus / SmoothedTrueRange * 100
DX      = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100
adxSma  = ta.sma(DX, len)
adxRma  = ta.rma(DX, len)
ADX     = smooth == "Original (SMA of DX)" ? adxSma : adxRma
 
// ───────── Trend state ─────────
// 2 = STRONG UP, 1 = UP FADING, 0 = NO TREND, -1 = DOWN FADING, -2 = STRONG DOWN
adxRising = ADX > ADX[1]
upDir     = DIPlus > DIMinus
int state = na(ADX) ? 0 : ADX < th ? 0 : upDir ? (adxRising ? 2 : 1) : (adxRising ? -2 : -1)
stateName(int s) =>
    s == 2 ? "STRONG UPTREND" : s == 1 ? "UPTREND, FADING" : s == -1 ? "DOWNTREND, FADING" : s == -2 ? "STRONG DOWNTREND" : "NO TREND (chop)"
stateCol(int s) =>
    s == 2 ? color.new(#00c853, 0) : s == 1 ? color.new(#00c853, 60) : s == -1 ? color.new(#ff1744, 60) : s == -2 ? color.new(#ff1744, 0) : color.new(color.gray, 40)
 
// trend age: bars since the direction (up / no trend / down) last changed
dirGroup = math.sign(state)
var int age = 0
age := dirGroup == dirGroup[1] ? age + 1 : 1
 
// ───────── Dip finder ─────────
ma         = ta.sma(close, maLen)
rsiFast    = ta.rsi(close, rsiLen)
aboveMA    = not na(ma) and close > ma
dipNow     = rsiFast < rsiMax
trendWasUp = ADX[look] >= th and DIPlus[look] > DIMinus[look]
strongDip  = dipNow and aboveMA and trendWasUp
weakDip    = dipNow and aboveMA and not trendWasUp
// first bar of each condition only (no repeated signals while the dip continues)
sigStrong  = strongDip and not strongDip[1]
sigWeak    = weakDip and not weakDip[1]
 
// ───────── Plots (indicator pane) ─────────
plot(ADX, "ADX (trend strength)", stateCol(state), 4, plot.style_columns)
hline(th, "Trend threshold", color.new(color.gray, 30), hline.style_dashed)
plot(showDI ? DIPlus : na, "DI+", color.green)
plot(showDI ? DIMinus : na, "DI-", color.red)
plotshape(sigStrong, "Dip in strong uptrend (pane)", shape.triangleup, location.bottom, color.new(#2962ff, 0), size = size.small)
 
// ───────── Marks on the price chart ─────────
if sigStrong and barstate.isconfirmed
    label.new(bar_index, low, "DIP\nin uptrend", yloc = yloc.belowbar, color = color.new(#2962ff, 0), textcolor = color.white, style = label.style_label_up, size = size.large, force_overlay = true)
plotshape(showWeak and sigWeak, "Dip, weak trend", shape.circle, location.belowbar, color.new(#2962ff, 50), size = size.small, force_overlay = true)
plot(ma, "200 MA", color.new(color.orange, 20), 2, force_overlay = true)
 
var label lNow = na
if showNow and barstate.islast
    label.delete(lNow)
    dipTxt = not aboveMA ? "below " + str.tostring(maLen) + " MA: no dip signals" : strongDip ? "DIP in strong uptrend" : weakDip ? "dip, weak trend" : "no dip"
    txt = "Now: " + stateName(state) + "\nTrend age: " + str.tostring(age) + " bars · ADX " + str.tostring(ADX, "#.0") + "\n" + dipTxt
    lNow := label.new(bar_index + 3, close, txt, color = stateCol(state), textcolor = color.white, style = label.style_label_left, size = size.normal, force_overlay = true)
 
// ───────── Alerts ─────────
alertcondition(sigStrong, "DIP in strong uptrend", "Uptrend Dip Finder: DIP in a strong uptrend on {{ticker}} ({{interval}})")
alertcondition(sigWeak, "Dip, weak trend", "Uptrend Dip Finder: dip while the trend is weak on {{ticker}}")
alertcondition(state == 2 and state[1] != 2, "Strong uptrend starts", "Uptrend Dip Finder: STRONG UPTREND on {{ticker}}")
alertcondition(state == 0 and state[1] != 0, "Trend turns to chop", "Uptrend Dip Finder: NO TREND (chop) on {{ticker}}")
alertcondition(state == -2 and state[1] != -2, "Strong downtrend starts", "Uptrend Dip Finder: STRONG DOWNTREND on {{ticker}}")
 
// ───────── Stats: forward return fwdN bars after each signal vs any bar ─────────
var int   nA = 0
var float sA = 0.0
var int   uA = 0
var int   nS = 0
var float sS = 0.0
var int   uS = 0
var int   nW = 0
var float sW = 0.0
var int   uW = 0
if bar_index >= fwdN and time[fwdN] >= startT and not na(ma[fwdN])
    r = close / close[fwdN] - 1
    nA += 1
    sA += r
    uA += r > 0 ? 1 : 0
    if sigStrong[fwdN]
        nS += 1
        sS += r
        uS += r > 0 ? 1 : 0
    if sigWeak[fwdN]
        nW += 1
        sW += r
        uW += r > 0 ? 1 : 0
 
avgTxt(float s, int n) => n > 0 ? str.tostring(s / n * 100, "#.##") + "%" : "-"
upTxt(int u, int n) => n > 0 ? str.tostring(u * 100.0 / n, "#") + "%" : "-"
var table t = table.new(position.top_right, 4, 5, bgcolor = color.new(color.black, 25), border_width = 1)
if showTbl and barstate.islast
    t.cell(0, 0, "Since " + str.format_time(startT, "yyyy-MM-dd", syminfo.timezone) + ": " + str.tostring(fwdN) + " bars after the signal (close to close, no costs)", text_color = color.white, text_size = size.small)
    t.merge_cells(0, 0, 3, 0)
    t.cell(0, 1, "", text_size = size.small)
    t.cell(1, 1, "Signals", text_color = color.silver, text_size = size.small)
    t.cell(2, 1, "Avg return", text_color = color.silver, text_size = size.small)
    t.cell(3, 1, "% up", text_color = color.silver, text_size = size.small)
    t.cell(0, 2, "DIP in strong uptrend", text_color = color.white, text_size = size.small)
    t.cell(1, 2, str.tostring(nS), text_color = color.white, text_size = size.small)
    t.cell(2, 2, avgTxt(sS, nS), text_color = color.white, text_size = size.small)
    t.cell(3, 2, upTxt(uS, nS), text_color = color.white, text_size = size.small)
    t.cell(0, 3, "Dip, weak trend", text_color = color.white, text_size = size.small)
    t.cell(1, 3, str.tostring(nW), text_color = color.white, text_size = size.small)
    t.cell(2, 3, avgTxt(sW, nW), text_color = color.white, text_size = size.small)
    t.cell(3, 3, upTxt(uW, nW), text_color = color.white, text_size = size.small)
    t.cell(0, 4, "Any bar (baseline)", text_color = color.silver, text_size = size.small)
    t.cell(1, 4, str.tostring(nA), text_color = color.silver, text_size = size.small)
    t.cell(2, 4, avgTxt(sA, nA), text_color = color.silver, text_size = size.small)
    t.cell(3, 4, upTxt(uA, nA), text_color = color.silver, text_size = size.small)

← 返回列表