本页源码来自 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("Market Structure Trap & Breaker Reversal [PhenLabs]", shorttitle = "MSTBR [PhenLabs]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 300)
// ═══════════════════════════════════════════════════════════════════════════════
// ENUMS
// ═══════════════════════════════════════════════════════════════════════════════
enum EntryMode
snap = "Trap Snapback Close"
retest = "Breaker Zone Retest"
enum TblPos
br = "Bottom Right"
bl = "Bottom Left"
tl = "Top Left"
enum TblSize
tiny = "Tiny"
small = "Small"
normal = "Normal"
// ═══════════════════════════════════════════════════════════════════════════════
// INPUTS
// ═══════════════════════════════════════════════════════════════════════════════
const string G_S = "Structure & Trap"
const string G_F = "Trap Quality Filters"
const string G_R = "Risk Plan"
const string G_V = "Visuals"
int pivLen = input.int(5, "Swing Length", minval = 2, maxval = 20, group = G_S, tooltip = "Bars on each side required to confirm a swing high or swing low. The swing is only used after it is fully confirmed, so levels never repaint.")
int trapWin = input.int(5, "Trap Window (bars)", minval = 1, maxval = 12, group = G_S, tooltip = "After price closes beyond a swing, the breakout is treated as a possible trap for this many bars. A close back inside the broken level within the window confirms the failed break.")
EntryMode entryMode = input.enum(EntryMode.snap, "Entry Mode", group = G_S, tooltip = "Trap Snapback Close enters on the candle that closes back inside the broken level. Breaker Zone Retest waits for price to revisit the flipped breaker zone and reject it.")
int retestWait = input.int(10, "Retest Wait (bars)", minval = 2, maxval = 40, group = G_S, active = entryMode == EntryMode.retest, tooltip = "Maximum bars to wait for a breaker zone retest before the armed setup expires.")
float minBody = input.float(0.45, "Min Snapback Body (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = G_F, tooltip = "The snapback candle body must be at least this many ATRs. Filters weak drifts back inside the level.")
bool useTrend = input.bool(true, "Trend Filter EMA", group = G_F, inline = "tr", tooltip = "Only take bearish traps below the EMA and bullish traps above it. Turning this off roughly triples signal count but lowers average R in testing.")
int trendLen = input.int(100, "", minval = 10, maxval = 400, group = G_F, inline = "tr", active = useTrend)
float slBuf = input.float(0.25, "Stop Buffer Beyond Trap Extreme (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = G_R)
float tp1R = input.float(1.0, "Targets: TP1 / TP2 (R)", minval = 0.3, maxval = 5.0, step = 0.1, group = G_R, inline = "tp")
float tp2R = input.float(2.4, "", minval = 0.5, maxval = 10.0, step = 0.1, group = G_R, inline = "tp")
bool useBE = input.bool(true, "Move Stop to Breakeven After TP1", group = G_R, tooltip = "Half the position is closed at TP1. When enabled, the runner stop moves to entry once TP1 prints.")
bool showSpot = input.bool(true, "Trap Excursion Highlight", group = G_V)
bool showZones = input.bool(true, "Breaker Zones", group = G_V)
bool showPlan = input.bool(true, "Stop & Target Rays", group = G_V)
int maxHist = input.int(12, "Setups Kept on Chart", minval = 1, maxval = 40, group = G_V)
color bullCol = input.color(#089981, "Bull / Bear / Trap", group = G_V, inline = "col")
color bearCol = input.color(#F23645, "", group = G_V, inline = "col")
color trapCol = input.color(#F59E0B, "", group = G_V, inline = "col")
TblPos tblPos = input.enum(TblPos.br, "Dashboard Position", group = G_V, inline = "tb")
TblSize tblSize = input.enum(TblSize.small, "", group = G_V, inline = "tb")
// Fixed engine constants (validated defaults)
const float MAX_BRK_ATR = 1.8
const float CLOSE_POS = 0.40
const float ATR_FLOOR = 0.65
const float MIN_RISK_ATR = 0.35
const float MAX_RISK_ATR = 3.2
// ═══════════════════════════════════════════════════════════════════════════════
// TYPES & HELPERS
// ═══════════════════════════════════════════════════════════════════════════════
type Setup
line lvl
box trapBox
line trapCap
box zone
label sig
line sl
line t1
line t2
label t1Tag
label out
method del(Setup this) =>
if not na(this.lvl)
line.delete(this.lvl)
if not na(this.trapBox)
box.delete(this.trapBox)
if not na(this.trapCap)
line.delete(this.trapCap)
if not na(this.zone)
box.delete(this.zone)
if not na(this.sig)
label.delete(this.sig)
if not na(this.sl)
line.delete(this.sl)
if not na(this.t1)
line.delete(this.t1)
if not na(this.t2)
line.delete(this.t2)
if not na(this.t1Tag)
label.delete(this.t1Tag)
if not na(this.out)
label.delete(this.out)
f_pos(TblPos p) =>
switch p
TblPos.bl => position.bottom_left
TblPos.tl => position.top_left
=> position.bottom_right
f_size(TblSize s) =>
switch s
TblSize.tiny => size.tiny
TblSize.normal => size.normal
=> size.small
f_fmtR(float r) =>
(r >= 0 ? "+" : "") + str.tostring(r, "#.#") + "R"
// Draws the broken level, borderless amber trap excursion, extreme cap, and non-overlapping breaker zone
f_makeSetup(int dir, float lvl, int lvlTime, int brkTime, float ext, float zTop, float zBot, int nowTime, int barMs) =>
Setup s = Setup.new()
color dCol = dir == 1 ? bullCol : bearCol
s.lvl := line.new(lvlTime, lvl, nowTime, lvl, xloc = xloc.bar_time, color = color.new(chart.fg_color, 52), style = line.style_dotted, width = 1)
if showSpot
float tTop = dir == -1 ? ext : lvl
float tBot = dir == -1 ? lvl : ext
s.trapBox := box.new(brkTime, tTop, nowTime, tBot, xloc = xloc.bar_time, border_color = na, bgcolor = color.new(trapCol, 86))
s.trapCap := line.new(brkTime, ext, nowTime, ext, xloc = xloc.bar_time, color = trapCol, width = 2)
if showZones
s.zone := box.new(nowTime, zTop, nowTime + barMs, zBot, xloc = xloc.bar_time, border_color = color.new(dCol, 62), border_width = 1, bgcolor = color.new(dCol, 88), text = "", text_color = color.new(dCol, 25), text_size = size.tiny, text_halign = text.align_right, text_valign = text.align_center)
s
// ═══════════════════════════════════════════════════════════════════════════════
// CORE SERIES
// ═══════════════════════════════════════════════════════════════════════════════
max_bars_back(time, 64)
float atrV = ta.atr(14)
float atrMa = ta.sma(atrV, 50)
float emaV = ta.ema(close, trendLen)
float ph = ta.pivothigh(high, pivLen, pivLen)
float pl = ta.pivotlow(low, pivLen, pivLen)
int pivT = time[pivLen]
bool inCash = not na(time(timeframe.period, "0800-1600", "America/New_York"))
int secPerBar = timeframe.in_seconds()
bool hasBarTime = not na(secPerBar) and secPerBar > 0 and not timeframe.isweekly and not timeframe.ismonthly
int barMs = hasBarTime ? secPerBar * 1000 : 0
// ═══════════════════════════════════════════════════════════════════════════════
// STATE
// ═══════════════════════════════════════════════════════════════════════════════
var float swH = na
var int swHT = na
var bool hUsed = true
var float swL = na
var int swLT = na
var bool lUsed = true
var bool upAct = false
var int upBar = na
var float upLvl = na
var int upLvlT = na
var int upBrkT = na
var float upExt = na
var int upExtT = na
var float upZT = na
var float upZB = na
var bool dnAct = false
var int dnBar = na
var float dnLvl = na
var int dnLvlT = na
var int dnBrkT = na
var float dnExt = na
var int dnExtT = na
var float dnZT = na
var float dnZB = na
var int pendDir = 0
var int pendBar = na
var float pendTop = na
var float pendBot = na
var float pendExt = na
var Setup pend = na
var int tDir = 0
var float tEn = na
var float tSl = na
var float tSl0 = na
var float tT1 = na
var float tT2 = na
var bool tHit = false
var bool tCash = false
var int tStartBar = na
var Setup cur = na
var label aSl = na
var label aT1 = na
var label aT2 = na
var array<Setup> hist = array.new<Setup>()
var int nClosed = 0
var int nWin = 0
var float netR = 0.0
var float grossW = 0.0
var float grossL = 0.0
var int cashN = 0
var float cashR = 0.0
var int offN = 0
var float offR = 0.0
int sigNow = 0
int armedNow = 0
// ═══════════════════════════════════════════════════════════════════════════════
// CLOSED-BAR STATE MACHINE
// ═══════════════════════════════════════════════════════════════════════════════
if barstate.isconfirmed and not na(atrV) and atrV > 0
float a = atrV
// 1) Manage the active trade (stop checked first on the same bar)
if tDir != 0
bool closed = false
float pnl = 0.0
bool win = false
float exitPx = na
bool hitNow = false
if tDir == 1
if low <= tSl
pnl := tHit ? 0.5 * tp1R + (useBE ? 0.0 : -0.5) : -1.0
win := tHit
exitPx := tSl
closed := true
else
if not tHit and high >= tT1
tHit := true
hitNow := true
if useBE
tSl := tEn
if high >= tT2
pnl := 0.5 * tp1R + 0.5 * tp2R
win := true
exitPx := tT2
closed := true
else
if high >= tSl
pnl := tHit ? 0.5 * tp1R + (useBE ? 0.0 : -0.5) : -1.0
win := tHit
exitPx := tSl
closed := true
else
if not tHit and low <= tT1
tHit := true
hitNow := true
if useBE
tSl := tEn
if low <= tT2
pnl := 0.5 * tp1R + 0.5 * tp2R
win := true
exitPx := tT2
closed := true
if not na(cur)
if not na(cur.sl)
cur.sl.set_x2(time)
if hitNow and useBE
cur.sl.set_y1(tEn)
cur.sl.set_y2(tEn)
cur.sl.set_color(color.new(color.gray, 35))
cur.sl.set_style(line.style_dashed)
cur.sl.set_width(1)
if not na(cur.t1)
cur.t1.set_x2(time)
if not na(cur.t2)
cur.t2.set_x2(time)
if not na(cur.zone)
cur.zone.set_right(time)
if not na(tStartBar) and bar_index - tStartBar >= 5
cur.zone.set_text("BREAKER")
if closed
nClosed += 1
nWin += win ? 1 : 0
netR += pnl
grossW += pnl > 0 ? pnl : 0.0
grossL += pnl < 0 ? -pnl : 0.0
if tCash
cashN += 1
cashR += pnl
else
offN += 1
offR += pnl
if not na(cur)
if not tHit and not na(cur.t1)
line.delete(cur.t1)
cur.t1 := na
if pnl < tp1R and not na(cur.t2)
line.delete(cur.t2)
cur.t2 := na
if pnl >= tp1R
if tHit and showPlan
cur.t1Tag := label.new(time, tT1, " TP1 ✓", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_none, textcolor = bullCol, size = size.tiny, textalign = text.align_left)
cur.out := label.new(time, exitPx, "TP2 ✓ " + f_fmtR(pnl), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_label_left, color = bullCol, textcolor = color.white, size = size.tiny)
else if pnl > 0
cur.out := label.new(time, tT1, " TP1 · BE " + f_fmtR(pnl), xloc = xloc.bar_time, yloc = yloc.price, style = label.style_none, textcolor = bullCol, size = size.tiny, textalign = text.align_left)
else
bool aboveExit = tDir == -1
float outY = aboveExit ? math.max(exitPx, high) + 0.14 * a : math.min(exitPx, low) - 0.14 * a
string oTxt = pnl < 0 ? "✕ " + f_fmtR(pnl) : "BE 0R"
color oCol = pnl < 0 ? bearCol : color.gray
cur.out := label.new(time, outY, oTxt, xloc = xloc.bar_time, yloc = yloc.price, style = label.style_none, textcolor = oCol, size = size.tiny)
label.delete(aSl)
label.delete(aT1)
label.delete(aT2)
aSl := na
aT1 := na
aT2 := na
tDir := 0
cur := na
else if showPlan
if not na(aSl)
aSl.set_xy(time, tSl)
if tHit and useBE
aSl.set_text(" BE")
aSl.set_textcolor(color.gray)
aT1.set_xy(time, tT1)
if tHit
aT1.set_text(" TP1 ✓")
aT2.set_xy(time, tT2)
// 2) Register newly confirmed swings
if not na(ph)
swH := ph
swHT := pivT
hUsed := false
if not na(pl)
swL := pl
swLT := pivT
lUsed := false
int sig = 0
float sigExt = na
// 3) Armed breaker-zone retest
if pendDir != 0
bool expired = bar_index - pendBar > retestWait or (pendDir == 1 and close < pendExt) or (pendDir == -1 and close > pendExt)
if expired
pendDir := 0
if not na(pend)
pend.del()
pend := na
else if tDir == 0
bool longRt = pendDir == 1 and low <= pendTop and close >= pendBot and close > open
bool shortRt = pendDir == -1 and high >= pendBot and close <= pendTop and close < open
if longRt or shortRt
sig := pendDir
sigExt := pendExt
pendDir := 0
else if not na(pend) and not na(pend.zone)
pend.zone.set_right(time)
pend.lvl.set_x2(time)
// 4) Failed-breakout trap detection
int trapSig = 0
float trapExt = na
int trapExtT = na
float trapLvl = na
int trapLvlT = na
int trapBrkT = na
float zT = na
float zB = na
if upAct
if high > upExt
upExt := high
upExtT := time
if bar_index - upBar > trapWin
upAct := false
else if close < upLvl and close < open
float rg = math.max(high - low, syminfo.mintick)
bool ok = not na(atrMa) and a >= ATR_FLOOR * atrMa and (close - low) / rg <= CLOSE_POS and math.abs(close - open) / a >= minBody
if useTrend
ok := ok and close < emaV
if ok
trapSig := -1
trapExt := upExt
trapExtT := upExtT
trapLvl := upLvl
trapLvlT := upLvlT
trapBrkT := upBrkT
zT := upZT
zB := upZB
upAct := false
if dnAct
if low < dnExt
dnExt := low
dnExtT := time
if bar_index - dnBar > trapWin
dnAct := false
else if close > dnLvl and close > open and trapSig == 0
float rg = math.max(high - low, syminfo.mintick)
bool ok = not na(atrMa) and a >= ATR_FLOOR * atrMa and (close - low) / rg >= 1.0 - CLOSE_POS and math.abs(close - open) / a >= minBody
if useTrend
ok := ok and close > emaV
if ok
trapSig := 1
trapExt := dnExt
trapExtT := dnExtT
trapLvl := dnLvl
trapLvlT := dnLvlT
trapBrkT := dnBrkT
zT := dnZT
zB := dnZB
dnAct := false
if trapSig != 0
if entryMode == EntryMode.snap
sig := trapSig
sigExt := trapExt
else
if not na(pend)
pend.del()
pend := f_makeSetup(trapSig, trapLvl, trapLvlT, trapBrkT, trapExt, zT, zB, time, barMs)
pendDir := trapSig
pendBar := bar_index
pendTop := zT
pendBot := zB
pendExt := trapExt
armedNow := trapSig
// 5) Fresh close-through breakouts arm a trap watch
if not hUsed and not na(swH) and close > swH
hUsed := true
if close - swH <= MAX_BRK_ATR * a
upAct := true
upBar := bar_index
upLvl := swH
upLvlT := swHT
upBrkT := time
upExt := high
upExtT := time
upZT := math.max(open, swH + 0.15 * a)
upZB := math.min(open, swH - 0.15 * a)
if not lUsed and not na(swL) and close < swL
lUsed := true
if swL - close <= MAX_BRK_ATR * a
dnAct := true
dnBar := bar_index
dnLvl := swL
dnLvlT := swLT
dnBrkT := time
dnExt := low
dnExtT := time
dnZT := math.max(open, swL + 0.15 * a)
dnZB := math.min(open, swL - 0.15 * a)
// 6) Open the trade on the confirmed signal close
if sig != 0 and tDir == 0
float s = sigExt - sig * slBuf * a
float r = (close - s) * sig
Setup st = na
if entryMode == EntryMode.snap
if r >= MIN_RISK_ATR * a and r <= MAX_RISK_ATR * a
st := f_makeSetup(sig, trapLvl, trapLvlT, trapBrkT, trapExt, zT, zB, time, barMs)
else
if r >= MIN_RISK_ATR * a and r <= MAX_RISK_ATR * a
st := pend
else if not na(pend)
pend.del()
pend := na
if not na(st)
tDir := sig
tEn := close
tSl := s
tSl0 := s
tT1 := close + sig * tp1R * r
tT2 := close + sig * tp2R * r
tHit := false
tCash := inCash
tStartBar := bar_index
sigNow := sig
color dCol = sig == 1 ? bullCol : bearCol
float sigY = entryMode == EntryMode.snap ? (sig == 1 ? math.min(low, sigExt) - 0.16 * a : math.max(high, sigExt) + 0.16 * a) : (sig == 1 ? low - 0.16 * a : high + 0.16 * a)
st.sig := label.new(time, sigY, sig == 1 ? "TRAP LONG" : "TRAP SHORT", xloc = xloc.bar_time, yloc = yloc.price, style = sig == 1 ? label.style_label_up : label.style_label_down, color = dCol, textcolor = color.white, size = size.small)
if showPlan
int x1 = time
int x2 = time + barMs
st.sl := line.new(x1, tSl0, x2, tSl0, xloc = xloc.bar_time, color = color.new(bearCol, 20), width = 1)
st.t1 := line.new(x1, tT1, x2, tT1, xloc = xloc.bar_time, color = color.new(bullCol, 35), width = 1, style = line.style_dashed)
st.t2 := line.new(x1, tT2, x2, tT2, xloc = xloc.bar_time, color = bullCol, width = 2)
aSl := label.new(x2, tSl0, " SL", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_none, textcolor = bearCol, size = size.tiny, textalign = text.align_left)
aT1 := label.new(x2, tT1, " TP1 " + str.tostring(tp1R, "#.#") + "R", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_none, textcolor = bullCol, size = size.tiny, textalign = text.align_left)
aT2 := label.new(x2, tT2, " TP2 " + str.tostring(tp2R, "#.#") + "R", xloc = xloc.bar_time, yloc = yloc.price, style = label.style_none, textcolor = bullCol, size = size.tiny, textalign = text.align_left)
cur := st
hist.push(st)
if hist.size() > maxHist
Setup old = hist.shift()
old.del()
// ═══════════════════════════════════════════════════════════════════════════════
// PINE SCREENER OUTPUTS (first plots), TREND EMA & PRICE ANCHORS
// ═══════════════════════════════════════════════════════════════════════════════
float winRate = nClosed > 0 ? 100.0 * nWin / nClosed : na
plot(sigNow, "Screener: Trap Signal (+1 Long, -1 Short)", display = display.data_window + display.pine_screener)
plot(tDir, "Screener: Active Trade (+1 Long, -1 Short)", display = display.data_window + display.pine_screener)
plot(pendDir, "Screener: Breaker Armed (+1 / -1)", display = display.data_window + display.pine_screener)
plot(winRate, "Screener: TP1+ Hit Rate %", display = display.data_window + display.pine_screener)
plot(netR, "Screener: Net R", display = display.data_window + display.pine_screener)
plot(useTrend ? emaV : na, "Trend Regime EMA", color = close >= emaV ? color.new(bullCol, 35) : color.new(bearCol, 35), linewidth = 2)
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)
// ═══════════════════════════════════════════════════════════════════════════════
// ALERTS
// ═══════════════════════════════════════════════════════════════════════════════
alertcondition(sigNow == 1, "Bullish Trap Reversal", "MSTBR: Bullish failed-breakdown trap confirmed. LONG plan active on {{ticker}} {{interval}}.")
alertcondition(sigNow == -1, "Bearish Trap Reversal", "MSTBR: Bearish failed-breakout trap confirmed. SHORT plan active on {{ticker}} {{interval}}.")
alertcondition(sigNow != 0, "Any Trap Reversal", "MSTBR: Trap reversal confirmed on {{ticker}} {{interval}}.")
alertcondition(armedNow != 0, "Breaker Zone Armed", "MSTBR: Trap confirmed, breaker zone armed for a retest on {{ticker}} {{interval}}.")
// ═══════════════════════════════════════════════════════════════════════════════
// DASHBOARD (badge-safe, compact 6 rows, bottom right by default)
// ═══════════════════════════════════════════════════════════════════════════════
var table dash = na
var TblPos lastPos = TblPos.br
if na(dash) or tblPos != lastPos
if not na(dash)
table.delete(dash)
dash := table.new(f_pos(tblPos), 2, 6, bgcolor = color.new(chart.bg_color, 2), frame_color = color.new(chart.fg_color, 72), frame_width = 1, border_color = color.new(chart.fg_color, 86), border_width = 1)
lastPos := tblPos
if barstate.islast
string ts = f_size(tblSize)
color txt = chart.fg_color
color dim = color.new(chart.fg_color, 40)
string stTxt = tDir == 1 ? "LONG active" : tDir == -1 ? "SHORT active" : pendDir == 1 ? "Bull breaker armed" : pendDir == -1 ? "Bear breaker armed" : upAct or dnAct ? "Breakout watch" : "Scanning"
color stCol = tDir == 1 or pendDir == 1 ? bullCol : tDir == -1 or pendDir == -1 ? bearCol : upAct or dnAct ? trapCol : dim
float pf = grossL > 0 ? grossW / grossL : na
string wrTxt = na(winRate) ? "-" : str.tostring(winRate, "#.0") + "%"
string pfTxt = na(pf) ? "-" : str.tostring(pf, "#.00")
table.cell(dash, 0, 0, "MSTBR", text_color = txt, text_size = ts, text_formatting = text.format_bold, text_halign = text.align_left)
table.cell(dash, 1, 0, entryMode == EntryMode.snap ? "Snapback" : "Retest", text_color = trapCol, text_size = ts, text_halign = text.align_right)
table.cell(dash, 0, 1, "State", text_color = dim, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, 1, stTxt, text_color = stCol, text_size = ts, text_halign = text.align_right)
table.cell(dash, 0, 2, "Trades · TP1+", text_color = dim, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, 2, str.tostring(nClosed) + " · " + wrTxt, text_color = txt, text_size = ts, text_halign = text.align_right)
table.cell(dash, 0, 3, "Net R · PF", text_color = dim, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, 3, f_fmtR(netR) + " · " + pfTxt, text_color = netR >= 0 ? bullCol : bearCol, text_size = ts, text_halign = text.align_right)
table.cell(dash, 0, 4, "Cash 08-16 ET", text_color = dim, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, 4, f_fmtR(cashR) + " (" + str.tostring(cashN) + ")", text_color = cashR >= 0 ? bullCol : bearCol, text_size = ts, text_halign = text.align_right)
table.cell(dash, 0, 5, "Off-Hours", text_color = dim, text_size = ts, text_halign = text.align_left)
table.cell(dash, 1, 5, f_fmtR(offR) + " (" + str.tostring(offN) + ")", text_color = offR >= 0 ? bullCol : bearCol, text_size = ts, text_halign = text.align_right)