Trend Shift Sequencer (5-Step)

zanigh888 · study · 289 行 · 点赞 6 · TradingView 原页

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

Pine Script

//@version=6
indicator("Trend Shift Sequencer (5-Step)", shorttitle = "TSS-5", overlay = true, behind_chart = false, max_labels_count = 20, max_lines_count = 20)
 
// ===========================================================================
//  Trend Shift Sequencer
//  Tracks a 5-step reversal sequence against the established trend:
//    1. Stop      - price closes across the short-term EMA (default 9)
//  MAs: short-term and medium-term are EMAs; long-term and far are SMAs.
//    2. Base      - the short-term MA turns in the new direction
//    3. Breakout  - the short-term MA crosses the medium-term MA (default 20)
//    4. Confirm   - short, medium and long-term (default 50) MAs all slope the new way
//    5. New trend - HH+HL / LH+LL structure, price stretches away from the
//                   short-term MA and bounces off it  -> trend flips
//  Candles are green/red by trend; they switch colour once a reversal reaches step 2.
//  Steps are sequential: each one only counts after the previous one.
//  Also draws a recommended put strike - below the medium-term MA AND at least
//  1.5x ATR below price (both adjustable) - plus the ATR floor and a stop loss
//  15% below the strike (adjustable).
// ===========================================================================
 
// ----- Inputs --------------------------------------------------------------
const string G_SH = "Show / hide"
bool showTable  = input.bool(true, "Show summary table", group = G_SH)
 
