Gold 1H Sweep + Fib Pullback

mikandoinlove · study · 371 行 · 点赞 27 · TradingView 原页

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

Pine Script

//@version=6
// ════════════════════════════════════════════════════════════════════
//  Gold 1H Sweep + Fib Pullback (GSF)
//  Flow:  liquidity sweep -> impulse leg -> pullback into 50-61.8% zone
//         -> rejection candle closes out of the zone -> ENTRY
//  One active trade at a time. Signals are evaluated on bar close only
//  (no intrabar repaint). Built for XAUUSD on the 1H chart.
//
//  ALERTS: Create Alert -> Condition: "Gold 1H Sweep + Fib Pullback"
//    - "Any alert() function call" = rich messages with Entry/SL/TP1-4
//    - or pick a specific alertcondition (Buy, Sell, TP1..TP4, SL, Sweeps)
//    Set "Once Per Bar Close".
// ════════════════════════════════════════════════════════════════════
indicator("Gold 1H Sweep + Fib Pullback", shorttitle="GSF", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=200)
 
// ───────────────────────────── INPUTS ─────────────────────────────
grpS = "1) Liquidity sweep"
pivLen      = input.int(5, "Swing length (pivot left/right)", minval=2, maxval=20, group=grpS)
maxAge      = input.int(60, "Max age of a liquidity level (bars)", minval=10, group=grpS)
minSweepATR = input.float(0.05, "Min sweep depth (x ATR)", minval=0.0, step=0.01, group=grpS)
 
grpF = "2) Fibonacci pullback"
minLegATR  = input.float(1.5, "Min impulse leg after sweep (x ATR)", minval=0.5, step=0.1, group=grpF)
fibA       = input.float(0.5, "Golden zone - start", minval=0.2, maxval=0.9, step=0.01, group=grpF)
fibB       = input.float(0.618, "Golden zone - end", minval=0.3, maxval=0.95, step=0.01, group=grpF)
expireBars = input.int(30, "Setup expires after (bars)", minval=5, group=grpF)
needBOS    = input.bool(false, "Require impulse to break last swing (MSS)", group=grpF)
 
grpT = "3) Trade levels"
slMode     = input.string("Sweep extreme", "Stop-loss mode", options=["Sweep extreme", "ATR"], group=grpT)
slBufATR   = input.float(0.2, "SL buffer beyond sweep (x ATR)", minval=0.0, step=0.05, group=grpT)
slATRmult  = input.float(1.5, "SL distance in ATR mode (x ATR)", minval=0.5, step=0.1, group=grpT)
maxRiskATR = input.float(4.0, "Skip trade if risk is bigger than (x ATR)", minval=1.0, step=0.5, group=grpT)
r1         = input.float(1.0, "TP1 (R multiple)", minval=0.1, step=0.1, group=grpT)
r2         = input.float(2.0, "TP2 (R multiple)", minval=0.1, step=0.1, group=grpT)
r3         = input.float(3.0, "TP3 (R multiple)", minval=0.1, step=0.1, group=grpT)
r4         = input.float(4.0, "TP4 (R multiple)", minval=0.1, step=0.1, group=grpT)
closeAt    = input.int(3, "Trade closes at TP #  (lower TPs = milestones only)", options=[1, 2, 3, 4], group=grpT)
allowFlip  = input.bool(false, "Allow opposite signal to reverse the trade after TP1", group=grpT)
 
grpX = "4) Filters (optional)"
useTrend = input.bool(false, "Trend filter: only trade with EMA", group=grpX)
emaLen   = input.int(200, "EMA length", minval=2, group=grpX)
useSess  = input.bool(false, "Session filter", group=grpX)
sess     = input.session("0700-2000", "Session (chart exchange time)", group=grpX)
 
grpD = "5) Display & alerts"
showZone   = input.bool(true, "Show golden-zone box", group=grpD)
showSweeps = input.bool(true, "Mark liquidity sweeps", group=grpD)
showDash   = input.bool(true, "Show dashboard", group=grpD)
richAlerts = input.bool(true, "Send rich alert() messages", group=grpD)
 
