CA Capitulation Flush Map v2

Crypto_Andy_ · study · 257 行 · 点赞 14 · TradingView 原页

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

Pine Script

//@version=6
// CA Capitulation Flush Map v2
// Changelog: v1 - initial release.
//            v2 - softer default thresholds (1.5 ATR, 1.5x volume); optional manual anchor bar for a known flush;
//                 debug markers for near-miss candidates; table shows "no recent flush" once a setup is stale.
//
// Chart analysis indicator, symbol-agnostic. Detects capitulation ("flush") candles from the chart's own
// OHLCV data, then tracks whether the flush resolves into a local bottom or a second leg down.
//   - Flush:  confirmed bar with a range of at least X ATR (ATR of the previous bar), a lower wick of at
//             least Y% of the range, the lowest low of the last N bars and, optionally, relative volume of
//             at least Z times its average.
//   - Levels: absorption zone (flush low to the lower body edge), flush low, bounce high since the flush,
//             reclaim level (last confirmed swing high before the flush, or a manual value).
//   - States: Holding     = closes stay above the flush low minus a buffer
//             Reclaim     = close above the reclaim level (bottom scenario confirmed)
//             Second wave = close below the flush low minus the buffer (flush failed)
//             Expired     = max setup age reached without resolution
// All distances are in ATR, so the logic runs unchanged on any symbol and timeframe.
// Swing pivots and HL labels appear only after their confirmation bars (pivot length bars late).
// The higher timeframe EMA uses the previous closed HTF bar, so it does not repaint.
// Liquidation data is not available in Pine: the flush is inferred from price and volume only.
 
indicator("CA Capitulation Flush Map v2", shorttitle="CA Flush v2", overlay=true, max_labels_count=200, max_lines_count=200, max_boxes_count=100)
 
// ───────────── Inputs: flush detection ─────────────
string gDet = "Flush detection"
int   atrLen      = input.int(14, "ATR length", minval=1, group=gDet)
float minRngAtr   = input.float(1.5, "Min candle range (ATR)", minval=0.5, maxval=20.0, step=0.1, group=gDet, tooltip="Range of the flush candle compared with the ATR of the previous bar.")
float minWickPct  = input.float(50.0, "Min lower wick (% of range)", minval=0.0, maxval=100.0, step=5.0, group=gDet, tooltip="A long lower wick shows forced selling that was absorbed inside the same bar.")
int   lowLookback = input.int(50, "Must be the lowest low of last N bars", minval=5, maxval=1000, group=gDet)
bool  useVol      = input.bool(true, "Require volume spike", group=gDet, tooltip="Turn off on feeds without reliable volume.")
int   volLen      = input.int(20, "Volume average length", minval=2, maxval=500, group=gDet)
float minRelVol   = input.float(1.5, "Min relative volume (x average)", minval=1.0, maxval=20.0, step=0.1, group=gDet)
bool  useAnchor   = input.bool(false, "Anchor flush to a specific bar", group=gDet, tooltip="Forces the bar containing this time to be treated as the flush, e.g. a liquidation cascade confirmed by external data. Off = automatic detection only.")
int   anchorTime  = input.time(timestamp("14 Nov 2026 20:00 +0000"), "Anchor bar time", group=gDet)
bool  showDebug   = input.bool(false, "Debug: show near-miss candidates", group=gDet, tooltip="Grey x on bars that pass 3 of the 4 flush conditions; the tooltip shows every value.")
 
// ───────────── Inputs: tracking ─────────────
string gTrk = "Tracking"
int   swingLen      = input.int(5, "Reclaim swing pivot length", minval=2, maxval=50, group=gTrk, tooltip="Reclaim level = last confirmed swing high before the flush. A pivot is confirmed this many bars after it forms.")
float manualReclaim = input.float(0.0, "Manual reclaim level (0 = auto)", minval=0.0, group=gTrk)
float failAtr       = input.float(0.25, "Second wave buffer below flush low (ATR)", minval=0.0, maxval=5.0, step=0.05, group=gTrk)
int   hlLen         = input.int(3, "Higher-low pivot length", minval=2, maxval=20, group=gTrk)
int   maxAge        = input.int(150, "Max setup age (bars)", minval=10, maxval=2000, group=gTrk, tooltip="150 bars = 25 days on 4H.")
 