const string G_MA = "Moving averages"
int  fastLen = input.int(9,   "Short-term MA period", minval = 1, group = G_MA, tooltip = "Drives steps 1-2 (price crossing it, it turning) and the step 5 stretch/bounce checks.")
int  midLen  = input.int(20,  "Medium-term MA period", minval = 1, group = G_MA, tooltip = "Step 3 breakout: short-term MA crossing this one.")
int  slowLen = input.int(50,  "Long-term MA period", minval = 1, group = G_MA, tooltip = "Step 4 confirmation: short, medium and long-term MAs all sloping the same way.")
int  slopeLb = input.int(1, "Slope lookback (bars)", minval = 1, group = G_MA, tooltip = "An MA counts as rising/falling when it is above/below its own value this many bars ago. Raise to 2-3 to ignore one-day wiggles.")
int    farLen  = input.int(100, "Far MA period (SMA, display only)", minval = 1, group = G_MA, tooltip = "Plotted for reference only - not used in the trend-shift steps.")
bool   showFar = input.bool(true, "Plot the far MA", group = G_MA)
bool showMA  = input.bool(true, "Plot the MAs", group = G_MA)
color colShort = input.color(#FF9800, "Short-term MA colour", group = G_MA)
color colMid   = input.color(#2962FF, "Medium-term MA colour", group = G_MA)
color colLong  = input.color(#9C27B0, "Long-term MA colour", group = G_MA)
color colFar   = input.color(#787B86, "Far MA colour", group = G_MA)
 
const string G_S5 = "Step 5 - new trend development"
int   pivLen     = input.int(3, "Swing pivot strength (bars each side)", minval = 1, group = G_S5, tooltip = "Bars needed on each side to confirm a swing high/low. Pivots are confirmed this many bars late.")
bool  useStruct  = input.bool(true, "Require HH+HL (up) / LH+LL (down) after step 1", group = G_S5)
bool  useDev     = input.bool(true, "Require price to stretch away from the short-term MA", group = G_S5)
float devMult    = input.float(1.0, "   Stretch at least (x ATR14)", minval = 0.1, step = 0.1, group = G_S5)
int   devLookback = input.int(15, "   ...within the last N bars", minval = 1, group = G_S5)
bool  useBounce  = input.bool(true, "Require a bounce off / rejection at the short-term MA since step 3", group = G_S5)
 
const string G_INV = "Invalidation"
bool useInvalid = input.bool(true, "Reset the sequence if the old trend resumes", group = G_INV, tooltip = "Any step: price closes back above a rising short-term MA (cancels a down reversal) or below a falling one (cancels an up reversal). Any step: also resets when the short-term MA crosses back over the medium-term MA (above in an uptrend, below in a downtrend).")
 
const string G_D = "Display"
bool paintBars  = input.bool(true, "Paint candles", group = G_D)
color upCol    = input.color(#1B8E3E, "Uptrend colour", group = G_D)
color dnCol    = input.color(#C62828, "Downtrend colour", group = G_D)
bool showBg     = input.bool(false, "Tint background", group = G_D)
int  bgTransp   = input.int(85, "   Background transparency", minval = 0, maxval = 100, group = G_D)
 
const string G_K = "Recommended strike & stop loss"
bool  showStrike = input.bool(true, "Show recommended strike and stop loss", group = G_K)
float atrMult    = input.float(1.5, "Strike: at least this many x ATR below price", minval = 0.1, step = 0.1, group = G_K, tooltip = "The strike must be below BOTH the ATR floor (price - this x ATR) and the medium-term MA. Default 1.5x.")
int   atrLen     = input.int(14, "ATR length", minval = 1, group = G_K)
float slPct      = input.float(15.0, "Stop loss: % below strike", minval = 0.1, step = 0.5, group = G_K, tooltip = "Stop loss = strike x (1 - this %). Default 15%.")
float incIn      = input.float(0.0, "Strike increment (0 = auto)", minval = 0.0, step = 0.5, group = G_K, tooltip = "Auto: 0.5 under $25, 1 under $200, 5 under $1,000, 10 above. Set your own to match the option chain.")
bool  showAtr    = input.bool(true, "Show the ATR floor line", group = G_K)
color strikeCol  = input.color(#1E88E5, "Strike colour", group = G_K)
color slCol      = input.color(#E53935, "Stop loss colour", group = G_K)
color atrCol     = input.color(#7E57C2, "ATR floor colour", group = G_K)
 
// ----- Step names ----------------------------------------------------------
string sF = str.tostring(fastLen)
string sM = str.tostring(midLen)
string sS = str.tostring(slowLen)
var string[] names = array.from("1 Stop: price crossed " + sF + " EMA", "2 Base: " + sF + " EMA turning", "3 Breakout: " + sF + " EMA crossed " + sM + " EMA", "4 Confirm: " + sF + "/" + sM + "/" + sS + " aligned", "5 New trend established")
 
// ----- Core series ---------------------------------------------------------
float f   = ta.ema(close, fastLen)   // short-term: EMA
float far = ta.sma(close, farLen)    // far: SMA, display only
float m   = ta.ema(close, midLen)    // medium-term: EMA
bool  fmUpX = ta.crossover(f, m)     // short-term crosses back above medium-term
bool  fmDnX = ta.crossunder(f, m)    // short-term crosses back below medium-term
float s   = ta.sma(close, slowLen)    // long-term: SMA
float atr = ta.atr(14)
float atrX = ta.atr(atrLen)
 
bool fUp = f > f[slopeLb]
bool fDn = f < f[slopeLb]
bool mUp = m > m[slopeLb]
bool mDn = m < m[slopeLb]
bool sUp = s > s[slopeLb]
bool sDn = s < s[slopeLb]
 
// Swing pivots (latest = 1, previous = 2)
float ph = ta.pivothigh(high, pivLen, pivLen)
float pl = ta.pivotlow(low, pivLen, pivLen)
var float ph1 = na
var float ph2 = na
var int   ph1Bar = na
var float pl1 = na
var float pl2 = na
var int   pl1Bar = na
if not na(ph)
    ph2    := ph1
    ph1    := ph
    ph1Bar := bar_index - pivLen
if not na(pl)
    pl2    := pl1
    pl1    := pl
    pl1Bar := bar_index - pivLen
 
// Stretch from the short-term MA, in ATR units
float z    = (close - f) / atr
float maxZ = ta.highest(z, devLookback)
float minZ = ta.lowest(z, devLookback)
 
// Bounce off the short-term MA (up: dips to it and closes above; down: pokes it and closes below)
int barsBU = nz(ta.barssince(low <= f and close > f), 100000)
int barsBD = nz(ta.barssince(high >= f and close < f), 100000)
 
// ----- State machine -------------------------------------------------------
var int trend    = 0     // 1 = established uptrend, -1 = established downtrend
var int step     = 0     // reversal steps completed against the current trend (0-4)
var int step1Bar = na
var int step3Bar = na
 
int    reached    = 0
int    reachedDir = 0
string reachedTxt = ""
 
bool ready = not na(s) and not na(atr)
 
if ready
    if trend == 0
        trend := f > m ? 1 : -1
    else
        int dir = -trend   // direction the reversal is heading
 
        bool c1 = dir == 1 ? close > f : close < f
        bool c2 = dir == 1 ? fUp : fDn
        bool c3 = dir == 1 ? f > m : f < m
        bool c4 = dir == 1 ? (fUp and mUp and sUp) : (fDn and mDn and sDn)
 
        bool structSeq = dir == 1 ? (ph1 > ph2 and pl1 > pl2) : (ph1 < ph2 and pl1 < pl2)
        bool structOK  = not useStruct or (structSeq and ph1Bar >= step1Bar and pl1Bar >= step1Bar)
        bool devOK     = not useDev or (dir == 1 ? maxZ >= devMult : minZ <= -devMult)
        bool bounceOK  = not useBounce or (dir == 1 ? barsBU <= bar_index - step3Bar : barsBD <= bar_index - step3Bar)
        // Step 5 keeps short>medium and the medium/long slopes aligned, but lets the short-term MA wobble on bounces
        bool c5 = c3 and (dir == 1 ? (mUp and sUp) : (mDn and sDn)) and structOK and devOK and bounceOK
 
        // Invalidation: old trend resumes -> start over
        if useInvalid and step > 0
            // Any step: price closes back on the old trend's side of a short-term MA that is
            // sloping the old trend's way (uptrend: close above a rising MA; downtrend: below a falling MA).
            // Steps 3-4 also reset if the short-term MA crosses back over the medium-term MA.
            bool priceBack = trend == 1 ? (close > f and fUp) : (close < f and fDn)
            bool maBack    = trend == 1 ? f > m : f < m
            bool crossBack = trend == 1 ? fmUpX : fmDnX   // any step: short-term MA crosses back over the medium-term MA
            bool resumes   = priceBack or crossBack or (step >= 3 and maBack)
            if resumes
                step := 0
 
        // Advance sequentially (several steps can complete on one bar)
        bool more = true
        while more and step < 5
            int nxt = step + 1
            bool ok = switch nxt
                1 => c1
                2 => c2
                3 => c3
                4 => c4
                => c5
            if ok
                step := nxt
                if nxt == 1
                    step1Bar := bar_index
                if nxt == 3
                    step3Bar := bar_index
                reached    := nxt
                reachedDir := dir
                reachedTxt := reachedTxt == "" ? str.tostring(nxt) : reachedTxt + "+" + str.tostring(nxt)
            else
                more := false
 
        // Step 5 -> the new trend is established
        if step == 5
            trend := dir
            step  := 0
 
// ----- Colouring -----------------------------------------------------------
color barCol = na
if trend != 0
    // Step 1 is only a warning: keep the existing trend's colour.
    // From step 2 (short-term MA turns) the candles switch to the new direction.
    int colDir = step >= 2 ? -trend : trend
    barCol := colDir == 1 ? upCol : dnCol
 
// Draw full candles (body, border and wick) in the trend colour so the chart's
// default up/down border colours don't show through
bool drawC = paintBars and not na(barCol)
// barcolor recolours the chart's own candle bodies even if they sit on top of this indicator
barcolor(drawC ? barCol : na)
// Full candle (body, wick and border) in the trend colour, drawn over the chart's own candle
plotcandle(drawC ? open : na, drawC ? high : na, drawC ? low : na, drawC ? close : na, "Trend candles", color = barCol, wickcolor = barCol, bordercolor = barCol)
bgcolor(showBg and not na(barCol) ? color.new(barCol, bgTransp) : na)
 
plot(showMA ? f : na, "Short-term MA", color = colShort, linewidth = 1)
plot(showMA ? m : na, "Medium-term MA",  color = colMid, linewidth = 2)
plot(showMA ? s : na, "Long-term MA", color = colLong, linewidth = 2)
plot(showFar ? far : na, "Far MA", color = colFar, linewidth = 2)
 
// ----- Strike, stop loss and ATR levels ------------------------------------
// Strike cap: the lower of (a) the medium-term MA and (b) the ATR floor
// (price - atrMult x ATR). Strike = first increment below that cap.
float inc        = incIn > 0 ? incIn : close < 25 ? 0.5 : close < 200 ? 1.0 : close < 1000 ? 5.0 : 10.0
float atrDn      = close - atrMult * atrX
string maTxt     = sM + " EMA"
bool  atrBinds   = atrDn < m
float cap        = atrBinds ? atrDn : m
string capTxt    = atrBinds ? (str.tostring(atrMult) + "x ATR") : maTxt
float strikeRaw  = math.floor(cap / inc) * inc
float strike     = strikeRaw >= cap ? strikeRaw - inc : strikeRaw
float stopLoss   = strike * (1 - slPct / 100)
 
f_level(line ln, label lb, float y, color c, string txt, string st) =>
    line.set_xy1(ln, bar_index - 15, y)
    line.set_xy2(ln, bar_index + 12, y)
    line.set_color(ln, c)
    line.set_style(ln, st)
    label.set_xy(lb, bar_index + 12, y)
    label.set_text(lb, txt)
    label.set_textcolor(lb, c)
 
var line  lnStrike = line.new(na, na, na, na, width = 2)
var line  lnSL     = line.new(na, na, na, na, width = 2)
var line  lnAD     = line.new(na, na, na, na, width = 1)
var label lbStrike = label.new(na, na, "", style = label.style_label_left, color = color(na), size = size.small)
var label lbSL     = label.new(na, na, "", style = label.style_label_left, color = color(na), size = size.small)
var label lbAD     = label.new(na, na, "", style = label.style_label_left, color = color(na), size = size.small)
 
if barstate.islast
    string mx = str.tostring(atrMult)
    if showStrike and not na(cap)
        f_level(lnStrike, lbStrike, strike, strikeCol, "Strike " + str.tostring(strike, format.mintick) + " (below " + capTxt + ")", line.style_solid)
        f_level(lnSL, lbSL, stopLoss, slCol, "Stop loss " + str.tostring(stopLoss, format.mintick) + " (-" + str.tostring(slPct) + "%)", line.style_solid)
    else
        line.set_xy1(lnStrike, na, na)
        line.set_xy2(lnStrike, na, na)
        label.set_xy(lbStrike, na, na)
        line.set_xy1(lnSL, na, na)
        line.set_xy2(lnSL, na, na)
        label.set_xy(lbSL, na, na)
    if showAtr and not na(atrX)
        f_level(lnAD, lbAD, atrDn, atrCol, "-" + mx + " ATR floor " + str.tostring(atrDn, format.mintick), line.style_dashed)
    else
        line.set_xy1(lnAD, na, na)
        line.set_xy2(lnAD, na, na)
        label.set_xy(lbAD, na, na)
 
// ----- Summary table (transparent) -----------------------------------------
var table tbl = table.new(position.top_right, 2, 8, bgcolor = color(na), frame_color = color(na), border_color = color(na), border_width = 0)
if showTable and barstate.islast
    color fg = chart.fg_color
    color tc = trend == 1 ? upCol : dnCol
    string revTxt = step == 0 ? "none" : ((-trend == 1 ? "-> UP " : "-> DOWN ") + str.tostring(step) + "/5")
    color rc = step == 0 ? fg : (-trend == 1 ? upCol : dnCol)
    table.cell(tbl, 0, 0, "Trend", text_color = fg, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 0, trend == 1 ? "UP" : trend == -1 ? "DOWN" : "-", text_color = tc, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 1, "Reversal", text_color = fg, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 1, revTxt, text_color = rc, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 2, "Stage", text_color = fg, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 2, step == 0 ? "trend intact" : names.get(step - 1), text_color = rc, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 3, maTxt, text_color = fg, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 3, str.tostring(m, format.mintick) + "  (strike must be below)", text_color = colMid, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 4, "Rec. strike", text_color = fg, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 4, str.tostring(strike, format.mintick) + "  (" + str.tostring((strike / close - 1) * 100, "#.#") + "%, " + str.tostring((close - strike) / atrX, "#.#") + "x ATR below; set by " + capTxt + ")", text_color = strikeCol, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 5, "Stop loss", text_color = fg, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 5, str.tostring(stopLoss, format.mintick) + "  (-" + str.tostring(slPct) + "% of strike)", text_color = slCol, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 6, "ATR(" + str.tostring(atrLen) + ")", text_color = fg, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 6, str.tostring(atrX, format.mintick) + "  (" + str.tostring(atrX / close * 100, "#.#") + "%)", text_color = fg, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 7, str.tostring(atrMult) + "x ATR floor", text_color = fg, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 7, str.tostring(atrDn, format.mintick) + "  (strike must be at or below)", text_color = atrCol, text_size = size.small, text_halign = text.align_left)
 
// ----- Alerts --------------------------------------------------------------
if reached > 0
    alert(syminfo.ticker + ": " + (reachedDir == 1 ? "UP" : "DOWN") + " reversal step " + reachedTxt + " - " + names.get(reached - 1), alert.freq_once_per_bar_close)
 
alertcondition(reached == 1 and reachedDir == 1,  "Up reversal - step 1 (stall)",     "{{ticker}}: downtrend stalling, price above short-term MA")
alertcondition(reached == 1 and reachedDir == -1, "Down reversal - step 1 (stall)",   "{{ticker}}: uptrend stalling, price below short-term MA")
alertcondition(reached == 3 and reachedDir == 1,  "Up reversal - step 3 (breakout)",  "{{ticker}}: short-term MA crossed above medium-term MA")
alertcondition(reached == 3 and reachedDir == -1, "Down reversal - step 3 (breakout)","{{ticker}}: short-term MA crossed below medium-term MA")
alertcondition(reached == 5 and reachedDir == 1,  "New UPTREND confirmed",            "{{ticker}}: new uptrend established (step 5)")
alertcondition(reached == 5 and reachedDir == -1, "New DOWNTREND confirmed",          "{{ticker}}: new downtrend established (step 5)")

← 返回列表