// ───────────────────────────── SERIES ─────────────────────────────
atrV    = ta.atr(14)
emaV    = ta.ema(close, emaLen)
ph      = ta.pivothigh(high, pivLen, pivLen)
pl      = ta.pivotlow(low, pivLen, pivLen)
inSess  = not useSess or not na(time(timeframe.period, sess))
okLong  = not useTrend or close > emaV
okShort = not useTrend or close < emaV
fLo     = math.min(fibA, fibB)
fHi     = math.max(fibA, fibB)
 
// ───────────────────────────── STATE ──────────────────────────────
var array<float> hiLv = array.new<float>()
var array<int>   hiBr = array.new<int>()
var array<float> loLv = array.new<float>()
var array<int>   loBr = array.new<int>()
var float lastPH = na
var float lastPL = na
 
var int   setupDir = 0      // 1 = buy setup armed, -1 = sell setup armed
var float swpExt   = na     // extreme of the sweep candle (low for buy, high for sell)
var int   swpBar   = na
var float legExt   = na     // furthest point of the impulse leg since the sweep
var float bosLvl   = na
var box   zoneBox  = na
 
var int   tDir   = 0        // 1 long, -1 short, 0 flat
var float tEntry = na
var float tSL    = na
var float tRisk  = na
var float tTP1   = na
var float tTP2   = na
var float tTP3   = na
var float tTP4   = na
var bool  hit1   = false
var bool  hit2   = false
var bool  hit3   = false
var bool  hit4   = false
var int   tBar   = na
 
var array<line>  tLines   = array.new<line>()
var array<label> tLabs    = array.new<label>()
var array<string> lvlNames = array.from("ENTRY", "SL", "TP1", "TP2", "TP3", "TP4")
 
var int   wins   = 0
var int   losses = 0
var float totR   = 0.0
 
// per-bar event flags (reset every bar)
bool buySig        = false
bool sellSig       = false
bool sweepBuyFlag  = false
bool sweepSellFlag = false
bool slFlag        = false
bool tp1Flag       = false
bool tp2Flag       = false
bool tp3Flag       = false
bool tp4Flag       = false
bool closedNow     = false
bool enteredNow    = false
 
