Trend Pullback Signals. (Entry, Stop & Two Targets)

jimmyjames4684 · study · 295 行 · 点赞 13 · TradingView 原页

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

Pine Script

//@version=6
indicator("Trend Pullback Signals", shorttitle = "TPS", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// =====================================================================================
//  TREND PULLBACK SIGNALS — one simple idea, done carefully
//  LONG : trend is up (EMA21 > EMA50 > EMA200, EMA50 rising, ADX ≥ 20)
//         price pulls back into the 21 EMA without closing below the 50 EMA
//         a bullish candle closes back above the 21 EMA AND above the prior candle's high
//  SHORT: mirror image
//  STOP : beyond the pullback swing (last 5 bars) + 0.2 ATR, never closer than 0.75 ATR
//  EXIT : half at TP1 (1R), stop to breakeven, runner to TP2 (2R), time exit after 36 bars
//  All decisions on closed candles. No repainting, no lookahead.
// =====================================================================================
 
const string G1 = "Signals"
const string G2 = "Stops & Targets"
const string G3 = "Costs"
const string G4 = "Display"
 
fastLen    = input.int(21, "Fast EMA (pullback line)", minval = 2, group = G1)
midLen     = input.int(50, "Mid EMA (must hold)", minval = 2, group = G1)
slowLen    = input.int(200, "Slow EMA (big trend)", minval = 2, group = G1)
useAdx     = input.bool(true, "Require ADX ≥", inline = "adx", group = G1)
adxMin     = input.float(20.0, "", minval = 1, step = 1, inline = "adx", group = G1)
pbBars     = input.int(3, "Pullback window (bars)", minval = 1, maxval = 10, group = G1, tooltip = "Price must have traded into the fast EMA within this many bars, without closing beyond the mid EMA.")
useSession = input.bool(true, "Trade only in session", inline = "s", group = G1)
sessStr    = input.session("0830-1500", "", inline = "s", group = G1, tooltip = "Exchange time (CT). 0830-1500 = NQ regular hours.")
 
atrLen     = input.int(14, "ATR length", minval = 1, group = G2)
swingLen   = input.int(5, "Swing lookback for stop (bars)", minval = 2, group = G2)
bufAtr     = input.float(0.2, "Stop buffer (× ATR)", minval = 0, step = 0.05, group = G2)
minStopAtr = input.float(0.75, "Min stop distance (× ATR)", minval = 0, step = 0.05, group = G2)
maxStopAtr = input.float(2.5, "Skip if stop wider than (× ATR)", minval = 0.25, step = 0.25, group = G2)
tp1R       = input.float(1.0, "TP1 (R) — closes half", minval = 0.25, step = 0.25, group = G2)
tp2R       = input.float(2.0, "TP2 (R) — closes the rest", minval = 0.5, step = 0.25, group = G2)
moveBE     = input.bool(true, "Move stop to breakeven after TP1", group = G2)
maxBars    = input.int(36, "Time exit after (bars)", minval = 2, maxval = 400, group = G2)
 
slipTicks  = input.int(1, "Slippage per market fill (ticks)", minval = 0, group = G3)
commMode   = input.string("Auto (NQ / MNQ)", "Commission", options = ["Auto (NQ / MNQ)", "Manual"], group = G3, tooltip = "Auto: $2.85/side NQ, $0.85/side MNQ.")
commManual = input.float(1.0, "Manual commission per side ($)", minval = 0, step = 0.05, group = G3)
 
showEmas = input.bool(true, "Show EMAs", group = G4)
maxShow  = input.int(5, "Trades kept on chart", minval = 1, maxval = 50, group = G4)
colTP    = input.color(#26a69a, "Target", inline = "c", group = G4)
colSL    = input.color(#ef5350, "Stop", inline = "c", group = G4)
colEntry = input.color(#b2b5be, "Entry", inline = "c", group = G4)
showDash = input.bool(true, "Show stats table", group = G4)
 
// ─────────────── CALCULATIONS ───────────────
float emaF = ta.ema(close, fastLen)
float emaM = ta.ema(close, midLen)
float emaS = ta.ema(close, slowLen)
float atrV = ta.atr(atrLen)
[diP, diM, adxV] = ta.dmi(14, 14)
 
float swingLo  = ta.lowest(low, swingLen)
float swingHi  = ta.highest(high, swingLen)
float pbLoDist = ta.lowest(low - emaF, pbBars)      // ≤ ~0 means price reached the fast EMA
float pbHiDist = ta.highest(high - emaF, pbBars)
float minCvM   = ta.lowest(close - emaM, pbBars)    // > 0 means no close below the mid EMA
float maxCvM   = ta.highest(close - emaM, pbBars)
 
bool sessOk  = not useSession or not na(time(timeframe.period, sessStr))
bool upTrend = emaF > emaM and emaM > emaS and emaM > emaM[5] and (not useAdx or (adxV >= adxMin and diP > diM))
bool dnTrend = emaF < emaM and emaM < emaS and emaM < emaM[5] and (not useAdx or (adxV >= adxMin and diM > diP))
 
bool longSetup  = upTrend and pbLoDist <= 0.1 * atrV and minCvM > 0 and close > emaF and close > high[1] and close > open and sessOk
bool shortSetup = dnTrend and pbHiDist >= -0.1 * atrV and maxCvM < 0 and close < emaF and close < low[1] and close < open and sessOk
 
float slipPts  = slipTicks * syminfo.mintick
float commSide = commMode == "Manual" ? commManual : syminfo.root == "MNQ" ? 0.85 : syminfo.root == "NQ" ? 2.85 : 0.0
float commPts  = syminfo.pointvalue > 0 ? 2.0 * commSide / syminfo.pointvalue : 0.0
 
f_floorTick(float p) => math.floor(p / syminfo.mintick + 1e-9) * syminfo.mintick
f_ceilTick(float p)  => math.ceil(p / syminfo.mintick - 1e-9) * syminfo.mintick
f_px(float p) => str.tostring(p, format.mintick)
 
// ─────────────── TYPES & METHODS ───────────────
type Trade
    int   dir
    int   bar
    float entry
    float stop
    float curStop
    float tp1
    float tp2
    float risk
    bool  tp1Hit   = false
    float realized = 0.0
    box   winBox
    box   lossBox
    line  entryLn
    line  stopLn
    line  tp1Ln
    line  tp2Ln
    label info
 
type Stats
    int   total     = 0
    int   wins      = 0
    int   tp2Hits   = 0
    int   longN     = 0
    int   longW     = 0
    int   shortN    = 0
    int   shortW    = 0
    int   skipped   = 0
    float grossWin  = 0.0
    float grossLoss = 0.0
    float netR      = 0.0
    float peakR     = 0.0
    float maxDD     = 0.0
 
method draw(Trade t) =>
    int x2 = t.bar + maxBars
    t.winBox  := box.new(t.bar, math.max(t.entry, t.tp2), x2, math.min(t.entry, t.tp2), border_color = color.new(colTP, 50), bgcolor = color.new(colTP, 82), text = "TP1 " + f_px(t.tp1) + "   TP2 " + f_px(t.tp2), text_size = size.small, text_color = colTP, text_halign = text.align_right)
    t.lossBox := box.new(t.bar, math.max(t.entry, t.stop), x2, math.min(t.entry, t.stop), border_color = color.new(colSL, 50), bgcolor = color.new(colSL, 82), text = "SL " + f_px(t.stop), text_size = size.small, text_color = colSL, text_halign = text.align_right)
    t.entryLn := line.new(t.bar, t.entry, x2, t.entry, color = colEntry, width = 2)
    t.stopLn  := line.new(t.bar, t.stop, x2, t.stop, color = colSL, width = 2)
    t.tp1Ln   := line.new(t.bar, t.tp1, x2, t.tp1, color = colTP, width = 1, style = line.style_dashed)
    t.tp2Ln   := line.new(t.bar, t.tp2, x2, t.tp2, color = colTP, width = 2)
    string txt = (t.dir == 1 ? "LONG ▲ " : "SHORT ▼ ") + f_px(t.entry) + "\nSL " + f_px(t.stop) + "\nTP1 " + f_px(t.tp1) + " · TP2 " + f_px(t.tp2)
    t.info    := label.new(t.bar, t.entry, txt, style = label.style_label_right, color = color.new(t.dir == 1 ? colTP : colSL, 10), textcolor = color.white, size = size.small)
 
method erase(Trade t) =>
    if not na(t.winBox)
        t.winBox.delete()
        t.lossBox.delete()
        t.entryLn.delete()
        t.stopLn.delete()
        t.tp1Ln.delete()
        t.tp2Ln.delete()
        t.info.delete()
        t.winBox := na
 
method markTp1(Trade t) =>
    if not na(t.winBox)
        t.info.set_text(t.info.get_text() + "\nTP1 ✓" + (moveBE ? " · stop → BE" : ""))
        if moveBE
            t.stopLn.set_y1(t.entry)
            t.stopLn.set_y2(t.entry)
    t.tp1Hit
 
method finish(Trade t, float r, string why) =>
    if not na(t.winBox)
        t.winBox.set_right(bar_index)
        t.lossBox.set_right(bar_index)
        t.entryLn.set_x2(bar_index)
        t.stopLn.set_x2(bar_index)
        t.tp1Ln.set_x2(bar_index)
        t.tp2Ln.set_x2(bar_index)
        t.winBox.set_bgcolor(color.new(colTP, 92))
        t.lossBox.set_bgcolor(color.new(colSL, 92))
        t.info.set_text(t.info.get_text() + "\n" + (r >= 0 ? "+" : "") + str.tostring(r, "#.00") + "R · " + why)
        t.info.set_color(color.new(r > 0 ? colTP : colSL, 35))
    r
 
method record(Stats s, float r, int d, bool hitTp2) =>
    s.total := s.total + 1
    if r > 0
        s.wins     := s.wins + 1
        s.grossWin := s.grossWin + r
    else
        s.grossLoss := s.grossLoss + math.abs(r)
    if hitTp2
        s.tp2Hits := s.tp2Hits + 1
    if d == 1
        s.longN := s.longN + 1
        s.longW := s.longW + (r > 0 ? 1 : 0)
    else
        s.shortN := s.shortN + 1
        s.shortW := s.shortW + (r > 0 ? 1 : 0)
    s.netR  := s.netR + r
    s.peakR := math.max(s.peakR, s.netR)
    s.maxDD := math.max(s.maxDD, s.peakR - s.netR)
    s.total
 
// ─────────────── TRADE MANAGEMENT (closed candles only) ───────────────
var array<Trade> trades = array.new<Trade>()
var array<Trade> drawn  = array.new<Trade>()
var Stats st = Stats.new()
 
if barstate.isconfirmed and trades.size() > 0
    for i = trades.size() - 1 to 0
        Trade t = trades.get(i)
        if bar_index > t.bar
            int    d     = t.dir
            float  exitR = na
            string why   = ""
            if not t.tp1Hit
                bool hitSL = d == 1 ? low <= t.stop : high >= t.stop
                bool hitT1 = d == 1 ? high >= t.tp1 : low <= t.tp1
                if hitSL
                    // stop checked first: if stop and TP1 share a candle, assume the loss
                    float slPx = (d == 1 ? math.min(open, t.stop) : math.max(open, t.stop)) - d * slipPts
                    exitR := d * (slPx - t.entry) / t.risk
                    why   := "SL"
                else if hitT1
                    t.tp1Hit   := true
                    t.curStop  := moveBE ? t.entry : t.stop
                    t.realized := 0.5 * d * (t.tp1 - t.entry) / t.risk
                    t.markTp1()
                    bool beSame = moveBE and (d == 1 ? low <= t.entry : high >= t.entry)
                    bool t2Same = d == 1 ? high >= t.tp2 : low <= t.tp2
                    if beSame
                        exitR := t.realized - 0.5 * slipPts / t.risk
                        why   := "TP1 + BE"
                    else if t2Same
                        exitR := t.realized + 0.5 * d * (t.tp2 - t.entry) / t.risk
                        why   := "TP2"
            else
                bool hitStop = d == 1 ? low <= t.curStop : high >= t.curStop
                bool hitT2   = d == 1 ? high >= t.tp2 : low <= t.tp2
                if hitStop
                    float rPx = (d == 1 ? math.min(open, t.curStop) : math.max(open, t.curStop)) - d * slipPts
                    exitR := t.realized + 0.5 * d * (rPx - t.entry) / t.risk
                    why   := moveBE ? "TP1 + BE" : "TP1 + SL"
                else if hitT2
                    exitR := t.realized + 0.5 * d * (t.tp2 - t.entry) / t.risk
                    why   := "TP2"
            if na(exitR) and bar_index - t.bar >= maxBars
                float tPx   = close - d * slipPts
                float share = t.tp1Hit ? 0.5 : 1.0
                exitR := t.realized + share * d * (tPx - t.entry) / t.risk
                why   := "Time"
            if not na(exitR)
                float net = exitR - commPts / t.risk
                t.finish(net, why)
                st.record(net, d, why == "TP2")
                trades.remove(i)
 
// ─────────────── NEW SIGNALS (closed candles only, one trade at a time) ───────────────
bool longFired  = false
bool shortFired = false
if barstate.isconfirmed and (longSetup or shortSetup) and trades.size() == 0
    int   d         = longSetup ? 1 : -1
    float entry     = close + d * slipPts
    float swingStop = d == 1 ? swingLo - bufAtr * atrV : swingHi + bufAtr * atrV
    float minStop   = entry - d * minStopAtr * atrV
    float stopPx    = d == 1 ? f_floorTick(math.min(swingStop, minStop)) : f_ceilTick(math.max(swingStop, minStop))
    float risk      = d * (entry - stopPx)
    if risk <= 0 or risk > maxStopAtr * atrV
        st.skipped := st.skipped + 1
    else
        float tp1 = d == 1 ? f_floorTick(entry + tp1R * risk) : f_ceilTick(entry - tp1R * risk)
        float tp2 = d == 1 ? f_floorTick(entry + tp2R * risk) : f_ceilTick(entry - tp2R * risk)
        Trade t = Trade.new(dir = d, bar = bar_index, entry = entry, stop = stopPx, curStop = stopPx, tp1 = tp1, tp2 = tp2, risk = risk)
        t.draw()
        drawn.push(t)
        while drawn.size() > maxShow
            Trade old = drawn.shift()
            old.erase()
        trades.push(t)
        longFired  := d == 1
        shortFired := d == -1
        alert(syminfo.ticker + " " + timeframe.period + " | " + (d == 1 ? "LONG" : "SHORT") + " " + f_px(entry) + " | SL " + f_px(stopPx) + " | TP1 " + f_px(tp1) + " | TP2 " + f_px(tp2), alert.freq_once_per_bar_close)
 
// ─────────────── PLOTS ───────────────
plot(showEmas ? emaF : na, "EMA fast", color = color.new(#ff9800, 10), linewidth = 1)
plot(showEmas ? emaM : na, "EMA mid", color = color.new(#2962ff, 10), linewidth = 2)
plot(showEmas ? emaS : na, "EMA slow", color = color.new(#9c27b0, 20), linewidth = 2)
plotshape(longFired, "Long", shape.triangleup, location.belowbar, colTP, size = size.small, text = "LONG", textcolor = colTP)
plotshape(shortFired, "Short", shape.triangledown, location.abovebar, colSL, size = size.small, text = "SHORT", textcolor = colSL)
 
// ─────────────── STATS TABLE ───────────────
var table dash = table.new(position.top_right, 2, 12, bgcolor = color.new(#131722, 10), frame_color = color.new(#434651, 0), frame_width = 1, border_color = color.new(#2a2e39, 0), border_width = 1)
 
f_cell(int r, string k, string v, color vc) =>
    table.cell(dash, 0, r, k, text_color = color.new(#b2b5be, 0), text_halign = text.align_left, text_size = size.small)
    table.cell(dash, 1, r, v, text_color = vc, text_halign = text.align_right, text_size = size.small)
 
f_pct(int a, int b) => b > 0 ? str.tostring(100.0 * a / b, "#.0") + "%" : "—"
f_r(float x) => (x >= 0 ? "+" : "") + str.tostring(x, "#.00") + "R"
 
if barstate.islast and showDash
    float wr = st.total > 0 ? 100.0 * st.wins / st.total : 0.0
    string trendTxt = upTrend ? "UP ▲" : dnTrend ? "DOWN ▼" : "NONE — wait"
    color  trendCol = upTrend ? colTP : dnTrend ? colSL : color.new(#b2b5be, 0)
    string pfTxt = st.total == 0 ? "—" : st.grossLoss > 0 ? str.tostring(st.grossWin / st.grossLoss, "#.00") : "∞"
    table.cell(dash, 0, 0, "TREND PULLBACK", text_color = color.white, text_halign = text.align_left, text_size = size.small, bgcolor = color.new(#2a2e39, 0))
    table.cell(dash, 1, 0, "", bgcolor = color.new(#2a2e39, 0), text_size = size.small)
    f_cell(1, "Trend now", trendTxt, trendCol)
    f_cell(2, "Trades", str.tostring(st.total), color.white)
    f_cell(3, "Win rate", f_pct(st.wins, st.total), st.total > 0 and wr >= 60 ? colTP : color.white)
    f_cell(4, "Reached TP2", f_pct(st.tp2Hits, st.total), color.white)
    f_cell(5, "Profit factor", pfTxt, color.white)
    f_cell(6, "Net result", st.total > 0 ? f_r(st.netR) : "—", st.netR >= 0 ? colTP : colSL)
    f_cell(7, "Avg per trade", st.total > 0 ? f_r(st.netR / st.total) : "—", st.netR >= 0 ? colTP : colSL)
    f_cell(8, "Max drawdown", st.total > 0 ? "−" + str.tostring(st.maxDD, "#.00") + "R" : "—", colSL)
    f_cell(9, "Longs (win%)", str.tostring(st.longN) + " · " + f_pct(st.longW, st.longN), color.white)
    f_cell(10, "Shorts (win%)", str.tostring(st.shortN) + " · " + f_pct(st.shortW, st.shortN), color.white)
    f_cell(11, "Skipped (stop too wide)", str.tostring(st.skipped), color.new(#b2b5be, 0))
 
alertcondition(longFired, "LONG signal", "TPS LONG on {{ticker}} {{interval}} at {{close}}")
alertcondition(shortFired, "SHORT signal", "TPS SHORT on {{ticker}} {{interval}} at {{close}}")

← 返回列表