// ───────────── Inputs: higher timeframe EMA ─────────────
string gHtf = "Higher timeframe EMA"
bool   showHtf = input.bool(true, "Show HTF EMA", group=gHtf)
string htfTf   = input.timeframe("1D", "HTF timeframe", group=gHtf)
int    htfLen  = input.int(200, "HTF EMA length", minval=1, maxval=1000, group=gHtf)
 
// ───────────── Inputs: visuals ─────────────
string gVis = "Visuals"
bool   showZone   = input.bool(true, "Show absorption zone", group=gVis)
bool   showLevels = input.bool(true, "Show flush low and reclaim level", group=gVis)
bool   showBounce = input.bool(true, "Show bounce high", group=gVis)
bool   showHL     = input.bool(true, "Show higher lows after the flush", group=gVis)
bool   showLabels = input.bool(true, "Show state labels", group=gVis)
int    maxSetups  = input.int(5, "Setups kept on chart", minval=1, maxval=20, group=gVis)
bool   showTable  = input.bool(true, "Show status table", group=gVis)
string tablePos   = input.string("Top right", "Table position", options=["Top right", "Bottom right", "Top left", "Bottom left"], group=gVis)
 
// ───────────── Calculations (every bar) ─────────────
float atr       = ta.atr(atrLen)
float atrRef    = atr[1]
float rng       = high - low
float lowerWick = math.min(open, close) - low
float wickPct   = rng > 0 ? 100.0 * lowerWick / rng : 0.0
float volAvg    = ta.sma(volume, volLen)[1]
float relVol    = not na(volume) and not na(volAvg) and volAvg > 0 ? volume / volAvg : na
bool  isLowest  = low <= ta.lowest(low, lowLookback)
float ph        = ta.pivothigh(high, swingLen, swingLen)
float plHL      = ta.pivotlow(low, hlLen, hlLen)
float htfEma    = request.security(syminfo.tickerid, htfTf, ta.ema(close, htfLen)[1], lookahead=barmerge.lookahead_on)
 
// ───────────── Helpers ─────────────
px(float x) => na(x) ? "-" : str.tostring(x, format.mintick)
num(float x) => na(x) ? "-" : str.tostring(x, "#.##")
 
var array<box>   zoneBoxes = array.new<box>()
var array<line>  lvlLines  = array.new<line>()
var array<label> evLabels  = array.new<label>()
 
keepBox(box b) =>
    zoneBoxes.push(b)
    if zoneBoxes.size() > maxSetups
        zoneBoxes.shift().delete()
 
keepLine(line l) =>
    lvlLines.push(l)
    if lvlLines.size() > maxSetups * 3
        lvlLines.shift().delete()
 
keepLabel(label lb) =>
    evLabels.push(lb)
    if evLabels.size() > maxSetups * 6
        evLabels.shift().delete()
 
// ───────────── Reclaim reference: last confirmed swing high ─────────────
var float lastSwingHigh = na
if not na(ph)
    lastSwingHigh := ph
 
// ───────────── Flush detection (confirmed bars only) ─────────────
bool atrOk    = not na(atrRef) and atrRef > 0
bool rngOk    = atrOk and rng >= minRngAtr * atrRef
bool wickOk   = wickPct >= minWickPct
bool volOk    = not useVol or (not na(relVol) and relVol >= minRelVol)
bool autoFl   = barstate.isconfirmed and rngOk and wickOk and isLowest and volOk
bool anchorFl = barstate.isconfirmed and atrOk and useAnchor and time <= anchorTime and time_close > anchorTime
bool flush    = autoFl or anchorFl
 
// Debug: bars that miss exactly one condition
int passCount = (rngOk ? 1 : 0) + (wickOk ? 1 : 0) + (isLowest ? 1 : 0) + (volOk ? 1 : 0)
if showDebug and barstate.isconfirmed and atrOk and not flush and passCount == 3
    string dtip = "Near-miss flush candidate\nRange: " + num(rng / atrRef) + " ATR (min " + str.tostring(minRngAtr) + ")" + (rngOk ? " ok" : " FAIL") + "\nLower wick: " + num(wickPct) + "% (min " + str.tostring(minWickPct) + ")" + (wickOk ? " ok" : " FAIL") + "\nLowest low of " + str.tostring(lowLookback) + " bars:" + (isLowest ? " ok" : " FAIL") + "\nRelative volume: " + (na(relVol) ? "-" : num(relVol) + "x") + " (min " + str.tostring(minRelVol) + ")" + (volOk ? " ok" : " FAIL")
    keepLabel(label.new(bar_index, low, "x", yloc=yloc.belowbar, style=label.style_none, textcolor=color.gray, size=size.small, tooltip=dtip))
 
