Absorption Edge

CopyCats · study · 210 行 · 点赞 15 · TradingView 原页

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

Pine Script

//@version=6
// Volume Pressure — aggressive buys vs sells, efficiency, and absorption.
// Inspired by Bookmap/NinjaTrader-style "volume pressure" panels.
//
// HOW AGGRESSION IS MEASURED
//  • Live bar: every price update is classified with the tick rule
//    (uptick = aggressive buy, downtick = aggressive sell, unchanged = same as last).
//  • Historical bars: intrabar data (lower timeframe) is classified the same way.
//  • If no intrabar data is available, falls back to close location within the bar's range.
//
// EFFICIENCY
//  How far price moved compared with what that much delta normally moves it.
//  +100% = normal follow-through. Near 0% with heavy delta = ABSORPTION.
//  Negative = price moved against the aggressive side.
 
indicator("Volume Pressure", "Absorption Edge", overlay = true, max_lines_count = 500)
 
// ───────── Inputs ─────────
grpData  = "Data"
ltfMode  = input.string("Auto", "Intrabar timeframe", options = ["Auto", "1S", "5S", "15S", "1", "5"], group = grpData,
     tooltip = "Used for historical bars. Seconds (S) need a TradingView plan that includes seconds data. Auto uses 1S on charts of 1 minute or lower only if 'Allow seconds data' is on.")
allowSec = input.bool(false, "Allow seconds data (paid plan)", group = grpData)
useTicks = input.bool(true, "Use live tick-by-tick on realtime bar", group = grpData)
winBars  = input.int(1, "Window (bars)", minval = 1, group = grpData, tooltip = "1 = current bar only. Higher values sum the last N bars.")
maxLen   = input.int(50, "'Max' lookback (bars)", minval = 5, group = grpData)
 
grpEff   = "Efficiency / Absorption"
effLen   = input.int(50, "Baseline length", minval = 10, group = grpEff)
absMult  = input.float(1.5, "Absorption: |delta| ≥ x × average", minval = 0.5, step = 0.1, group = grpEff)
absEff   = input.float(30.0, "Absorption: efficiency ≤ %", group = grpEff)
pressTh  = input.float(75.0, "Pressure alert threshold %", minval = 50, maxval = 100, group = grpEff)
 
