Trend & Chop Regime Filter [Jireh]

Leeonidas187 · study · 329 行 · 点赞 15 · TradingView 原页

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

Pine Script

//@version=6
indicator("Trend & Chop Regime Filter [Jireh]", shorttitle = "Regime Filter", overlay = true, max_labels_count = 50)
 
// =====================================================================
// Trend & Chop Regime Filter [Jireh]
// High/low MA channel + regime engine (trend up / trend down / chop / transition)
// Engine inputs: channel position, slope, efficiency ratio, channel crossings,
// failed breakouts (fakeouts), compression. Minimal display by default.
// =====================================================================
 
// ---------- Channel ----------
grpCh      = "Channel"
maType     = input.string("EMA", "MA type", options = ["EMA", "SMA", "WMA", "HMA", "RMA"], group = grpCh)
chLen      = input.int(20, "Channel length", minval = 2, group = grpCh, tooltip = "MA of highs and MA of lows. 20 is a good start for NQ 1m; try 14 or 34.")
atrLen     = input.int(14, "ATR length", minval = 1, group = grpCh)
 
// ---------- Regime engine ----------
grpEng     = "Regime engine"
slopeSrcIn = input.string("Close", "Slope source", options = ["Close", "HL2"], group = grpEng, tooltip = "Hidden line used only to measure slope. Close reacts faster to acceptance.")
slopeLen   = input.int(5, "Slope lookback (bars)", minval = 1, group = grpEng)
slopeFull  = input.float(0.10, "Slope for full trend credit (ATR per bar)", minval = 0.01, step = 0.01, group = grpEng)
erLen      = input.int(14, "Efficiency ratio length", minval = 2, group = grpEng)
erFull     = input.float(0.50, "ER for full trend credit", minval = 0.05, maxval = 1.0, step = 0.05, group = grpEng)
crossLen   = input.int(30, "Crossings lookback (bars)", minval = 5, group = grpEng)
crossFull  = input.int(3, "Crossings for full chop penalty", minval = 1, group = grpEng)
bufMult    = input.float(0.25, "Breakout buffer (x ATR)", minval = 0.0, step = 0.05, group = grpEng, tooltip = "Close must be this far outside the channel to count as a breakout. Wicks never count.")
failWin    = input.int(4, "Fakeout window (bars)", minval = 1, group = grpEng, tooltip = "A breakout that closes back inside within this many bars counts as a failed breakout.")
failLook   = input.int(30, "Fakeout lookback (bars)", minval = 5, group = grpEng)
failFull   = input.int(2, "Fakeouts for full chop penalty", minval = 1, group = grpEng)
compLen    = input.int(100, "Compression baseline length", minval = 10, group = grpEng)
sqzThr     = input.float(0.70, "Squeeze threshold", minval = 0.1, maxval = 1.5, step = 0.05, group = grpEng, tooltip = "Channel width and ATR vs. their baseline. Below this = squeeze (shown as transition, not chop).")
smoothLen  = input.int(3, "Score smoothing", minval = 1, group = grpEng)
confBars   = input.int(2, "Confirmation bars", minval = 1, group = grpEng, tooltip = "A new regime must hold this many bars before the color changes. Breakouts from chop pass through transition first.")
 
// ---------- Weights ----------
grpW       = "Weights"
wSlope     = input.float(1.0, "Slope", minval = 0, step = 0.1, group = grpW)
wER        = input.float(1.0, "Efficiency ratio", minval = 0, step = 0.1, group = grpW)
wPos       = input.float(0.7, "Channel position", minval = 0, step = 0.1, group = grpW)
wCross     = input.float(1.0, "Crossings penalty", minval = 0, step = 0.1, group = grpW)
wFail      = input.float(1.0, "Fakeout penalty", minval = 0, step = 0.1, group = grpW)
penStr     = input.float(0.6, "Penalty strength", minval = 0, maxval = 1, step = 0.05, group = grpW, tooltip = "How hard crossings and fakeouts pull the score toward chop.")
 