// ─────────────────────── MAIN LOGIC (bar close only) ───────────────────────
if barstate.isconfirmed
 
    // 1) confirmed swing pivots become liquidity levels
    if not na(ph)
        array.push(hiLv, ph)
        array.push(hiBr, bar_index - pivLen)
        lastPH := ph
        if array.size(hiLv) > 30
            array.shift(hiLv)
            array.shift(hiBr)
    if not na(pl)
        array.push(loLv, pl)
        array.push(loBr, bar_index - pivLen)
        lastPL := pl
        if array.size(loLv) > 30
            array.shift(loLv)
            array.shift(loBr)
 
    // 2) manage the open trade (SL checked first = conservative)
    if tDir != 0 and bar_index > tBar
        bool slTouch = tDir == 1 ? low <= tSL : high >= tSL
        bool t1 = tDir == 1 ? high >= tTP1 : low <= tTP1
        bool t2 = tDir == 1 ? high >= tTP2 : low <= tTP2
        bool t3 = tDir == 1 ? high >= tTP3 : low <= tTP3
        bool t4 = tDir == 1 ? high >= tTP4 : low <= tTP4
        bool closeTouch = closeAt == 1 ? t1 : closeAt == 2 ? t2 : closeAt == 3 ? t3 : t4
        float closeR = closeAt == 1 ? r1 : closeAt == 2 ? r2 : closeAt == 3 ? r3 : r4
        if slTouch
            losses += 1
            totR -= 1.0
            slFlag := true
            closedNow := true
            label.set_text(array.get(tLabs, 1), "SL ✖ " + str.tostring(tSL, format.mintick))
            if richAlerts
                alert("GSF " + syminfo.ticker + " SL hit @ " + str.tostring(tSL, format.mintick), alert.freq_once_per_bar_close)
        else
            if t1 and not hit1
                hit1 := true
                tp1Flag := true
                label.set_text(array.get(tLabs, 2), "TP1 ✔ " + str.tostring(tTP1, format.mintick))
                if richAlerts
                    alert("GSF " + syminfo.ticker + " TP1 hit @ " + str.tostring(tTP1, format.mintick), alert.freq_once_per_bar_close)
            if t2 and not hit2
                hit2 := true
                tp2Flag := true
                label.set_text(array.get(tLabs, 3), "TP2 ✔ " + str.tostring(tTP2, format.mintick))
                if richAlerts
                    alert("GSF " + syminfo.ticker + " TP2 hit @ " + str.tostring(tTP2, format.mintick), alert.freq_once_per_bar_close)
            if t3 and not hit3
                hit3 := true
                tp3Flag := true
                label.set_text(array.get(tLabs, 4), "TP3 ✔ " + str.tostring(tTP3, format.mintick))
                if richAlerts
                    alert("GSF " + syminfo.ticker + " TP3 hit @ " + str.tostring(tTP3, format.mintick), alert.freq_once_per_bar_close)
            if t4 and not hit4
                hit4 := true
                tp4Flag := true
                label.set_text(array.get(tLabs, 5), "TP4 ✔ " + str.tostring(tTP4, format.mintick))
                if richAlerts
                    alert("GSF " + syminfo.ticker + " TP4 hit @ " + str.tostring(tTP4, format.mintick), alert.freq_once_per_bar_close)
            if closeTouch
                wins += 1
                totR += closeR
                closedNow := true
        for i = 0 to 5
            line.set_x2(array.get(tLines, i), bar_index)
            label.set_x(array.get(tLabs, i), bar_index + 1)
        if closedNow
            tDir := 0
 
    // 3) liquidity sweep detection
    bool swBuy  = false   // sell-side liquidity taken (wick below low, close back above) -> BUY setup
    bool swSell = false   // buy-side liquidity taken (wick above high, close back below) -> SELL setup
 
    int nL = array.size(loLv)
    if nL > 0
        for i = nL - 1 to 0
            float lv = array.get(loLv, i)
            if bar_index - array.get(loBr, i) > maxAge
                array.remove(loLv, i)
                array.remove(loBr, i)
            else if low < lv - minSweepATR * atrV and close > lv
                swBuy := true
                array.remove(loLv, i)
                array.remove(loBr, i)
            else if close < lv
                array.remove(loLv, i)
                array.remove(loBr, i)
 
    int nH = array.size(hiLv)
    if nH > 0
        for i = nH - 1 to 0
            float lv = array.get(hiLv, i)
            if bar_index - array.get(hiBr, i) > maxAge
                array.remove(hiLv, i)
                array.remove(hiBr, i)
            else if high > lv + minSweepATR * atrV and close < lv
                swSell := true
                array.remove(hiLv, i)
                array.remove(hiBr, i)
            else if close > lv
                array.remove(hiLv, i)
                array.remove(hiBr, i)
 
    if swBuy and swSell
        if close >= open
            swSell := false
        else
            swBuy := false
 
    bool armedNow = swBuy or swSell
    if armedNow
        if not na(zoneBox)
            box.delete(zoneBox)
            zoneBox := na
        if swBuy
            setupDir := 1
            swpExt := low
            legExt := high
            bosLvl := lastPH
            sweepBuyFlag := true
        else
            setupDir := -1
            swpExt := high
            legExt := low
            bosLvl := lastPL
            sweepSellFlag := true
        swpBar := bar_index
 
    // 4) setup progress: impulse -> pullback into golden zone -> rejection -> entry
    if setupDir != 0 and not armedNow
        bool expired = bar_index - swpBar > expireBars
        bool invalid = setupDir == 1 ? close < swpExt : close > swpExt
        if expired or invalid
            setupDir := 0
        else
            float legSz = math.abs(legExt - swpExt)
            bool legOk = legSz >= minLegATR * atrV and (not needBOS or na(bosLvl) or (setupDir == 1 ? legExt > bosLvl : legExt < bosLvl))
            float zA = setupDir == 1 ? legExt - fLo * legSz : legExt + fLo * legSz
            float zB = setupDir == 1 ? legExt - fHi * legSz : legExt + fHi * legSz
 
            if showZone and legOk
                float zTop = math.max(zA, zB)
                float zBot = math.min(zA, zB)
                if na(zoneBox)
                    zoneBox := box.new(bar_index, zTop, bar_index + 1, zBot, border_color=color.new(color.yellow, 40), bgcolor=color.new(color.yellow, 88))
                else
                    box.set_top(zoneBox, zTop)
                    box.set_bottom(zoneBox, zBot)
                    box.set_right(zoneBox, bar_index + 1)
 
            bool touched = setupDir == 1 ? low <= zA : high >= zA
            bool confirm = setupDir == 1 ? (close > open and close > zB) : (close < open and close < zB)
 
            if legOk and touched and confirm
                int nd = setupDir
                float eP = close
                float sP = slMode == "Sweep extreme" ? (nd == 1 ? swpExt - slBufATR * atrV : swpExt + slBufATR * atrV) : (nd == 1 ? eP - slATRmult * atrV : eP + slATRmult * atrV)
                float rk = math.abs(eP - sP)
                bool okRisk = rk > 0 and rk <= maxRiskATR * atrV
                bool okFilt = inSess and (nd == 1 ? okLong : okShort)
                bool canEnter = not closedNow and (tDir == 0 or (allowFlip and hit1 and tDir != nd))
 
                if okRisk and okFilt and canEnter
                    // reversal: close the old trade at market and book its result
                    if tDir != 0
                        float rr = tDir * (close - tEntry) / tRisk
                        totR += rr
                        if rr > 0
                            wins += 1
                        else
                            losses += 1
 
                    tDir := nd
                    tEntry := eP
                    tSL := sP
                    tRisk := rk
                    tTP1 := eP + nd * rk * r1
                    tTP2 := eP + nd * rk * r2
                    tTP3 := eP + nd * rk * r3
                    tTP4 := eP + nd * rk * r4
                    hit1 := false
                    hit2 := false
                    hit3 := false
                    hit4 := false
                    tBar := bar_index
 
                    array<float> lvls = array.from(tEntry, tSL, tTP1, tTP2, tTP3, tTP4)
                    array.clear(tLines)
                    array.clear(tLabs)
                    for i = 0 to 5
                        float py = array.get(lvls, i)
                        color c = i == 0 ? color.blue : i == 1 ? color.red : color.green
                        array.push(tLines, line.new(bar_index, py, bar_index + 1, py, color=c, style=(i == 0 ? line.style_solid : line.style_dashed), width=(i == 0 ? 2 : 1)))
                        array.push(tLabs, label.new(bar_index + 1, py, array.get(lvlNames, i) + " " + str.tostring(py, format.mintick), style=label.style_label_left, color=color.new(c, 85), textcolor=c, size=size.small))
 
                    buySig := nd == 1
                    sellSig := nd == -1
                    enteredNow := true
                    setupDir := 0
 
                    if richAlerts
                        alert("GSF " + (nd == 1 ? "BUY " : "SELL ") + syminfo.ticker + " " + timeframe.period + " | Entry " + str.tostring(tEntry, format.mintick) + " | SL " + str.tostring(tSL, format.mintick) + " | TP1 " + str.tostring(tTP1, format.mintick) + " | TP2 " + str.tostring(tTP2, format.mintick) + " | TP3 " + str.tostring(tTP3, format.mintick) + " | TP4 " + str.tostring(tTP4, format.mintick), alert.freq_once_per_bar_close)
 
            // extend the leg only after the entry check (zone uses prior bars)
            if setupDir != 0
                legExt := setupDir == 1 ? math.max(legExt, high) : math.min(legExt, low)
 
    // cleanup of the golden-zone box when no setup is alive
    if setupDir == 0 and not na(zoneBox)
        if not enteredNow
            box.delete(zoneBox)
        zoneBox := na
 
    if richAlerts and (sweepBuyFlag or sweepSellFlag)
        alert("GSF " + syminfo.ticker + (sweepBuyFlag ? " sell-side liquidity swept - watch for BUY pullback" : " buy-side liquidity swept - watch for SELL pullback"), alert.freq_once_per_bar_close)
 