grpVis   = "Display"
showPan  = input.bool(true, "Show panel", group = grpVis)
panPos   = input.string("Bottom Right", "Panel position", options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right"], group = grpVis)
barW     = input.int(14, "Panel bar width", minval = 5, maxval = 30, group = grpVis)
showAbs  = input.bool(true, "Mark absorption", group = grpVis)
colBars  = input.bool(false, "Color absorption candles", group = grpVis)
 
grpOrb   = "Opening Range"
showOrb  = input.bool(true, "Show opening range", group = grpOrb)
orbSess  = input.session("0820-0835", "ORB session", group = grpOrb, tooltip = "08:20–08:35 NY = first 15 min of COMEX gold. Use 0930-0945 for equity index futures.")
orbTz    = input.string("America/New_York", "ORB time zone", group = grpOrb)
 
// ───────── Intrabar timeframe ─────────
chartSec = timeframe.in_seconds()
string ltf = switch ltfMode
    "Auto" => chartSec <= 60 ? (allowSec ? "1S" : timeframe.period) : chartSec <= 900 ? "1" : "5"
    => ltfMode
 
[ltfO, ltfC, ltfV] = request.security_lower_tf(syminfo.tickerid, ltf, [open, close, volume])
 
float ibBuy  = 0.0
float ibSell = 0.0
int   ibDir  = 0
int   n      = ltfV.size()
if n > 1
    for i = 0 to n - 1
        float o  = ltfO.get(i)
        float c  = ltfC.get(i)
        float v  = ltfV.get(i)
        float pc = i == 0 ? o : ltfC.get(i - 1)
        int d = c > pc ? 1 : c < pc ? -1 : c > o ? 1 : c < o ? -1 : ibDir
        if d == 1
            ibBuy += v
        else if d == -1
            ibSell += v
        else
            ibBuy  += v / 2
            ibSell += v / 2
        ibDir := d
else
    // Fallback: close location within the bar
    float rng = high - low
    float pos = rng > 0 ? (close - low) / rng : 0.5
    ibBuy  := volume * pos
    ibSell := volume * (1 - pos)
 
// ───────── Live tick classification ─────────
varip float tBuy    = 0.0
varip float tSell   = 0.0
varip float lastPx  = na
varip float lastVol = 0.0
varip int   lastDir = 0
varip bool  tickFull = false   // true only when we've watched the bar from its first tick
 
if barstate.isrealtime
    if barstate.isnew
        tBuy     := 0.0
        tSell    := 0.0
        lastVol  := 0.0
        tickFull := true
    float dv = volume - lastVol
    if not na(lastPx) and dv > 0
        int d = close > lastPx ? 1 : close < lastPx ? -1 : lastDir
        if d == 1
            tBuy += dv
        else if d == -1
            tSell += dv
        else
            tBuy  += dv / 2
            tSell += dv / 2
        lastDir := d
    else if na(lastPx) and dv > 0 and barstate.isnew
        // first tick of a new bar: assign by direction vs prior close
        int d = close > close[1] ? 1 : close < close[1] ? -1 : lastDir
        if d == 1
            tBuy += dv
        else if d == -1
            tSell += dv
        lastDir := d
    lastPx  := close
    lastVol := volume
 
bool liveTicks = useTicks and barstate.isrealtime and tickFull
float buyBar  = liveTicks ? tBuy  : ibBuy
float sellBar = liveTicks ? tSell : ibSell
 
// ───────── Core metrics ─────────
float buyW   = math.sum(buyBar,  winBars)
float sellW  = math.sum(sellBar, winBars)
float total  = buyW + sellW
float delta  = buyW - sellW
float buyPct  = total > 0 ? buyW  / total * 100 : 50
float sellPct = total > 0 ? sellW / total * 100 : 50
float maxVal = ta.highest(math.max(buyW, sellW), maxLen)
 
float move     = close - open[winBars - 1]
float avgMove  = ta.sma(math.abs(move),  effLen)
float avgDelta = ta.sma(math.abs(delta), effLen)
float k        = avgDelta > 0 ? avgMove / avgDelta : na
float expected = na(k) ? na : delta * k
float eff      = (na(expected) or expected == 0) ? 0.0 : math.max(-200, math.min(200, move / expected * 100))
 
bool heavy   = avgDelta > 0 and math.abs(delta) >= absMult * avgDelta
bool absorb  = heavy and eff <= absEff
bool absBear = absorb and delta > 0   // buyers hit hard, price didn't follow → passive sellers absorbing
bool absBull = absorb and delta < 0   // sellers hit hard, price didn't follow → passive buyers absorbing
 
// ───────── Plots ─────────
plotshape(showAbs and absBear, "Absorption (bearish)", shape.triangledown, location.abovebar, color.new(color.red, 0),   size = size.tiny, text = "ABS")
plotshape(showAbs and absBull, "Absorption (bullish)", shape.triangleup,   location.belowbar, color.new(color.green, 0), size = size.tiny, text = "ABS")
barcolor(colBars and absorb ? color.yellow : na)
 
plot(buyW,   "Aggr. Buys",   display = display.data_window)
plot(sellW,  "Aggr. Sells",  display = display.data_window)
plot(delta,  "Delta",        display = display.data_window)
plot(eff,    "Efficiency %", display = display.data_window)
 
// Opening range
bool inOrb = not na(time(timeframe.period, orbSess, orbTz))
var float orbH = na
var float orbL = na
if inOrb and not inOrb[1]
    orbH := high
    orbL := low
else if inOrb
    orbH := math.max(orbH, high)
    orbL := math.min(orbL, low)
bool orbDone = showOrb and timeframe.isintraday and not inOrb
plot(orbDone ? orbH : na, "ORB High", color.new(color.navy, 0), 2, plot.style_linebr)
plot(orbDone ? orbL : na, "ORB Low",  color.new(color.navy, 0), 2, plot.style_linebr)
bgcolor(showOrb and timeframe.isintraday and inOrb ? color.new(color.gray, 85) : na, title = "ORB window")
 
// ───────── Panel ─────────
f_bar(float v, float mx, int w) =>
    int filled = mx > 0 ? int(math.round(math.min(math.abs(v) / mx, 1.0) * w)) : 0
    str.repeat("█", filled) + str.repeat("░", w - filled)
 
f_pos(string p) =>
    switch p
        "Top Right"    => position.top_right
        "Bottom Left"  => position.bottom_left
        "Bottom Right" => position.bottom_right
        => position.top_left
 
var table pan = table.new(f_pos(panPos), 3, 5, bgcolor = color.new(color.white, 15), border_width = 1, frame_color = color.gray, frame_width = 1)
 
if showPan and barstate.islast
    color txt  = color.black
    color gCol = color.new(color.green, 0)
    color rCol = color.new(color.red, 0)
    color eCol = eff >= 0 ? gCol : rCol
    string src = liveTicks ? "live ticks" : n > 1 ? "intrabar " + ltf : "bar estimate"
 
    table.cell(pan, 0, 0, "Max", text_color = txt, text_size = size.small)
    table.cell(pan, 1, 0, str.tostring(maxVal, format.volume), text_color = txt, text_size = size.small)
    table.cell(pan, 2, 0, "", text_size = size.small)
 
    table.cell(pan, 0, 1, "Aggr. Buys", text_color = txt, text_size = size.small, text_halign = text.align_left)
    table.cell(pan, 1, 1, f_bar(buyW, maxVal, barW), text_color = gCol, text_size = size.small)
    table.cell(pan, 2, 1, str.tostring(buyW, format.volume) + "  (" + str.tostring(buyPct, "#") + "%)", text_color = txt, text_size = size.small)
 
    table.cell(pan, 0, 2, "Aggr. Sells", text_color = txt, text_size = size.small, text_halign = text.align_left)
    table.cell(pan, 1, 2, f_bar(sellW, maxVal, barW), text_color = rCol, text_size = size.small)
    table.cell(pan, 2, 2, str.tostring(sellW, format.volume) + "  (" + str.tostring(sellPct, "#") + "%)", text_color = txt, text_size = size.small)
 
    table.cell(pan, 0, 3, "Efficiency", text_color = txt, text_size = size.small, text_halign = text.align_left)
    table.cell(pan, 1, 3, f_bar(eff, 100, barW), text_color = eCol, text_size = size.small)
    table.cell(pan, 2, 3, (eff >= 0 ? "+" : "") + str.tostring(eff, "#") + "%" + (absorb ? "  ABSORPTION" : ""), text_color = absorb ? color.orange : txt, text_size = size.small)
 
    table.cell(pan, 0, 4, "Source", text_color = color.gray, text_size = size.tiny, text_halign = text.align_left)
    table.cell(pan, 1, 4, src, text_color = color.gray, text_size = size.tiny)
    table.cell(pan, 2, 4, "", text_size = size.tiny)
 
// ───────── Alerts ─────────
alertcondition(ta.crossover(buyPct, pressTh),  "Buy pressure",         "Aggressive buys crossed the pressure threshold")
alertcondition(ta.crossover(sellPct, pressTh), "Sell pressure",        "Aggressive sells crossed the pressure threshold")
alertcondition(absBull, "Bullish absorption", "Heavy selling absorbed — price not following")
alertcondition(absBear, "Bearish absorption", "Heavy buying absorbed — price not following")

← 返回列表