Big Trades & Absorption Bubbles [Jireh]

Leeonidas187 · study · 256 行 · 点赞 110 · TradingView 原页

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

Pine Script

//@version=6
indicator("Big Trades & Absorption Bubbles [Jireh]", shorttitle = "Big Trades", overlay = true, max_labels_count = 500)
 
// =====================================================================
// Big Trades & Absorption Bubbles [Jireh]
// Uses TradingView's native footprint data (Premium/Ultimate) to find
// unusually large aggressive buying (at the ask) and selling (at the bid)
// at each price level, draws them as bubbles, and flags absorption when
// a big push fails to move price.
// Note: footprint data is aggregated per price per bar. It cannot separate
// one large print from many small prints at the same price in the same bar.
// =====================================================================
 
// ---------- Footprint ----------
grpFP     = "Footprint"
ticksRow  = input.int(1, "Ticks per row", minval = 1, group = grpFP, tooltip = "1 = every price level (closest to individual prints). Raise for slower instruments or if the script loads slowly.")
imbPct    = input.int(300, "Imbalance %", minval = 100, group = grpFP, tooltip = "Passed to the footprint request. Not used for bubbles, kept for completeness.")
 
// ---------- Detection ----------
grpDet    = "Detection"
filterMode = input.string("Automatic", "Filter mode", options = ["Automatic", "Manual"], group = grpDet, tooltip = "Automatic: a level counts when its buy or sell volume is in the top percentile of recent levels. Manual: fixed contract sizes.")
intensity = input.string("Medium", "Automatic intensity", options = ["Low", "Medium", "High", "Custom"], group = grpDet, tooltip = "Low = more bubbles (top 3%), Medium = top 1.5%, High = fewer, only the biggest (top 0.5%).")
customPct = input.float(98.5, "Custom percentile", minval = 50, maxval = 99.99, step = 0.1, group = grpDet)
histLen   = input.int(1500, "Automatic lookback (price levels)", minval = 200, maxval = 5000, group = grpDet, tooltip = "How many recent price-level samples the automatic threshold is based on.")
autoFloor = input.float(0, "Automatic minimum size (0 = off)", minval = 0, group = grpDet, tooltip = "The automatic threshold never goes below this size.")
manualMin = input.float(50, "Manual minimum size", minval = 1, group = grpDet)
maxFilter = input.float(0, "Maximum size (0 = off)", minval = 0, group = grpDet, tooltip = "Use with a second copy of the indicator to show separate size tiers.")
domPct    = input.float(0, "Minimum side dominance % (0 = off)", minval = 0, maxval = 100, group = grpDet, tooltip = "Optional: the aggressive side must be at least this % of that level's total volume.")
maxPerBar = input.int(2, "Max bubbles per bar per side", minval = 1, maxval = 10, group = grpDet, tooltip = "Keeps the chart clean by showing only the largest levels in each bar.")
showBuys  = input.bool(true, "Show buy bubbles", group = grpDet)
showSells = input.bool(true, "Show sell bubbles", group = grpDet)
 
// ---------- Absorption ----------
grpAbs    = "Absorption"
useAbs    = input.bool(true, "Flag absorption", group = grpAbs, tooltip = "Big buying that fails to push price higher (or big selling that fails to push lower) within the window is marked as absorbed.")
absBars   = input.int(3, "Absorption window (bars)", minval = 1, maxval = 50, group = grpAbs)
absTol    = input.int(4, "Follow-through needed (ticks)", minval = 0, group = grpAbs, tooltip = "Price must trade at least this many ticks beyond the bubble within the window, or it counts as absorbed.")
absNeedClose = input.bool(true, "Also require close back through bubble", group = grpAbs, tooltip = "Absorbed buying also needs the window's last close below the bubble price (and vice versa).")
absOnly   = input.bool(false, "Show absorption only", group = grpAbs, tooltip = "Hides regular bubbles. Only big trades that end up absorbed are shown.")
absMinX   = input.float(1.0, "Absorption minimum size (x threshold)", minval = 1.0, step = 0.25, group = grpAbs, tooltip = "Only bubbles at least this many times the threshold can be flagged as absorption. Raise to 2-3 for only the most significant.")
absRevTicks = input.int(0, "Reversal required (ticks, 0 = off)", minval = 0, group = grpAbs, tooltip = "Absorbed buying must also see the window close at least this many ticks BELOW the bubble (and vice versa). Raise for only absorption that actually turned price.")
 
