本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PhenLabs
//@version=6
indicator("Multi-Timeframe Trend Ribbon & Pullback Signals [PhenLabs]", shorttitle = "MTTRPS [PhenLabs]", overlay = true, max_lines_count = 300, max_labels_count = 300)
// ════════════════════════════════════════════════════════════════
// ENUMS
// ════════════════════════════════════════════════════════════════
enum ModeOpt
Fast = "Fast"
Balanced = "Balanced"
Swing = "Swing"
enum TblPos
BR = "Bottom Right"
BL = "Bottom Left"
TL = "Top Left"
enum TblSize
Tiny = "Tiny"
Small = "Small"
Normal = "Normal"
// ════════════════════════════════════════════════════════════════
// INPUTS (12)
// ════════════════════════════════════════════════════════════════
const string G1 = "Trend Engine"
const string G2 = "Trade Plan"
const string G3 = "Display"
ModeOpt modeIn = input.enum(ModeOpt.Balanced, "Mode", group = G1, tooltip = "Fast = 8/18/30 ribbon for scalping. Balanced = 9/21/34 for intraday. Swing = 12/26/42 for slower, stricter pullbacks.")
string htfIn = input.timeframe("", "Higher Timeframe", group = G1, tooltip = "Leave empty for automatic 4x the chart timeframe. If the chosen timeframe is not higher than the chart, the frontier falls back to the chart timeframe.")
float stMult = input.float(3.0, "Frontier ATR Multiplier", minval = 1.0, maxval = 6.0, step = 0.1, group = G1, tooltip = "Width of the higher-timeframe trend frontier (ATR 10 based).")
float tp2R = input.float(2.4, "Runner Target (R)", minval = 1.5, maxval = 5.0, step = 0.1, group = G2, tooltip = "TP1 is fixed at 1R (50 percent scale-out). TP2 closes the runner at this R multiple.")
bool showPlan = input.bool(true, "Show SL / TP Rays", group = G2)
int maxPlans = input.int(25, "Historical Plans Kept", minval = 1, maxval = 60, group = G2, active = showPlan)
color bullCol = input.color(#10E39A, "Ribbon Colors", inline = "c", group = G3)
color bearCol = input.color(#FF4D6D, "", inline = "c", group = G3)
color chopCol = input.color(#64748B, "", inline = "c", group = G3)
bool showDash = input.bool(true, "Show Dashboard", group = G3)
TblPos tPosIn = input.enum(TblPos.BR, "Table Position", group = G3, active = showDash)
TblSize tSizeIn = input.enum(TblSize.Small, "Table Size", group = G3, active = showDash)
// ════════════════════════════════════════════════════════════════
// MODE PARAMETERS
// ════════════════════════════════════════════════════════════════
int fastLen = modeIn == ModeOpt.Fast ? 8 : modeIn == ModeOpt.Swing ? 12 : 9
int midLen = modeIn == ModeOpt.Fast ? 18 : modeIn == ModeOpt.Swing ? 26 : 21
int slowLen = modeIn == ModeOpt.Fast ? 30 : modeIn == ModeOpt.Swing ? 42 : 34
float erFloor = modeIn == ModeOpt.Fast ? 0.16 : modeIn == ModeOpt.Swing ? 0.24 : 0.20
int coolBars = modeIn == ModeOpt.Fast ? 6 : modeIn == ModeOpt.Swing ? 10 : 8
float minSprd = modeIn == ModeOpt.Fast ? 0.16 : modeIn == ModeOpt.Swing ? 0.24 : 0.20
float slopeMin = modeIn == ModeOpt.Fast ? 0.02 : modeIn == ModeOpt.Swing ? 0.04 : 0.03
// ════════════════════════════════════════════════════════════════
// CORE CALCULATIONS
// ════════════════════════════════════════════════════════════════
float fastR = ta.ema(close, fastLen)
float midR = ta.ema(close, midLen)
float slowR = ta.ema(close, slowLen)
float baseR = ta.ema(close, 100)
float atr = ta.atr(14)
float erDen = math.sum(math.abs(close - close[1]), 20)
float er = erDen > 0 ? math.abs(close - close[20]) / erDen : 0.0
// Higher-timeframe trend frontier (non-repainting: previous closed HTF bar)
f_frontier(float m) =>
[s, d] = ta.supertrend(m, 10)
[s[1], d[1]]
int chartSec = timeframe.in_seconds(timeframe.period)
string autoTf = timeframe.from_seconds(chartSec * 4)
string htfTf = htfIn == "" ? autoTf : htfIn
bool useHtf = timeframe.in_seconds(htfTf) > chartSec
[htfS, htfD] = request.security(syminfo.tickerid, htfTf, f_frontier(stMult), lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true)
[ltfS, ltfD] = ta.supertrend(stMult, 10)
float frontier = useHtf ? htfS : ltfS
int htfBias = useHtf ? (na(htfD) ? 0 : htfD < 0 ? 1 : -1) : (ltfD < 0 ? 1 : -1)
float sprd = atr > 0 ? math.abs(fastR - slowR) / atr : 0.0
float slope = atr > 0 ? (slowR - slowR[5]) / (5.0 * atr) : 0.0
bool chop = er < erFloor
// ════════════════════════════════════════════════════════════════
// TRADE PLAN OBJECT
// ════════════════════════════════════════════════════════════════
type Plan
int dir
float entry
float sl
float tp1
float tp2
bool tp1Hit
bool done
line slL
line tp1L
line tp2L
label sigLb
label tp1Lb
label endLb
var array<Plan> plans = array.new<Plan>()
// ════════════════════════════════════════════════════════════════
// STATE MACHINE (confirmed bars only)
// ════════════════════════════════════════════════════════════════
var int armedDir = 0
var float pbExtreme = na
var int armedBars = 0
var int activeDir = 0
var float entryPx = na
var float stopPx = na
var float tp1Px = na
var float tp2Px = na
var bool tp1Hit = false
var int lastSig = -100000
var int nTrades = 0
var int nTp1 = 0
var int nTp2 = 0
var float netR = 0.0
bool bullSig = false
bool bearSig = false
int resolved = 0 // 1 = TP2, 2 = TP1 then stop, 3 = stop
if barstate.isconfirmed and not na(frontier) and not na(atr) and atr > 0 and bar_index > 110
// 1. Resolve active plan (stop checked before targets on the same bar)
if activeDir == 1
if low <= stopPx
resolved := tp1Hit ? 2 : 3
else
if not tp1Hit and high >= tp1Px
tp1Hit := true
nTp1 += 1
if showPlan and array.size(plans) > 0
Plan cp = array.last(plans)
cp.tp1Lb := label.new(time, tp1Px, "TP1 ✓", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(bullCol, 15), textcolor = #06110D, size = size.tiny)
if high >= tp2Px
resolved := 1
else if activeDir == -1
if high >= stopPx
resolved := tp1Hit ? 2 : 3
else
if not tp1Hit and low <= tp1Px
tp1Hit := true
nTp1 += 1
if showPlan and array.size(plans) > 0
Plan cp = array.last(plans)
cp.tp1Lb := label.new(time, tp1Px, "TP1 ✓", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(bullCol, 15), textcolor = #06110D, size = size.tiny)
if low <= tp2Px
resolved := 1
if resolved != 0
float r = resolved == 1 ? 0.5 + 0.5 * tp2R : resolved == 2 ? 0.0 : -1.0
netR += r
if resolved == 1
nTp2 += 1
if array.size(plans) > 0
Plan p = array.last(plans)
p.done := true
if showPlan
line.set_x2(p.slL, time)
line.set_x2(p.tp1L, time)
line.set_x2(p.tp2L, time)
if resolved == 1
p.endLb := label.new(time, p.tp2, "TP2 ✓", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(bullCol, 0), textcolor = #06110D, size = size.tiny)
else
p.endLb := label.new(time, p.sl, resolved == 2 ? "BE" : "SL", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = color.new(resolved == 2 ? chopCol : bearCol, 15), textcolor = color.white, size = size.tiny)
activeDir := 0
// 2. Disarm on regime loss or stale pullback
if armedDir == 1 and (not (htfBias == 1 and close > frontier and slowR > baseR) or armedBars > 10)
armedDir := 0
else if armedDir == -1 and (not (htfBias == -1 and close < frontier and slowR < baseR) or armedBars > 10)
armedDir := 0
// 3. Arm pullback into the ribbon
bool bullRegime = htfBias == 1 and close > frontier and midR > slowR and slowR > baseR and slope >= slopeMin
bool bearRegime = htfBias == -1 and close < frontier and midR < slowR and slowR < baseR and slope <= -slopeMin
if bullRegime
if armedDir != 1 and low <= fastR and low > frontier
armedDir := 1
pbExtreme := low
armedBars := 1
else if armedDir == 1
pbExtreme := math.min(pbExtreme, low)
armedBars += 1
else if bearRegime
if armedDir != -1 and high >= fastR and high < frontier
armedDir := -1
pbExtreme := high
armedBars := 1
else if armedDir == -1
pbExtreme := math.max(pbExtreme, high)
armedBars += 1
// 4. Closed-bar reclaim trigger
float barRng = math.max(high - low, syminfo.mintick)
float closePos = (close - low) / barRng
if activeDir == 0 and bar_index - lastSig >= coolBars and er >= erFloor and sprd >= minSprd
if armedDir == 1 and close > fastR and close > open and closePos >= 0.55 and (close[1] <= fastR[1] or low <= fastR)
float rawRisk = close - (math.min(pbExtreme, slowR) - 0.45 * atr)
float risk = math.min(math.max(rawRisk, 1.3 * atr), 2.8 * atr)
activeDir := 1
entryPx := close
stopPx := close - risk
tp1Px := close + risk
tp2Px := close + tp2R * risk
bullSig := true
else if armedDir == -1 and close < fastR and close < open and closePos <= 0.45 and (close[1] >= fastR[1] or high >= fastR)
float rawRisk = (math.max(pbExtreme, slowR) + 0.45 * atr) - close
float risk = math.min(math.max(rawRisk, 1.3 * atr), 2.8 * atr)
activeDir := -1
entryPx := close
stopPx := close + risk
tp1Px := close - risk
tp2Px := close - tp2R * risk
bearSig := true
if bullSig or bearSig
tp1Hit := false
armedDir := 0
lastSig := bar_index
nTrades += 1
int d = bullSig ? 1 : -1
label sLb = label.new(time, bullSig ? low - 0.6 * atr : high + 0.6 * atr, bullSig ? "BUY" : "SELL", xloc = xloc.bar_time, yloc = yloc.price, style = bullSig ? label.style_label_up : label.style_label_down, color = bullSig ? bullCol : bearCol, textcolor = bullSig ? #06110D : color.white, size = size.small)
line l1 = na
line l2 = na
line l3 = na
if showPlan
l1 := line.new(time, stopPx, time, stopPx, xloc = xloc.bar_time, color = color.new(bearCol, 10), width = 2)
l2 := line.new(time, tp1Px, time, tp1Px, xloc = xloc.bar_time, color = color.new(bullCol, 30), width = 2)
l3 := line.new(time, tp2Px, time, tp2Px, xloc = xloc.bar_time, color = color.new(bullCol, 0), width = 2)
array.push(plans, Plan.new(d, entryPx, stopPx, tp1Px, tp2Px, false, false, l1, l2, l3, sLb, na, na))
if array.size(plans) > maxPlans
Plan old = array.shift(plans)
line.delete(old.slL)
line.delete(old.tp1L)
line.delete(old.tp2L)
label.delete(old.sigLb)
label.delete(old.tp1Lb)
label.delete(old.endLb)
// Extend the active plan rays to the current bar
if showPlan and activeDir != 0 and array.size(plans) > 0
Plan cur = array.last(plans)
if not cur.done
line.set_x2(cur.slL, time)
line.set_x2(cur.tp1L, time)
line.set_x2(cur.tp2L, time)
// ════════════════════════════════════════════════════════════════
// PINE SCREENER / DATA WINDOW (declared first)
// ════════════════════════════════════════════════════════════════
plot(bullSig ? 1 : bearSig ? -1 : 0, "Signal Direction", display = display.data_window + display.pine_screener)
plot(htfBias, "HTF Trend Bias", display = display.data_window + display.pine_screener)
plot(armedDir, "Pullback Armed", display = display.data_window + display.pine_screener)
plot(activeDir, "Active Plan", display = display.data_window + display.pine_screener)
plot(er * 100, "Trend Efficiency", display = display.data_window + display.pine_screener)
plot(netR, "Net R", display = display.data_window + display.pine_screener)
// ════════════════════════════════════════════════════════════════
// VISUALS — ADAPTIVE RIBBON + HTF FRONTIER
// ════════════════════════════════════════════════════════════════
plot(high, "Price Anchor High", color = color.new(color.white, 100), display = display.pane, editable = false)
plot(low, "Price Anchor Low", color = color.new(color.white, 100), display = display.pane, editable = false)
color ribBase = chop ? chopCol : fastR >= slowR ? bullCol : bearCol
pFast = plot(fastR, "Fast Ribbon", color = color.new(ribBase, chop ? 40 : 0), linewidth = 2)
pMid = plot(midR, "Mid Ribbon", color = color.new(ribBase, chop ? 60 : 35), linewidth = 1)
pSlow = plot(slowR, "Slow Ribbon", color = color.new(ribBase, chop ? 50 : 15), linewidth = 2)
fill(pFast, pMid, color = color.new(ribBase, chop ? 88 : 62), title = "Ribbon Core")
fill(pMid, pSlow, color = color.new(ribBase, chop ? 92 : 78), title = "Ribbon Body")
color frontCol = htfBias == 1 ? #22D3EE : htfBias == -1 ? #F59E0B : chopCol
plot(frontier, "HTF Trend Frontier", color = color.new(frontCol, 0), linewidth = 2, style = plot.style_stepline)
// ════════════════════════════════════════════════════════════════
// DASHBOARD
// ════════════════════════════════════════════════════════════════
string tPos = tPosIn == TblPos.BL ? position.bottom_left : tPosIn == TblPos.TL ? position.top_left : position.bottom_right
string tSz = tSizeIn == TblSize.Tiny ? size.tiny : tSizeIn == TblSize.Normal ? size.normal : size.small
var table dash = table.new(tPos, 2, 7, bgcolor = color.new(chart.bg_color, 8), border_color = color.new(chart.fg_color, 82), border_width = 1, frame_color = color.new(chart.fg_color, 70), frame_width = 1)
if showDash and barstate.islast
color fg = chart.fg_color
string tfTxt = useHtf ? htfTf : "Chart"
string biasTxt = htfBias == 1 ? "BULL" : htfBias == -1 ? "BEAR" : "N/A"
color biasCol = htfBias == 1 ? bullCol : htfBias == -1 ? bearCol : chopCol
string ribTxt = chop ? "CHOP LOCKED" : fastR >= slowR ? "RISING" : "FALLING"
color ribCol = chop ? chopCol : fastR >= slowR ? bullCol : bearCol
string setTxt = activeDir == 1 ? "LONG ACTIVE" : activeDir == -1 ? "SHORT ACTIVE" : armedDir == 1 ? "BULL PULLBACK" : armedDir == -1 ? "BEAR PULLBACK" : "WAITING"
float tp1Pct = nTrades > 0 ? 100.0 * nTp1 / nTrades : 0.0
table.cell(dash, 0, 0, "MTTRPS", text_color = fg, text_size = tSz, text_formatting = text.format_bold)
table.cell(dash, 1, 0, str.tostring(modeIn), text_color = color.new(fg, 30), text_size = tSz)
table.cell(dash, 0, 1, "HTF Trend (" + tfTxt + ")", text_color = color.new(fg, 25), text_size = tSz, text_halign = text.align_left)
table.cell(dash, 1, 1, biasTxt, text_color = biasCol, text_size = tSz, text_formatting = text.format_bold)
table.cell(dash, 0, 2, "Ribbon", text_color = color.new(fg, 25), text_size = tSz, text_halign = text.align_left)
table.cell(dash, 1, 2, ribTxt, text_color = ribCol, text_size = tSz)
table.cell(dash, 0, 3, "Setup", text_color = color.new(fg, 25), text_size = tSz, text_halign = text.align_left)
table.cell(dash, 1, 3, setTxt, text_color = fg, text_size = tSz)
table.cell(dash, 0, 4, "Signals", text_color = color.new(fg, 25), text_size = tSz, text_halign = text.align_left)
table.cell(dash, 1, 4, str.tostring(nTrades), text_color = fg, text_size = tSz)
table.cell(dash, 0, 5, "TP1 Hit Rate", text_color = color.new(fg, 25), text_size = tSz, text_halign = text.align_left)
table.cell(dash, 1, 5, str.tostring(tp1Pct, "#.0") + "%", text_color = fg, text_size = tSz)
table.cell(dash, 0, 6, "Net R", text_color = color.new(fg, 25), text_size = tSz, text_halign = text.align_left)
table.cell(dash, 1, 6, (netR >= 0 ? "+" : "") + str.tostring(netR, "#.0") + "R", text_color = netR >= 0 ? bullCol : bearCol, text_size = tSz, text_formatting = text.format_bold)
// ════════════════════════════════════════════════════════════════
// ALERTS
// ════════════════════════════════════════════════════════════════
bool frontFlip = htfBias != htfBias[1] and htfBias != 0 and htfBias[1] != 0
alertcondition(bullSig, "Bullish Pullback Signal", "MTTRPS: Bullish pullback reclaim on {{ticker}} {{interval}} at {{close}}")
alertcondition(bearSig, "Bearish Pullback Signal", "MTTRPS: Bearish pullback reclaim on {{ticker}} {{interval}} at {{close}}")
alertcondition(bullSig or bearSig, "Any Pullback Signal", "MTTRPS: Pullback signal on {{ticker}} {{interval}} at {{close}}")
alertcondition(frontFlip, "HTF Trend Frontier Flip", "MTTRPS: Higher-timeframe trend frontier flipped on {{ticker}} {{interval}}")