Auction Failure (Liquidity Sweep/Fakeout)

OlympusCipher · study · 216 行 · 点赞 109 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OlympusCipher
 
//  ◇━━━━━━━━━━━━━━━━━━  C R E A T E D    B Y  ━━━━━━━━━━━━━━━━━━◇
//
//     ████   ██      ██  ██  ██      ██  █████   ██  ██   █████
//    ██  ██  ██      ██  ██  ███    ███  ██  ██  ██  ██  ██
//    ██  ██  ██       ████   ████  ████  ██  ██  ██  ██  ██
//    ██  ██  ██        ██    ██ ████ ██  █████   ██  ██   ████
//    ██  ██  ██        ██    ██  ██  ██  ██      ██  ██      ██
//    ██  ██  ██        ██    ██      ██  ██      ██  ██      ██
//     ████   ██████    ██    ██      ██  ██       ████   █████
//
//           █████  ██████  █████   ██  ██  ██████  █████
//          ██        ██    ██  ██  ██  ██  ██      ██  ██
//          ██        ██    ██  ██  ██  ██  ██      ██  ██
//          ██        ██    █████   ██████  █████   █████
//          ██        ██    ██      ██  ██  ██      ██  ██
//          ██        ██    ██      ██  ██  ██      ██  ██
//           █████  ██████  ██      ██  ██  ██████  ██  ██
//
//  ◇━━━━━━━━━━━━ Ω  O L Y M P U S    C I P H E R  Ω ━━━━━━━━━━━━◇
 
//@version=6
indicator("Auction Failure (Liquidity Sweep)", shorttitle="AuctionFail", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500)
 
// ───────────────────────── Inputs ─────────────────────────
grpS = "Signal"
dirMode      = input.string("Both", "Signal direction", options=["Both", "Long only", "Short only"], group=grpS, tooltip="Long = sweep of the range LOW (price breaks below, then closes back inside). Short = sweep of the range HIGH (price breaks above, then closes back inside). The trend filters below can further restrict direction.")
lookback     = input.int(50, "Range lookback (candles)", minval=3, maxval=300, group=grpS, tooltip="The highest high and lowest low of this many candles (before the current one) define the range.")
failWindow   = input.int(2, "Candles allowed to reject after the break", minval=0, maxval=20, group=grpS, tooltip="0 = the breakout candle itself must close back inside the range. 2 = the breakout candle or either of the next 2 candles.")
cooldownBars = input.int(10, "Min candles between same-direction signals", minval=0, maxval=100, group=grpS, tooltip="After a long signal, new long setups are ignored until more than this many candles have passed. Same for shorts (tracked separately). 0 = off. Helps avoid repeated counter-trend signals in a strong trend.")
 
grpT = "Trend filter (SMA)"
useTrend     = input.bool(false, "Signal only in the direction of the trend", group=grpT, tooltip="Long signals only when price is above the SMA, short signals only when price is below it. Measured on the candle before the break.")
smaLen       = input.int(50, "SMA length", minval=2, maxval=500, group=grpT, tooltip="Used by the trend filter and by the strong trend guard.")
slopeBars    = input.int(0, "SMA slope check (candles, 0 = off)", minval=0, maxval=50, group=grpT, tooltip="If above 0, the SMA must also be rising (longs) or falling (shorts) compared with this many candles earlier.")
showSma      = input.bool(false, "Show SMA on chart", group=grpT)
 
grpX = "Strong trend guard"
useStrong    = input.bool(true, "Block counter-trend signals in a strong trend", group=grpX, tooltip="When a strong uptrend is detected, short signals are blocked. When a strong downtrend is detected, long signals are blocked. Can be used with or without the trend filter above (it uses the same SMA length).")
adxLen       = input.int(14, "ADX length", minval=2, maxval=100, group=grpX)
adxMin       = input.float(25.0, "Min ADX for a strong trend", minval=5.0, maxval=60.0, step=1.0, group=grpX, tooltip="Lower = the guard triggers more often (blocks more signals). Higher = only very strong trends block signals.")
strongBars   = input.int(10, "SMA move window (candles)", minval=1, maxval=100, group=grpX, tooltip="The SMA must have moved enough over this many candles (see next setting) to count as a strong trend.")
strongSlope  = input.float(1.0, "Min SMA move (× ATR)", minval=0.0, step=0.1, group=grpX, tooltip="How far the SMA must have travelled over the window, measured in ATR. 0 = ignore this check and use ADX only.")
showStrongBg = input.bool(true, "Tint background in strong trend", group=grpX, tooltip="Green tint = strong uptrend (shorts blocked). Red tint = strong downtrend (longs blocked).")
 