// ───────────── Setup state ─────────────
// 0 = none, 1 = holding, 2 = reclaimed, 3 = second wave, 4 = expired
var int   state    = 0
var int   fBar     = na
var int   fTime    = na
var float fLow     = na
var float fBodyLow = na
var float fRngAtr  = na
var float fWick    = na
var float fRelVol  = na
var float rcLvl    = na
var float bHigh    = na
var box   zBox     = na
var line  lowLn    = na
var line  rcLn     = na
var line  bLn      = na
 
bool evReclaim = false
bool evSecond  = false
 
if flush
    fBar     := bar_index
    fTime    := time
    fLow     := low
    fBodyLow := math.min(open, close)
    fRngAtr  := rng / atrRef
    fWick    := wickPct
    fRelVol  := relVol
    float rc  = manualReclaim > 0 ? manualReclaim : lastSwingHigh
    rcLvl    := not na(rc) and rc > close ? rc : na
    bHigh    := na
    bLn      := na
    zBox     := na
    lowLn    := na
    rcLn     := na
    state    := 1
    if showZone
        zBox := box.new(bar_index, fBodyLow, bar_index, fLow, border_color=color.new(color.orange, 40), bgcolor=color.new(color.orange, 80))
        keepBox(zBox)
    if showLevels
        lowLn := line.new(bar_index, fLow, bar_index, fLow, color=color.new(color.red, 0), style=line.style_dashed, width=1)
        keepLine(lowLn)
        if not na(rcLvl)
            rcLn := line.new(bar_index, rcLvl, bar_index, rcLvl, color=color.new(color.orange, 0), style=line.style_solid, width=1)
            keepLine(rcLn)
    if showLabels
        string tip = (anchorFl and not autoFl ? "Capitulation flush (manual anchor)" : "Capitulation flush") + "\nLow: " + px(fLow) + "\nRange: " + num(fRngAtr) + " ATR\nLower wick: " + num(fWick) + "% of range\nRelative volume: " + (na(fRelVol) ? "-" : num(fRelVol) + "x") + "\nReclaim level: " + px(rcLvl)
        keepLabel(label.new(bar_index, low, "FLUSH", yloc=yloc.belowbar, style=label.style_label_up, color=color.new(color.orange, 10), textcolor=color.black, size=size.small, tooltip=tip))
 
// Extend active objects to the current bar
if state == 1
    if not na(zBox)
        box.set_right(zBox, bar_index)
    if not na(lowLn)
        line.set_x2(lowLn, bar_index)
    if not na(rcLn)
        line.set_x2(rcLn, bar_index)
    if not na(bLn)
        line.set_x2(bLn, bar_index)
 
// Track the setup after the flush bar (confirmed bars only)
if state == 1 and not na(fBar) and bar_index > fBar and barstate.isconfirmed
    // Bounce high since the flush
    if na(bHigh) or high > bHigh
        bHigh := high
        if showBounce
            if na(bLn)
                bLn := line.new(bar_index, high, bar_index, high, color=color.new(color.gray, 0), style=line.style_dotted, width=1)
                keepLine(bLn)
            else
                line.set_xy1(bLn, bar_index, high)
                line.set_xy2(bLn, bar_index, high)
    // Higher low after the flush, shown once its pivot is confirmed
    if showHL and not na(plHL) and bar_index - hlLen > fBar and plHL > fLow
        keepLabel(label.new(bar_index - hlLen, plHL, "HL", yloc=yloc.belowbar, style=label.style_label_up, color=color.new(color.teal, 20), textcolor=color.white, size=size.tiny, tooltip="Higher low above the flush low, confirmed " + str.tostring(hlLen) + " bars after it formed."))
    // State transitions
    float failLvl = fLow - failAtr * atr
    if not na(rcLvl) and close > rcLvl
        state     := 2
        evReclaim := true
        if not na(zBox)
            box.set_bgcolor(zBox, color.new(color.teal, 80))
            box.set_border_color(zBox, color.new(color.teal, 40))
        if showLabels
            keepLabel(label.new(bar_index, high, "RECLAIM", yloc=yloc.abovebar, style=label.style_label_down, color=color.new(color.teal, 10), textcolor=color.white, size=size.small, tooltip="Close above the reclaim level: bottom scenario confirmed."))
    else if not na(atr) and close < failLvl
        state    := 3
        evSecond := true
        if not na(zBox)
            box.set_bgcolor(zBox, color.new(color.gray, 85))
            box.set_border_color(zBox, color.new(color.gray, 50))
        if showLabels
            keepLabel(label.new(bar_index, high, "2ND WAVE", yloc=yloc.abovebar, style=label.style_label_down, color=color.new(color.red, 10), textcolor=color.white, size=size.small, tooltip="Close below the flush low minus the buffer: the flush did not mark the low."))
    else if bar_index - fBar >= maxAge
        state := 4
 