// ───────────────────────────── PLOTS ─────────────────────────────
plotshape(buySig, title="BUY", style=shape.labelup, location=location.belowbar, color=color.green, text="BUY", textcolor=color.white, size=size.small)
plotshape(sellSig, title="SELL", style=shape.labeldown, location=location.abovebar, color=color.red, text="SELL", textcolor=color.white, size=size.small)
plotshape(showSweeps and sweepBuyFlag, title="Sell-side sweep", style=shape.diamond, location=location.belowbar, color=color.aqua, size=size.tiny)
plotshape(showSweeps and sweepSellFlag, title="Buy-side sweep", style=shape.diamond, location=location.abovebar, color=color.orange, size=size.tiny)
plot(useTrend ? emaV : na, title="EMA filter", color=color.new(color.gray, 30))
 
// ───────────────────────────── DASHBOARD ─────────────────────────────
var table dash = table.new(position.top_right, 2, 7, bgcolor=color.new(color.black, 15), border_width=1, border_color=color.new(color.gray, 50))
if showDash and barstate.islast
    int trades = wins + losses
    string setupTxt = setupDir == 1 ? "BUY armed" : setupDir == -1 ? "SELL armed" : "Waiting for sweep"
    string tradeTxt = tDir == 1 ? "LONG" : tDir == -1 ? "SHORT" : "None"
    string wrTxt = trades > 0 ? str.tostring(wins / trades * 100, "#.#") + "%" : "-"
    table.cell(dash, 0, 0, "Setup", text_color=color.gray, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 1, 0, setupTxt, text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 0, 1, "Trade", text_color=color.gray, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 1, 1, tradeTxt, text_color=tDir == 1 ? color.lime : tDir == -1 ? color.red : color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 0, 2, "Entry", text_color=color.gray, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 1, 2, tDir != 0 ? str.tostring(tEntry, format.mintick) : "-", text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 0, 3, "Trades (W/L)", text_color=color.gray, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 1, 3, str.tostring(trades) + " (" + str.tostring(wins) + "/" + str.tostring(losses) + ")", text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 0, 4, "Win rate", text_color=color.gray, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 1, 4, wrTxt, text_color=color.white, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 0, 5, "Total R", text_color=color.gray, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 1, 5, str.tostring(totR, "#.##") + "R", text_color=totR >= 0 ? color.lime : color.red, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 0, 6, "Closes at", text_color=color.gray, text_size=size.small, text_halign=text.align_left)
    table.cell(dash, 1, 6, "TP" + str.tostring(closeAt) + " or SL", text_color=color.white, text_size=size.small, text_halign=text.align_left)
 