// ---------- Display ----------
grpD      = "Display"
markerIn  = input.string("Circle", "Marker", options = ["Circle", "Square", "Diamond", "Text"], group = grpD)
sizeStep  = input.float(1.6, "Size step (x threshold)", minval = 1.1, step = 0.1, group = grpD, tooltip = "Bubbles grow one size each time volume is this many times larger than the threshold.")
baseSize  = input.string("Tiny", "Smallest bubble size", options = ["Tiny", "Small", "Normal"], group = grpD)
minOpac   = input.int(35, "Minimum opacity %", minval = 5, maxval = 100, group = grpD, tooltip = "Bigger trades get more opaque, from this value up to 100%.")
showSize  = input.bool(false, "Show size inside bubble", group = grpD)
maxBubbles = input.int(400, "Max bubbles on chart", minval = 10, maxval = 490, group = grpD)
showInfo  = input.bool(false, "Show threshold info box", group = grpD)
infoPosIn = input.string("Bottom right", "Info box position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = grpD)
 
// ---------- Colors ----------
grpC      = "Colors"
buyCol    = input.color(#378ADD, "Big buying (ask)", group = grpC)
sellCol   = input.color(#F928F5, "Big selling (bid)", group = grpC)
absBuyCol = input.color(#FF9800, "Absorbed buying (bearish)", group = grpC)
absSellCol = input.color(#00E5FF, "Absorbed selling (bullish)", group = grpC)
txtCol    = input.color(color.white, "Text", group = grpC)
 
// ---------- Session ----------
grpS      = "Session filter"
useSess   = input.bool(false, "Only show bubbles in session", group = grpS)
sessWin   = input.session("0930-1600", "Session (New York time)", group = grpS)
 
// =====================================================================
// Setup
// =====================================================================
pct = switch intensity
    "Low"    => 97.0
    "High"   => 99.5
    "Custom" => customPct
    => 98.5
 
baseIdx = baseSize == "Tiny" ? 0 : baseSize == "Small" ? 1 : 2
 
sizeFor(int idx) =>
    idx <= 0 ? size.tiny : idx == 1 ? size.small : idx == 2 ? size.normal : idx == 3 ? size.large : size.huge
 
mStyle = markerIn == "Circle" ? label.style_circle : markerIn == "Square" ? label.style_square : markerIn == "Diamond" ? label.style_diamond : label.style_none
 
inSess = not useSess or not na(time(timeframe.period, sessWin, "America/New_York"))
tick   = syminfo.mintick
 
// Rolling window for absorption checks (bars after the bubble bar)
hh = ta.highest(high, absBars)
ll = ta.lowest(low, absBars)
 
fp = request.footprint(ticksRow, 70, imbPct)
 
var array<float> hist    = array.new<float>()
var array<label> bubbles = array.new<label>()
 
// Pending absorption checks
var array<float> pP   = array.new<float>()
var array<int>   pSide = array.new<int>()
var array<int>   pBar  = array.new<int>()
var array<label> pLbl  = array.new<label>()
 
var float lastThr = na
 
bigBuyNow  = false
bigSellNow = false
absBuyNow  = false
absSellNow = false
 
// =====================================================================
// Absorption evaluation (runs on confirmed bars)
// =====================================================================
useAbsE = useAbs or absOnly
if useAbsE and barstate.isconfirmed and pP.size() > 0
    for k = pP.size() - 1 to 0
        age = bar_index - pBar.get(k)
        if age >= absBars
            p    = pP.get(k)
            side = pSide.get(k)
            lb   = pLbl.get(k)
            bool absorbed = false
            if side == 1
                absorbed := hh < p + absTol * tick and (not absNeedClose or close < p) and (absRevTicks <= 0 or close <= p - absRevTicks * tick)
                if absorbed
                    label.set_color(lb, color.new(absBuyCol, 0))
                    label.set_text(lb, "A")
                    label.set_textcolor(lb, txtCol)
                    label.set_tooltip(lb, "ABSORBED: buying failed to lift price")
                    absBuyNow := true
            else
                absorbed := ll > p - absTol * tick and (not absNeedClose or close > p) and (absRevTicks <= 0 or close >= p + absRevTicks * tick)
                if absorbed
                    label.set_color(lb, color.new(absSellCol, 0))
                    label.set_text(lb, "A")
                    label.set_textcolor(lb, txtCol)
                    label.set_tooltip(lb, "ABSORBED: selling failed to push price lower")
                    absSellNow := true
            if absOnly and not absorbed
                label.delete(lb)
            pP.remove(k)
            pSide.remove(k)
            pBar.remove(k)
            pLbl.remove(k)
 
// =====================================================================
// Big trade detection (confirmed bars only, no repainting)
// =====================================================================
if barstate.isconfirmed and not na(fp)
    rows = fp.rows()
    n    = rows.size()
 
    // Threshold from PREVIOUS samples so a bar can't raise its own bar
    float thr = na
    if filterMode == "Manual"
        thr := manualMin
    else if hist.size() >= 200
        thr := math.max(hist.percentile_nearest_rank(pct), autoFloor)
    lastThr := thr
 
    if n > 0 and not na(thr) and inSess
        cP    = array.new<float>()
        cV    = array.new<float>()
        cSide = array.new<int>()
        for r in rows
            bv  = r.buy_volume()
            sv  = r.sell_volume()
            tv  = r.total_volume()
            prc = ticksRow == 1 ? r.down_price() : (r.up_price() + r.down_price()) / 2
            okMaxB = maxFilter <= 0 or bv <= maxFilter
            okMaxS = maxFilter <= 0 or sv <= maxFilter
            okDomB = domPct <= 0 or (tv > 0 and bv / tv * 100 >= domPct)
            okDomS = domPct <= 0 or (tv > 0 and sv / tv * 100 >= domPct)
            if showBuys and bv >= thr and okMaxB and okDomB
                cP.push(prc)
                cV.push(bv)
                cSide.push(1)
            if showSells and sv >= thr and okMaxS and okDomS
                cP.push(prc)
                cV.push(sv)
                cSide.push(-1)
 
        // Draw the largest levels per side
        for s in array.from(1, -1)
            for j = 1 to maxPerBar
                best = -1
                bestV = 0.0
                if cV.size() > 0
                    for i = 0 to cV.size() - 1
                        if cSide.get(i) == s and cV.get(i) > bestV
                            bestV := cV.get(i)
                            best  := i
                if best >= 0
                    vol   = cV.get(best)
                    prc   = cP.get(best)
                    ratio = vol / thr
                    steps = ratio > 1 ? int(math.floor(math.log(ratio) / math.log(sizeStep))) : 0
                    sz    = sizeFor(baseIdx + steps)
                    opac  = math.min(100.0, minOpac + (100 - minOpac) * math.min((ratio - 1) / 3, 1))
                    col   = s == 1 ? buyCol : sellCol
                    eligible = ratio >= absMinX
                    hide  = absOnly
                    isTxt = markerIn == "Text"
                    txt   = isTxt or showSize ? str.tostring(vol, "#") : ""
                    tip   = (s == 1 ? "Big BUY " : "Big SELL ") + str.tostring(vol, "#") + " @ " + str.tostring(prc, format.mintick) + "\nThreshold: " + str.tostring(thr, "#") + " (" + str.tostring(ratio, "#.#") + "x)"
                    lb = label.new(bar_index, prc, hide ? "" : txt, xloc = xloc.bar_index, yloc = yloc.price, color = hide or isTxt ? color.new(col, 100) : color.new(col, 100 - opac), style = mStyle, textcolor = hide ? color.new(txtCol, 100) : isTxt ? col : txtCol, size = sz, tooltip = tip)
                    bubbles.push(lb)
                    if bubbles.size() > maxBubbles
                        label.delete(bubbles.shift())
                    if hide and not eligible
                        label.delete(lb)
                    if useAbsE and eligible
                        pP.push(prc)
                        pSide.push(s)
                        pBar.push(bar_index)
                        pLbl.push(lb)
                    if s == 1
                        bigBuyNow := true
                    else
                        bigSellNow := true
                    cV.set(best, -1.0)
 
    // Add this bar's levels to the automatic sample
    for r in rows
        bv = r.buy_volume()
        sv = r.sell_volume()
        if bv > 0
            hist.push(bv)
        if sv > 0
            hist.push(sv)
    while hist.size() > histLen
        hist.shift()
 
// =====================================================================
// Info box
// =====================================================================
infoPos = switch infoPosIn
    "Top right" => position.top_right
    "Top left"  => position.top_left
    "Bottom left" => position.bottom_left
    => position.bottom_right
 
var table info = table.new(infoPos, 2, 3, border_width = 0)
if showInfo and barstate.islast
    bg = color.new(color.black, 80)
    table.cell(info, 0, 0, "Mode", text_color = color.white, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.cell(info, 1, 0, filterMode == "Automatic" ? "Auto (" + intensity + ")" : "Manual", text_color = color.white, bgcolor = bg, text_size = size.small)
    table.cell(info, 0, 1, "Threshold", text_color = color.white, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.cell(info, 1, 1, na(lastThr) ? "warming up" : str.tostring(lastThr, "#") + " contracts", text_color = color.white, bgcolor = bg, text_size = size.small)
    table.cell(info, 0, 2, "Footprint", text_color = color.white, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
    table.cell(info, 1, 2, na(fp) ? "no data" : "ok", text_color = color.white, bgcolor = bg, text_size = size.small)
 
// =====================================================================
// Alerts (set to "Once per bar close")
// =====================================================================
alertcondition(bigBuyNow, "Big buying", "Big Trades: large aggressive BUYING on {{ticker}} {{interval}}")
alertcondition(bigSellNow, "Big selling", "Big Trades: large aggressive SELLING on {{ticker}} {{interval}}")
alertcondition(absBuyNow, "Absorbed buying (bearish)", "Big Trades: buying ABSORBED on {{ticker}} {{interval}}")
alertcondition(absSellNow, "Absorbed selling (bullish)", "Big Trades: selling ABSORBED on {{ticker}} {{interval}}")

← 返回列表