// ───────────── Plots ─────────────
plot(showHtf ? htfEma : na, "HTF EMA", color=color.new(color.purple, 0), linewidth=2)
 
// ───────────── Status table ─────────────
string tPos = tablePos == "Top right" ? position.top_right : tablePos == "Bottom right" ? position.bottom_right : tablePos == "Top left" ? position.top_left : position.bottom_left
var table tbl = table.new(tPos, 2, 10, bgcolor=color.new(color.gray, 85), border_width=1, border_color=color.new(color.gray, 60))
 
cell(int c, int r, string t, color tc) =>
    table.cell(tbl, c, r, t, text_color=tc, text_size=size.small, text_halign=c == 0 ? text.align_left : text.align_right)
 
if barstate.islast and showTable
    bool   stale = state != 1 and not na(fBar) and bar_index - fBar > maxAge
    string stTxt = state == 0 or stale ? "No recent flush" : state == 1 ? "Holding above flush low" : state == 2 ? "Reclaimed: bottom scenario" : state == 3 ? "Second wave: flush low lost" : "Expired, unresolved"
    color  stCol = stale ? color.gray : state == 2 ? color.teal : state == 3 ? color.red : state == 1 ? color.orange : color.gray
    bool   hasF  = state != 0 and not stale and not na(fLow)
    float  bncPct = hasF and fLow > 0 ? 100.0 * (close - fLow) / fLow : na
    float  bncAtr = hasF and not na(atr) and atr > 0 ? (close - fLow) / atr : na
    float  rcDist = not na(rcLvl) and not na(atr) and atr > 0 ? (rcLvl - close) / atr : na
    cell(0, 0, "Capitulation flush", color.white)
    cell(1, 0, syminfo.ticker, color.white)
    cell(0, 1, "State", color.white)
    cell(1, 1, stTxt, stCol)
    cell(0, 2, "Flush bar (UTC)", color.white)
    cell(1, 2, hasF and not na(fTime) ? str.format_time(fTime, "yyyy-MM-dd HH:mm", "UTC") : "-", color.white)
    cell(0, 3, "Flush low", color.white)
    cell(1, 3, hasF ? px(fLow) : "-", color.red)
    cell(0, 4, "Range / wick / rel. volume", color.white)
    cell(1, 4, hasF ? num(fRngAtr) + " ATR / " + num(fWick) + "% / " + (na(fRelVol) ? "-" : num(fRelVol) + "x") : "-", color.white)
    cell(0, 5, "Close vs flush low", color.white)
    cell(1, 5, hasF ? "+" + num(bncPct) + "% (" + num(bncAtr) + " ATR)" : "-", color.white)
    cell(0, 6, "Bounce high", color.white)
    cell(1, 6, hasF ? px(bHigh) : "-", color.gray)
    cell(0, 7, "Reclaim level (distance)", color.white)
    cell(1, 7, hasF ? px(rcLvl) + (na(rcDist) ? "" : " (" + num(rcDist) + " ATR)") : "-", color.orange)
    cell(0, 8, "HTF EMA " + str.tostring(htfLen) + " (" + htfTf + ")", color.white)
    cell(1, 8, na(htfEma) ? "-" : px(htfEma) + (close >= htfEma ? " (above)" : " (below)"), color.purple)
    cell(0, 9, "Inferred from price and volume, not liquidation data. Not a forecast.", color.gray)
    table.merge_cells(tbl, 0, 9, 1, 9)
 
// ───────────── Alerts (confirmed bars only) ─────────────
alertcondition(flush, "Flush detected", "{{ticker}} {{interval}}: capitulation flush candle confirmed")
alertcondition(evReclaim, "Reclaim", "{{ticker}} {{interval}}: close above the reclaim level after a flush")
alertcondition(evSecond, "Second wave", "{{ticker}} {{interval}}: close below the flush low, second leg down")

← 返回列表