// ───────────────────────────── ALERT CONDITIONS ─────────────────────────────
alertcondition(buySig, "GSF Buy", "Gold 1H Sweep+Fib: BUY signal")
alertcondition(sellSig, "GSF Sell", "Gold 1H Sweep+Fib: SELL signal")
alertcondition(buySig or sellSig, "GSF Any signal", "Gold 1H Sweep+Fib: new trade signal")
alertcondition(sweepBuyFlag, "GSF Sell-side sweep (buy watch)", "Gold 1H: sell-side liquidity swept - watch for BUY pullback")
alertcondition(sweepSellFlag, "GSF Buy-side sweep (sell watch)", "Gold 1H: buy-side liquidity swept - watch for SELL pullback")
alertcondition(tp1Flag, "GSF TP1 hit", "Gold 1H Sweep+Fib: TP1 hit")
alertcondition(tp2Flag, "GSF TP2 hit", "Gold 1H Sweep+Fib: TP2 hit")
alertcondition(tp3Flag, "GSF TP3 hit", "Gold 1H Sweep+Fib: TP3 hit")
alertcondition(tp4Flag, "GSF TP4 hit", "Gold 1H Sweep+Fib: TP4 hit")
alertcondition(slFlag, "GSF SL hit", "Gold 1H Sweep+Fib: stop-loss hit")

← 返回列表