// ---------- Breakout filter ----------
grpVol     = "Breakout filter"
useVol     = input.bool(false, "Require volume on breakouts", group = grpVol)
volLen     = input.int(20, "Volume average length", minval = 2, group = grpVol)
volMult    = input.float(1.2, "Relative volume needed", minval = 0.5, step = 0.1, group = grpVol)
 
// ---------- Thresholds ----------
grpT       = "Thresholds"
chopThr    = input.int(35, "Chop at or below", minval = 0, maxval = 100, group = grpT)
trendThr   = input.int(60, "Trend at or above", minval = 0, maxval = 100, group = grpT)
 
// ---------- Timeframes ----------
grpTF      = "Timeframes"
regimeTF   = input.timeframe("", "Regime timeframe", group = grpTF, tooltip = "Chart = use the chart's timeframe. Pick a higher timeframe to draw that channel and regime on this chart (confirmed bars only, no repaint).")
useCtx     = input.bool(true, "Show higher-timeframe context in label", group = grpTF)
ctxTF      = input.timeframe("15", "Context timeframe", group = grpTF, tooltip = "Ignored if it is not higher than the chart.")
 
// ---------- Display ----------
grpD       = "Display"
mode       = input.string("Minimal", "Display mode", options = ["Minimal", "Standard", "Detailed"], group = grpD)
showLines  = input.bool(true, "Show channel lines", group = grpD)
showFill   = input.bool(true, "Show channel fill", group = grpD)
lineW      = input.int(1, "Line width", minval = 1, maxval = 4, group = grpD)
fillTransp = input.int(85, "Fill transparency", minval = 0, maxval = 100, group = grpD)
colorBars  = input.bool(false, "Color candles by regime", group = grpD)
showLabel  = input.bool(true, "Show right-edge label", group = grpD)
showScore  = input.bool(true, "Show score in label", group = grpD)
lblOffset  = input.int(3, "Label offset (bars)", minval = 0, group = grpD)
lblSize    = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = grpD)
dashPosIn  = input.string("Top right", "Dashboard position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = grpD)
 
// ---------- Colors ----------
grpC       = "Colors"
upCol      = input.color(color.new(#1D9E75, 0), "Trend up", group = grpC)
dnCol      = input.color(color.new(#E24B4A, 0), "Trend down", group = grpC)
chopCol    = input.color(color.new(#888780, 0), "Chop", group = grpC)
trUpCol    = input.color(color.new(#378ADD, 0), "Bullish transition", group = grpC)
trDnCol    = input.color(color.new(#D4537E, 0), "Bearish transition", group = grpC)
lblTxtCol  = input.color(color.white, "Label text", group = grpC)
lblTransp  = input.int(15, "Label background transparency", minval = 0, maxval = 100, group = grpC)
 
// ---------- Session shading ----------
grpS       = "Session shading"
showSess   = input.bool(false, "Shade a session window", group = grpS)
sessWin    = input.session("1130-1330", "Window (New York time)", group = grpS)
sessCol    = input.color(color.new(#888780, 92), "Shade color", group = grpS)
 
// =====================================================================
// Helpers
// =====================================================================
maFn(float src, int len, string t) =>
    switch t
        "EMA" => ta.ema(src, len)
        "SMA" => ta.sma(src, len)
        "WMA" => ta.wma(src, len)
        "HMA" => ta.hma(src, len)
        => ta.rma(src, len)
 
stateCol(int s) =>
    s == 1 ? upCol : s == -1 ? dnCol : s == 2 ? trUpCol : s == -2 ? trDnCol : chopCol
 
stateName(int s) =>
    s == 1 ? "TREND ↑" : s == -1 ? "TREND ↓" : s == 2 ? "TRANS ↑" : s == -2 ? "TRANS ↓" : "CHOP"
 
stateShort(int s) =>
    s == 1 ? "↑" : s == -1 ? "↓" : s == 2 ? "trans ↑" : s == -2 ? "trans ↓" : "chop"
 
tfName(string tf) =>
    sec = timeframe.in_seconds(tf)
    sec < 3600 ? str.tostring(math.round(sec / 60)) + "m" : sec < 86400 ? str.tostring(math.round(sec / 3600)) + "H" : tf
 
// =====================================================================
// Engine
// returns [upper, lower, score, state, er, crosses, fakeouts, fakeoutNow, fakeoutDir, squeeze, slope]
// state: 1 trend up, -1 trend down, 0 chop, 2 bullish transition, -2 bearish transition
// =====================================================================
calc() =>
    hiB  = maFn(high, chLen, maType)
    loB  = maFn(low, chLen, maType)
    atr  = ta.atr(atrLen)
    src  = slopeSrcIn == "Close" ? close : hl2
    mid  = maFn(src, chLen, maType)
 
    // Slope (ATR per bar)
    slopeN     = atr > 0 ? (mid - mid[slopeLen]) / (atr * slopeLen) : 0.0
    slopeScore = math.min(math.abs(nz(slopeN)) / slopeFull, 1.0)
 
    // Efficiency ratio
    netMove  = math.abs(close - close[erLen])
    pathLen  = math.sum(math.abs(ta.change(close)), erLen)
    er       = pathLen > 0 ? netMove / pathLen : 0.0
    erScore  = math.min(nz(er) / erFull, 1.0)
 
    // Channel position (with optional volume filter)
    dist     = atr > 0 ? math.max(close - hiB, loB - close, 0.0) / atr : 0.0
    volOK    = not useVol or nz(volume) > nz(ta.sma(volume, volLen)) * volMult
    posScore = math.min(dist / 0.5, 1.0) * (volOK ? 1.0 : 0.5)
 
    // Full channel crossings
    side = close > hiB ? 1 : close < loB ? -1 : 0
    var int lastSide = 0
    crossEvt = false
    if side != 0
        if lastSide != 0 and side != lastSide
            crossEvt := true
        lastSide := side
    crosses      = math.sum(crossEvt ? 1 : 0, crossLen)
    crossPenalty = math.min(crosses / crossFull, 1.0)
 
    // Failed breakouts (fakeouts)
    buf    = bufMult * atr
    boUp   = close > hiB + buf and volOK
    boDn   = close < loB - buf and volOK
    newUp  = boUp and not boUp[1]
    newDn  = boDn and not boDn[1]
    inside = close <= hiB and close >= loB
    var int boBar = na
    var int boDir = 0
    failEvt = false
    failDir = 0
    if boDir != 0
        if inside and bar_index - boBar <= failWin
            failEvt := true
            failDir := boDir
            boDir   := 0
        else if bar_index - boBar > failWin
            boDir := 0
    if newUp
        boDir := 1
        boBar := bar_index
    if newDn
        boDir := -1
        boBar := bar_index
    fakeouts    = math.sum(failEvt ? 1 : 0, failLook)
    failPenalty = math.min(fakeouts / failFull, 1.0)
 
    // Compression / squeeze
    width     = hiB - loB
    wBase     = ta.sma(width, compLen)
    aBase     = ta.sma(atr, compLen)
    compRatio = (nz(width / wBase, 1.0) + nz(atr / aBase, 1.0)) / 2
    squeeze   = compRatio < sqzThr
 
    // Score
    wSum1    = math.max(wSlope + wER + wPos, 0.0001)
    wSum2    = math.max(wCross + wFail, 0.0001)
    trendRaw = (wSlope * slopeScore + wER * erScore + wPos * posScore) / wSum1
    penalty  = (wCross * crossPenalty + wFail * failPenalty) / wSum2
    score    = ta.ema(100 * trendRaw * (1 - penStr * penalty), smoothLen)
 
    // Raw regime
    tDir = slopeN >= 0 ? 2 : -2
    raw = score >= trendThr ? (slopeN >= 0 ? 1 : -1) : (score <= chopThr and not squeeze) ? 0 : tDir
 
    // Confirmation state machine (chop can't jump straight to trend)
    var int st   = 0
    var int cand = 0
    var int cnt  = 0
    c = raw
    if st == 0 and (raw == 1 or raw == -1)
        c := raw * 2
    if c == cand
        cnt += 1
    else
        cand := c
        cnt  := 1
    if cnt >= confBars and cand != st
        st := cand
 
    [hiB, loB, score, st, er, crosses, fakeouts, failEvt, failDir, squeeze, slopeN]
 
// Previous confirmed bar of the engine (for higher-timeframe requests, no repaint)
calcPrev() =>
    [a, b, c, d, e, f, g, h, i, j, k] = calc()
    [a[1], b[1], c[1], d[1], e[1], f[1], g[1], h[1], i[1], j[1], k[1]]
 
statePrev() =>
    [a, b, c, d, e, f, g, h, i, j, k] = calc()
    d[1]
 
// =====================================================================
// Run engine
// =====================================================================
chartSec = timeframe.in_seconds(timeframe.period)
rtfEff   = regimeTF == "" ? timeframe.period : regimeTF
useHTF   = timeframe.in_seconds(rtfEff) > chartSec
 
[hD, lD, sD, stD, erD, crD, foD, feD, fdD, sqD, slD] = calc()
[hH, lH, sH, stH, erH, crH, foH, feH, fdH, sqH, slH] = request.security(syminfo.tickerid, rtfEff, calcPrev(), lookahead = barmerge.lookahead_on)
 
hi    = useHTF ? hH  : hD
lo    = useHTF ? lH  : lD
score = useHTF ? sH  : sD
st    = useHTF ? stH : stD
erV   = useHTF ? erH : erD
crV   = useHTF ? crH : crD
foV   = useHTF ? foH : foD
sqV   = useHTF ? sqH : sqD
 
ctxValid = useCtx and timeframe.in_seconds(ctxTF) > timeframe.in_seconds(rtfEff)
ctxSt    = request.security(syminfo.tickerid, ctxTF, statePrev(), lookahead = barmerge.lookahead_on)
 
// =====================================================================
// Plots
// =====================================================================
col     = stateCol(st)
lineCol = showLines ? col : color.new(col, 100)
 
pU = plot(hi, "Upper band", color = lineCol, linewidth = lineW)
pL = plot(lo, "Lower band", color = lineCol, linewidth = lineW)
fill(pU, pL, color = showFill ? color.new(col, fillTransp) : na, title = "Channel fill")
 
barcolor(colorBars ? col : na, title = "Regime candles")
 
inSess = not na(time(timeframe.period, sessWin, "America/New_York"))
bgcolor(showSess and inSess ? sessCol : na, title = "Session shade")
 
// Fakeout / sweep-and-reject markers (Detailed mode, chart-timeframe regime only)
showMarks = mode == "Detailed" and not useHTF
plotshape(showMarks and feD and fdD == 1, "Fakeout up (swept and rejected)", shape.xcross, location.abovebar, trDnCol, size = size.tiny)
plotshape(showMarks and feD and fdD == -1, "Fakeout down (swept and rejected)", shape.xcross, location.belowbar, trUpCol, size = size.tiny)
 
// =====================================================================
// Label (Minimal view) with hover breakdown
// =====================================================================
lblSz = lblSize == "Tiny" ? size.tiny : lblSize == "Normal" ? size.normal : size.small
var label lbl = na
if barstate.islast
    label.delete(lbl)
    if showLabel
        txt = stateName(st) + (showScore ? " " + str.tostring(math.round(score)) : "") + (ctxValid ? " · " + tfName(ctxTF) + " " + stateShort(ctxSt) : "")
        tip = "Regime: " + stateName(st) + " (" + tfName(rtfEff) + ")" +
              "\nScore: " + str.tostring(math.round(score)) +
              "\nEfficiency ratio: " + str.tostring(erV, "#.##") +
              "\nCrossings: " + str.tostring(crV, "#") +
              "\nFakeouts: " + str.tostring(foV, "#") +
              "\nSqueeze: " + (sqV ? "yes" : "no") +
              (ctxValid ? "\n" + tfName(ctxTF) + " regime: " + stateName(ctxSt) : "")
        lbl := label.new(bar_index + lblOffset, close, txt, style = label.style_label_left, color = color.new(col, lblTransp), textcolor = lblTxtCol, size = lblSz, tooltip = tip)
 
// =====================================================================
// Dashboard (Standard / Detailed)
// =====================================================================
dashPos = switch dashPosIn
    "Top left"     => position.top_left
    "Bottom right" => position.bottom_right
    "Bottom left"  => position.bottom_left
    => position.top_right
 
var table dash = table.new(dashPos, 2, 7, border_width = 0)
if barstate.islast and mode != "Minimal"
    bg  = color.new(color.black, 80)
    txc = color.new(color.white, 0)
    table.cell(dash, 0, 0, "Regime", text_color = txc, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.cell(dash, 1, 0, stateName(st), text_color = lblTxtCol, bgcolor = color.new(col, 20), text_size = size.small)
    table.cell(dash, 0, 1, "Score", text_color = txc, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.cell(dash, 1, 1, str.tostring(math.round(score)), text_color = txc, bgcolor = bg, text_size = size.small)
    table.cell(dash, 0, 2, "Eff. ratio", text_color = txc, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.cell(dash, 1, 2, str.tostring(erV, "#.##"), text_color = txc, bgcolor = bg, text_size = size.small)
    table.cell(dash, 0, 3, "Crossings", text_color = txc, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.cell(dash, 1, 3, str.tostring(crV, "#"), text_color = txc, bgcolor = bg, text_size = size.small)
    table.cell(dash, 0, 4, "Fakeouts", text_color = txc, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.cell(dash, 1, 4, str.tostring(foV, "#"), text_color = txc, bgcolor = bg, text_size = size.small)
    table.cell(dash, 0, 5, "Squeeze", text_color = txc, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.cell(dash, 1, 5, sqV ? "yes" : "no", text_color = txc, bgcolor = bg, text_size = size.small)
    if mode == "Detailed" and ctxValid
        table.cell(dash, 0, 6, tfName(ctxTF), text_color = txc, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
        table.cell(dash, 1, 6, stateName(ctxSt), text_color = lblTxtCol, bgcolor = color.new(stateCol(ctxSt), 20), text_size = size.small)
 
// =====================================================================
// Alerts (set to "Once per bar close")
// =====================================================================
toUp     = st == 1 and st[1] != 1
toDn     = st == -1 and st[1] != -1
toChop   = st == 0 and st[1] != 0
toTrUp   = st == 2 and st[1] != 2
toTrDn   = st == -2 and st[1] != -2
trendGo  = (st == 1 or st == -1) and (st[1] == 0 or math.abs(st[1]) == 2)
 
alertcondition(toUp, "Trend up", "Regime Filter: TREND UP on {{ticker}} {{interval}}")
alertcondition(toDn, "Trend down", "Regime Filter: TREND DOWN on {{ticker}} {{interval}}")
alertcondition(toChop, "Chop", "Regime Filter: CHOP on {{ticker}} {{interval}}")
alertcondition(toTrUp, "Bullish transition", "Regime Filter: BULLISH TRANSITION on {{ticker}} {{interval}}")
alertcondition(toTrDn, "Bearish transition", "Regime Filter: BEARISH TRANSITION on {{ticker}} {{interval}}")
alertcondition(trendGo, "Chop/transition to trend", "Regime Filter: trend starting on {{ticker}} {{interval}}")
alertcondition(not useHTF and feD, "Fakeout", "Regime Filter: failed breakout on {{ticker}} {{interval}}")

← 返回列表