grpF = "Sweep quality"
minBreakAtr  = input.float(0.1, "Min break beyond the level (× ATR)", minval=0.0, step=0.05, group=grpF, tooltip="How far price must push beyond the range high/low for it to count as a break. 0 = any tick beyond the level.")
minRangeAtr  = input.float(1.0, "Min range height (× ATR)", minval=0.0, step=0.1, group=grpF, tooltip="The range must be at least this tall. Avoids tiny choppy ranges. 0 = off.")
needColor    = input.bool(true, "Rejection candle must close in signal direction", group=grpF, tooltip="On: bearish rejection candle for short signals, bullish for long signals.")
 
grpD = "Display"
showLine  = input.bool(true, "Show sweep line", group=grpD)
showZone  = input.bool(true, "Show sweep zone", group=grpD)
showDot   = input.bool(true, "Show wick marker", group=grpD)
showRange = input.bool(true, "Show range box", group=grpD)
lblStyle  = input.string("Pill", "Label style", options=["Pill", "Arrow"], group=grpD)
lblSize   = input.string("small", "Label text size", options=["tiny", "small", "normal", "large"], group=grpD)
 
grpC = "Colors"
colRange   = input.color(#9AA5B8, "Range box", group=grpC)
colRef     = input.color(#F5C542, "Sweep line", group=grpC)
colLong    = input.color(#089981, "Long signal", group=grpC)
colShort   = input.color(#F23645, "Short signal", group=grpC)
colSma     = input.color(#FFB74D, "Trend SMA", group=grpC)
 
// ───────────────────────── Helpers ─────────────────────────
// Picks black or white text depending on how bright the fill color is
f_textOn(color c) =>
    (color.r(c) * 0.299 + color.g(c) * 0.587 + color.b(c) * 0.114) > 160 ? color.black : color.white
 
string lblSz = switch lblSize
    "tiny"   => size.tiny
    "normal" => size.normal
    "large"  => size.large
    =>          size.small
 
// ───────────────────────── Series ─────────────────────────
float atrV  = ta.atr(14)
float rngHi = ta.highest(high, lookback)[1]
float rngLo = ta.lowest(low, lookback)[1]
int   hiOff = nz(ta.highestbars(high, lookback)[1])   // offset (<= 0) of the range high, relative to the previous bar
int   loOff = nz(ta.lowestbars(low, lookback)[1])     // offset (<= 0) of the range low, relative to the previous bar
 
// Trend, measured on the candle before the current one (so a break candle cannot flip it)
float smaV    = ta.sma(close, smaLen)
bool  trendUp = not useTrend or (not na(smaV[1]) and close[1] > smaV[1] and (slopeBars == 0 or smaV[1] > smaV[1 + slopeBars]))
bool  trendDn = not useTrend or (not na(smaV[1]) and close[1] < smaV[1] and (slopeBars == 0 or smaV[1] < smaV[1 + slopeBars]))
 
// Strong trend guard: ADX strength + SMA travel (in ATR), both on the candle before the current one
[diP, diM, adxV] = ta.dmi(adxLen, adxLen)
float atrPrev   = math.max(nz(atrV[1]), syminfo.mintick)
float smaMove   = (smaV[1] - smaV[1 + strongBars]) / atrPrev
bool  strongOk  = useStrong and not na(adxV[1]) and adxV[1] >= adxMin and (strongSlope == 0 or (not na(smaMove) and math.abs(smaMove) >= strongSlope))
bool  strongUp  = strongOk and diP[1] > diM[1] and (strongSlope == 0 or smaMove > 0)
bool  strongDn  = strongOk and diM[1] > diP[1] and (strongSlope == 0 or smaMove < 0)
 
plot(showSma ? smaV : na, "Trend SMA", color=colSma, linewidth=2)
bgcolor(showStrongBg ? (strongUp ? color.new(colLong, 92) : strongDn ? color.new(colShort, 92) : na) : na, title="Strong trend")
 
// ───────────────────────── State ─────────────────────────
// st: 0 = idle, 1 = watching a break for a rejection
var int   st     = 0
var int   bDir   = 0       // direction of the BREAK: 1 = broke the high, -1 = broke the low
var float lvl    = na      // broken level
var int   lvlBar = na      // candle that formed the level
var int   rStart = na      // first candle of the range window
var float ext    = na      // extreme of the sweep so far
var int   extBar = na
var int   brkBar = na
var float rHiS   = na      // range snapshot taken when the break happened
var float rLoS   = na
var int   lastLongBar  = na   // bar index of the last long signal
var int   lastShortBar = na   // bar index of the last short signal
 
bool sigLong  = false
bool sigShort = false
 
// ───────────────────────── Main logic (confirmed candles only, no repainting) ─────────────────────────
if barstate.isconfirmed and not na(atrV) and not na(rngHi) and not na(rngLo)
 
    // 1) A break of the range high or low starts the watch.
    //    Break of the HIGH -> possible SHORT. Needs: trend filter allows shorts, no strong uptrend, short cooldown over.
    //    Break of the LOW  -> possible LONG.  Needs: trend filter allows longs, no strong downtrend, long cooldown over.
    //    Cooldown is checked here so a blocked setup never occupies the watch state.
    if st == 0
        float minBrk  = minBreakAtr * atrV
        bool  rangeOk = (rngHi - rngLo) >= minRangeAtr * atrV
        bool  brkUp   = high > rngHi + minBrk
        bool  brkDn   = low < rngLo - minBrk
        bool  cdShort = na(lastShortBar) or bar_index - lastShortBar > cooldownBars
        bool  cdLong  = na(lastLongBar)  or bar_index - lastLongBar  > cooldownBars
        if rangeOk
            if brkUp and not brkDn and dirMode != "Long only" and trendDn and not strongUp and cdShort
                st     := 1
                bDir   := 1
                lvl    := rngHi
                lvlBar := bar_index - 1 + hiOff
                rStart := bar_index - lookback
                ext    := high
                extBar := bar_index
                brkBar := bar_index
                rHiS   := rngHi
                rLoS   := rngLo
            else if brkDn and not brkUp and dirMode != "Short only" and trendUp and not strongDn and cdLong
                st     := 1
                bDir   := -1
                lvl    := rngLo
                lvlBar := bar_index - 1 + loOff
                rStart := bar_index - lookback
                ext    := low
                extBar := bar_index
                brkBar := bar_index
                rHiS   := rngHi
                rLoS   := rngLo
 
    // 2) While watching: track the extreme, wait for the rejection
    if st == 1
        bool isS = bDir == 1   // broke the high -> short signal
        if isS and high > ext
            ext    := high
            extBar := bar_index
        else if not isS and low < ext
            ext    := low
            extBar := bar_index
 
        // Rejection = close back INSIDE the range (not just back under/over the level)
        bool rejected = isS ? (close < lvl and close > rLoS and (not needColor or close < open)) : (close > lvl and close < rHiS and (not needColor or close > open))
 
        if rejected
            color  dC    = isS ? colShort : colLong
            float  depth = math.abs(ext - lvl)
            string tip   = (isS ? "Swept high " : "Swept low ") + str.tostring(lvl, format.mintick) + "\nDepth " + str.tostring(depth, format.mintick)
 
            // Optional range box (starts at the beginning of the lookback window)
            if showRange
                box.new(left=rStart, top=rHiS, right=bar_index, bottom=rLoS, border_color=color.new(colRange, 60), border_width=1, border_style=line.style_dotted, bgcolor=color.new(colRange, 94))
 
            // Sweep zone: the band between the level and the wick extreme
            if showZone
                box.new(left=brkBar, top=isS ? ext : lvl, right=bar_index, bottom=isS ? lvl : ext, border_color=color.new(dC, 70), border_width=1, bgcolor=color.new(dC, 80))
 
            // Sweep line: from the candle that formed the level to the signal candle
            if showLine
                line.new(lvlBar, lvl, bar_index, lvl, color=color.new(colRef, 10), style=line.style_dashed, width=1)
 
            // Wick marker on the sweep extreme
            if showDot
                label.new(extBar, ext, "", style=label.style_circle, color=dC, size=size.tiny)
 
            // Signal label on the rejection candle (offset so it never covers the wick)
            float  off  = atrV * 0.3
            float  ly   = isS ? high + off : low - off
            string txt  = lblStyle == "Pill" ? (isS ? "SHORT ▼" : "LONG ▲") : ""
            string stl  = lblStyle == "Pill" ? (isS ? label.style_label_down : label.style_label_up) : (isS ? label.style_arrowdown : label.style_arrowup)
            label.new(bar_index, ly, txt, style=stl, color=dC, textcolor=f_textOn(dC), size=lblSz, text_formatting=text.format_bold, tooltip=tip)
 
            if isS
                sigShort     := true
                lastShortBar := bar_index
            else
                sigLong      := true
                lastLongBar  := bar_index
 
            // Dynamic alert (use "Any alert() function call" when creating the alert)
            alert("Auction Failure: " + (isS ? "SHORT" : "LONG") + " on " + syminfo.ticker + " (" + timeframe.period + ") | swept " + (isS ? "high " : "low ") + str.tostring(lvl, format.mintick) + " | close " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
 
            st := 0
        else if bar_index - brkBar >= failWindow
            st := 0   // no rejection in time: the break was accepted, not a sweep
 
// ───────────────────────── Alerts ─────────────────────────
alertcondition(sigLong,  "Long signal (sweep of range low)",   "Auction Failure: LONG signal on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(sigShort, "Short signal (sweep of range high)", "Auction Failure: SHORT signal on {{ticker}} ({{interval}}) at {{close}}")
alertcondition(sigLong or sigShort, "Any sweep signal", "Auction Failure: signal on {{ticker}} ({{interval}}) at {{close}}")

← 返回列表