本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("EMA Channel Reversal (Inside / Engulfing)", shorttitle="Snapback Scalper", overlay=true, max_labels_count=500, max_lines_count=500)
// ─────────────────────────────── Inputs ───────────────────────────────
grpE = "EMA Channel"
len = input.int(20, "EMA length", minval=1, group=grpE)
showFill = input.bool(true, "Shade channel", group=grpE)
grpP = "Confirmation patterns"
useInside = input.bool(true, "Inside bar", group=grpP)
useEngulf = input.bool(true, "Engulfing bar", group=grpP)
needColors = input.bool(true, "Require color flip (red→green for buys, green→red for sells)", group=grpP)
strict = input.bool(true, "Both pattern candles must be fully outside the band", group=grpP)
grpR = "Trade rules"
bufTicks = input.int(1, "Entry/stop offset (ticks beyond candle high/low)", minval=0, group=grpR)
showTrades = input.bool(true, "Show entry/stop lines & results", group=grpR)
showStats = input.bool(true, "Show stats table", group=grpR)
// ─────────────────────────────── EMA channel ───────────────────────────────
emaHi = ta.ema(high, len)
emaMid = ta.ema(close, len)
emaLo = ta.ema(low, len)
pHi = plot(emaHi, "Upper EMA (highs)", color=color.red)
pMid = plot(emaMid, "Center EMA (closes)", color=color.gray, linewidth=2)
pLo = plot(emaLo, "Lower EMA (lows)", color=color.green)
fill(pHi, pLo, color = showFill ? color.new(color.blue, 92) : na, title="Channel fill")
// ─────────────────────── Rule 1: candle fully outside band ───────────────────────
fullBelow = high < emaLo // even the HIGH is below the lower EMA
fullAbove = low > emaHi // even the LOW is above the upper EMA
// ─────────────────────── Rule 2: confirmation pattern ───────────────────────
isGreen = close > open
isRed = close < open
inside = high < high[1] and low > low[1]
engulf = high > high[1] and low < low[1]
bullColorsOK = not needColors or (isRed[1] and isGreen)
bearColorsOK = not needColors or (isGreen[1] and isRed)
bullPattern = bullColorsOK and ((useInside and inside) or (useEngulf and engulf))
bearPattern = bearColorsOK and ((useInside and inside) or (useEngulf and engulf))
buySetup = fullBelow and bullPattern and (not strict or fullBelow[1])
sellSetup = fullAbove and bearPattern and (not strict or fullAbove[1])
// ─────────────────────── Trade engine (Rules 3–5) ───────────────────────
tick = syminfo.mintick
var int pos = 0 // 1 = long, -1 = short, 0 = flat
var float entryPx = na
var float stopPx = na
var float pendLevel = na // stop-entry price for next candle
var float pendStop = na
var int pendDir = 0
var int pendBar = na
var line entryLn = na
var line stopLn = na
var int wins = 0
var int losses = 0
var float totalR = 0.0
bool entered = false
int enteredDir = 0
int exitCode = 0 // 1 = target, -1 = stop
int exitDir = 0
float exitPx = na
float tradeR = na
// Rule 3: order is only valid on the very next candle
if pos == 0 and pendDir != 0 and pendBar == bar_index - 1
if pendDir == 1 and high >= pendLevel
pos := 1
entryPx := math.max(open, pendLevel)
stopPx := pendStop
entered := true
else if pendDir == -1 and low <= pendLevel
pos := -1
entryPx := math.min(open, pendLevel)
stopPx := pendStop
entered := true
if entered
enteredDir := pos
if showTrades
entryLn := line.new(bar_index, entryPx, bar_index, entryPx, color=color.blue, width=2)
stopLn := line.new(bar_index, stopPx, bar_index, stopPx, color=color.red, width=2)
pendDir := 0 // unfilled order is cancelled
// Rules 4 & 5: stop beyond signal candle, exit when price touches center EMA
// (stop is checked first = conservative when both hit on the same candle)
if pos == 1
if low <= stopPx
exitCode := -1
exitPx := entered ? stopPx : math.min(open, stopPx)
else if high >= emaMid
exitCode := 1
exitPx := entered ? emaMid : math.max(open, emaMid)
else if pos == -1
if high >= stopPx
exitCode := -1
exitPx := entered ? stopPx : math.max(open, stopPx)
else if low <= emaMid
exitCode := 1
exitPx := entered ? emaMid : math.min(open, emaMid)
if pos != 0 and showTrades
line.set_x2(entryLn, bar_index)
line.set_x2(stopLn, bar_index)
if exitCode != 0
exitDir := pos
risk = math.abs(entryPx - stopPx)
tradeR := risk > 0 ? (exitPx - entryPx) * pos / risk : 0.0
totalR += tradeR
if tradeR > 0
wins += 1
else
losses += 1
if showTrades
label.new(bar_index, pos == 1 ? high : low, (exitCode == 1 ? "TP " : "SL ") + str.tostring(tradeR, "#.##") + "R",
style = pos == 1 ? label.style_label_down : label.style_label_up,
color = tradeR > 0 ? color.green : color.red, textcolor=color.white, size=size.small)
pos := 0
// New setup → stop-entry order for the next candle (only when flat)
bool newBuy = false
bool newSell = false
if pos == 0
if buySetup
pendDir := 1
pendLevel := high + bufTicks * tick
pendStop := low - bufTicks * tick
pendBar := bar_index
newBuy := true
else if sellSetup
pendDir := -1
pendLevel := low - bufTicks * tick
pendStop := high + bufTicks * tick
pendBar := bar_index
newSell := true
// ─────────────────────────────── Visuals ───────────────────────────────
plotshape(newBuy, "Buy setup", shape.triangleup, location.belowbar, color.green, size=size.small)
plotshape(newSell, "Sell setup", shape.triangledown, location.abovebar, color.red, size=size.small)
plotshape(enteredDir == 1, "Long entry", shape.labelup, location.belowbar, color.green, text="BUY", textcolor=color.white, size=size.tiny)
plotshape(enteredDir == -1, "Short entry", shape.labeldown, location.abovebar, color.red, text="SELL", textcolor=color.white, size=size.tiny)
// Pending stop-entry level (shown on the signal candle)
plot(newBuy ? pendLevel : na, "Pending buy stop", color=color.green, style=plot.style_circles, linewidth=2)
plot(newSell ? pendLevel : na, "Pending sell stop", color=color.red, style=plot.style_circles, linewidth=2)
var table stats = table.new(position.top_right, 2, 4, bgcolor=color.new(color.black, 20), border_width=1)
if showStats and barstate.islast
total = wins + losses
table.cell(stats, 0, 0, "Trades", text_color=color.white)
table.cell(stats, 1, 0, str.tostring(total), text_color=color.white)
table.cell(stats, 0, 1, "Win rate", text_color=color.white)
table.cell(stats, 1, 1, total > 0 ? str.tostring(wins * 100.0 / total, "#.0") + "%" : "-", text_color=color.white)
table.cell(stats, 0, 2, "Net R", text_color=color.white)
table.cell(stats, 1, 2, str.tostring(totalR, "#.##"), text_color = totalR >= 0 ? color.lime : color.red)
table.cell(stats, 0, 3, "Avg R", text_color=color.white)
table.cell(stats, 1, 3, total > 0 ? str.tostring(totalR / total, "#.##") : "-", text_color=color.white)
// ─────────────────────────────── Alerts ───────────────────────────────
alertcondition(newBuy, "Buy setup", "EMA Channel: bullish setup – buy stop above signal candle high (valid 1 bar)")
alertcondition(newSell, "Sell setup", "EMA Channel: bearish setup – sell stop below signal candle low (valid 1 bar)")
alertcondition(enteredDir == 1, "Long entry", "EMA Channel: long triggered")
alertcondition(enteredDir == -1,"Short entry", "EMA Channel: short triggered")
alertcondition(exitCode == 1, "Target hit", "EMA Channel: center EMA touched – exit")
alertcondition(exitCode == -1, "Stop hit", "EMA Channel: stop loss hit")