Edo Liquidity Voids

EdoLab-Markets · study · 737 行 · 点赞 20 · TradingView 原页

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

Pine Script

// ─────────────────────────────────────────────────────────────────
// ███████╗██████╗  ██████╗ ██╗      █████╗ ██████╗
// ██╔════╝██╔══██╗██╔═══██╗██║     ██╔══██╗██╔══██╗
// █████╗  ██║  ██║██║   ██║██║     ███████║██████╔╝
// ██╔══╝  ██║  ██║██║   ██║██║     ██╔══██║██╔══██╗
// ███████╗██████╔╝╚██████╔╝███████╗██║  ██║██████╔╝
// ╚══════╝╚═════╝  ╚═════╝ ╚══════╝╚═╝  ╚═╝╚═════╝
// ─────────────────────────────────────────────────────────────────
// ███╗   ███╗ █████╗ ██████╗ ██╗  ██╗███████╗████████╗███████╗
// ████╗ ████║██╔══██╗██╔══██╗██║ ██╔╝██╔════╝╚══██╔══╝██╔════╝
// ██╔████╔██║███████║██████╔╝█████╔╝ █████╗     ██║   ███████╗
// ██║╚██╔╝██║██╔══██║██╔══██╗██╔═██╗ ██╔══╝     ██║   ╚════██║
// ██║ ╚═╝ ██║██║  ██║██║  ██║██║  ██╗███████╗   ██║   ███████║
// ╚═╝     ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝   ╚═╝   ╚══════╝
// ─────────────────────────────────────────────────────────────────
// © Edolab Markets
 
//@version=6
indicator("Edo Liquidity Voids", overlay = true, behind_chart = false, max_boxes_count = 200, max_labels_count = 40)
 
// What changes when a new bar arrives (read before judging the drawing):
// 1. Voids come only from the volume traded at each price level over the latest closed bars
//    (the Profile Window). Candle structure is not used: no wicks, no gaps between candles,
//    no fills. Only how much volume each price row received.
// 2. The profile is scanned on closed bars only, every few bars (Scan Every). A void is created
//    on the close of a scan bar and its top and bottom never move afterwards. Its box starts at
//    the first bar of the window it was measured on, because that is the stretch of bars where
//    little volume traded at those prices, but the box only appears on the scan bar.
// 3. The forming bar is never used: its volume keeps changing until it closes. Voids, states,
//    events and alerts change only when a bar closes. Distances in the panel and in the labels
//    follow the live price.
// 4. A void is removed when the volume traded inside it after detection reaches the normal
//    level of its window (absorbed), or when no bar has touched it for a long time. Nothing is
//    removed or redrawn backwards.
// 5. The window profile on the right is rebuilt every bar from the latest closed window, and only
//    drawn once the window is full. Its highlighted rows are under the void threshold; they only
//    become a void with heavier volume above and below, the minimum height and a scan.
// 6. Part of the drawing follows the visible part of the chart, so it can change when you scroll or
//    zoom: the void labels sit at the left edge of the visible part of each void, the profile width
//    follows the number of visible bars, voids outside the visible prices are not drawn, the labels stay
//    inside the visible prices and the panel can move to another corner. Voids, states, events, alerts
//    and the panel values do not.
 
// ================== CONSTANTS ==================
 
const int   ATR_LEN   = 50     // yardstick for heights and distances
const int   MAX_TRACK = 30     // active voids followed at the same time
const int   RET_KEEP  = 50     // removed voids remembered so the same zone is not detected again at once
const float ACCEPT    = 1.0    // a void is absorbed when its volume reaches this share of a normal row
const int   PROF_GAP  = 2      // bars between the last candle and the window profile
 
const float PROF_SHARE = 0.06  // profile width as a share of the visible bars (display only)
const int   PROF_MIN   = 4     // narrowest profile, in bars
const float SIDE_SHARE = 0.35  // part of the visible chart, at each side, that the panel can cover
const float LOGO_PCT   = 9.0   // bottom-left: empty row under the panel, in % of the pane height, so the TradingView logo does not cover its last row
const float ICON_PCT   = 6.0   // bottom-right: the same for the round TradingView button in that corner
const float LEGEND_PCT = 4.0   // top-left: empty row above the panel, in % of the pane height, so the TradingView legend (study title and fold arrow) does not cover its first rows
 
gDet = "Detection"
gLif = "Lifecycle"
gDsp = "Display"
gSty = "Style"
gPan = "Panel"
 
// ================== SETTINGS — DETECTION ==================
 
winLen    = input.int(300, "Profile Window (bars)", minval = 100, maxval = 1000, group = gDet, tooltip = "Closed bars whose volume is spread over price rows to find the voids. 300 bars is about 14 months on the daily chart and 6 to 7 weeks on the 1-hour chart. Longer windows find the older, larger voids; shorter ones the recent ones. Nothing is drawn until the chart has this many closed bars.")
rowsN     = input.int(80, "Price Rows", minval = 30, maxval = 150, group = gDet, tooltip = "The price range of the window is cut into this many rows. Each bar's volume is shared evenly between the rows its high-low range covers. More rows = finer voids.")
thrPct    = input.float(30, "Void Threshold (% of the median row)", minval = 5, maxval = 80, step = 5, group = gDet, tooltip = "A row is thin when its volume is below this percentage of the median row of the window. Lower = only the emptiest zones. A void is a run of thin rows with heavier volume above and below it: the thin tails at the top and bottom of the window are not voids.")
minWAtr   = input.float(0.5, "Minimum Void Height (ATR)", minval = 0.1, maxval = 5.0, step = 0.1, group = gDet, tooltip = "Thinner runs are ignored. Measured in 50-bar ATR.")
mergeAtr  = input.float(0.25, "Merge Distance (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = gDet, tooltip = "Two thin runs separated by less than this distance become one void, as long as the joined zone stays under the threshold on average. 0 = only touching rows.")
scanEvery = input.int(5, "Scan Every (bars)", minval = 1, maxval = 50, group = gDet, tooltip = "How often the window is scanned for new voids, on closed bars. 1 = every bar (slower on long charts). A new void appears at most this many bars after it formed. Windows longer than 500 bars are scanned at least every window / 100 bars, to stay inside the TradingView time limit; the panel shows the step in use.")
 
// ================== SETTINGS — LIFECYCLE ==================
 
expireB   = input.int(500, "Remove After Untouched (bars)", minval = 50, maxval = 3000, group = gLif, tooltip = "A void that no bar has touched for this many bars is removed. A void is also removed as soon as the volume traded inside it since detection reaches the median row of the window it came from: it is no longer thin, it has been absorbed.")
 
// ================== SETTINGS — DISPLAY ==================
 
perSide   = input.int(3, "Voids Shown per Side", minval = 1, maxval = 6, group = gDsp, tooltip = "Nearest voids drawn above and below the price. The one that contains the price is always drawn. The rest keep being followed and counted in the panel.")
maxDist   = input.float(8, "Hide Voids Farther Than (ATR)", minval = 2, maxval = 50, step = 1, group = gDsp, tooltip = "Voids farther than this from the price are not drawn, and neither are voids outside the prices of the visible candles, so a distant zone never squeezes the chart scale. They keep being followed and counted in the panel. The window profile is cut at the same distance and at the visible prices.")
showProf  = input.bool(true, "Show Window Profile", group = gDsp, tooltip = "Volume per price row of the latest closed window, drawn to the right of the last candle once the window is full. Rows under the void threshold take the void colour.")
profW     = input.int(30, "Max Profile Width (bars)", minval = 10, maxval = 100, group = gDsp, tooltip = "The profile takes about 6 % of the visible bars, at least 4 bars and at most this many, so it keeps a similar size when you zoom.")
showLbl   = input.bool(true, "Show Void Labels", group = gDsp, tooltip = "Label at the left edge of the visible part of each drawn void, where the void has the fewest candles: distance to the price in 50-bar ATR, what price has done with it (intact: no candle has touched it · tested: touched by a candle, wick or body · crossed: a close went from one side to the other) and the volume inside it as a share of a normal row of its window (vol %). That share grows as volume trades inside the void; at 100 % the void is removed.")
labelSep  = input.float(0.6, "Label Spacing (ATR)", minval = 0.2, maxval = 3.0, step = 0.1, group = gDsp, tooltip = "Minimum vertical gap between labels so close voids never overlap their text. The gap also grows when the chart is zoomed out.")
labelSize = input.string("Medium", "Label Size", options = ["Small", "Medium", "Large"], group = gDsp)
showMarks = input.bool(true, "Show Crossing Markers", group = gDsp, tooltip = "Triangles when a close crosses a void from one side to the other: green upward, red downward.")
markGap   = input.int(10, "Min Bars Between Crossing Markers", minval = 1, maxval = 100, group = gDsp, tooltip = "A crossing triangle is skipped when another one was drawn less than this many bars before, so a void crossed back and forth does not fill the chart. The panel and the alerts still see every crossing. 1 = every crossing.")
showNewMk = input.bool(false, "Show New Void Diamonds", group = gDsp, tooltip = "Small diamond above the bar where a new void is detected. Off by default to keep the chart clean; the panel and the alerts report new voids anyway.")
 
// ================== SETTINGS — STYLE ==================
 
voidCol = input.color(#8E7CC3, "Void", group = gSty, tooltip = "A void has no direction, so it never uses green or red.")
profCol = input.color(#787b86, "Profile Rows", group = gSty)
bullCol = input.color(#4caf50, "Crossed Up", inline = "c1", group = gSty)
bearCol = input.color(#e53935, "Crossed Down", inline = "c1", group = gSty, tooltip = "Only the crossing markers and events use green and red: they say which way a close went through a void.")
warnCol = input.color(#f5a623, "Warnings", group = gSty)
fillTr  = input.int(80, "Void Fill Transparency", minval = 50, maxval = 100, group = gSty, tooltip = "The study is drawn in front of the candles, so keep it high enough to see them through it. 100 = no fill. With the Light theme the fill and the borders are drawn somewhat stronger so the voids stand out on a white background.")
profTr  = input.int(55, "Profile Transparency", minval = 0, maxval = 95, group = gSty)
 
// ================== SETTINGS — PANEL ==================
 
showPanel    = input.bool(true, "Show Panel", group = gPan, tooltip = "Small table with the position of the price, the nearest void above and below, the voids followed, the window and the volume source.")
panelDetail  = input.string("Full", "Panel Detail", options = ["Full", "Compact"], group = gPan, tooltip = "Compact keeps only the state, the nearest void above and below and the last event, plus a warning when the symbol has no real traded volume.")
panelPos     = input.string("Top Right", "Panel Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = gPan)
panelAvoid   = input.bool(true, "Keep Panel Off the Drawing", group = gPan, tooltip = "The panel moves to another corner when the chosen one would cover the latest candles, the window profile or the void labels and another corner has more room. It moves back when there is room again.")
panelSize    = input.string("Medium", "Panel Size", options = ["Small", "Medium"], group = gPan)
themeMode    = input.string("Dark", "Theme Mode", options = ["Dark", "Light"], group = gPan, tooltip = "Match your TradingView background theme.")
panelOpacity = input.int(70, "Panel Opacity (%)", minval = 0, maxval = 100, group = gPan, tooltip = "100 = solid background, 0 = transparent.")
 
// ================== THEME ==================
 
isDark      = themeMode == "Dark"
textCol     = isDark ? #ffffff : #131722
headerBg    = isDark ? #2a2e39 : #d1d4dc
subHeaderBg = isDark ? #363a45 : #e0e3eb
cellBg      = isDark ? #1e222d : #f0f3fa
cellTxt     = isDark ? #d1d4dc : #363a45
numTxt      = isDark ? #b2b5be : #555a67
panelTransp = 100 - panelOpacity
// The light background washes out the fill: draw it and the borders somewhat stronger there
fillTrE     = isDark ? fillTr : math.max(fillTr - 12, 0)
bordTr      = isDark ? 40 : 20
 
lblSz = labelSize == "Small" ? size.small : labelSize == "Large" ? size.large : size.normal
panSz = panelSize == "Small" ? size.tiny : size.small
 
// ================== SERIES (every bar) ==================
 
atr      = ta.atr(ATR_LEN)
barVol   = math.max(nz(volume), 0.0)
barNow   = bar_index    // plain copy of the bar number, stored in the voids created on this bar
// Scan step in use: long windows are scanned less often so the script stays fast
scanStep = winLen > 500 ? math.max(scanEvery, int(math.ceil(winLen / 100.0))) : scanEvery
// FX and CFD feeds carry tick volume (number of price changes), not traded size
isTick   = syminfo.volumetype == "tick" or syminfo.type == "forex" or syminfo.type == "cfd"
 
// ================== TYPES ==================
 
// One void: its band is frozen at detection; the rest follows the closed bars after it
type LvZone
    float top
    float bot
    int   bar0
    int   left
    float initVol
    float refDens
    float newVol
    int   prevSide
    int   lastSide
    bool  touched
    int   lastTouch
    int   nCross
    int   endBar
 
// ================== HELPERS ==================
 
fmt(float v) => na(v) ? "—" : str.tostring(v, format.mintick)
 
plural(int n, string one, string many) => str.tostring(n) + " " + (n == 1 ? one : many)
 
agoTxt(int b) => b == bar_index ? "this bar" : plural(bar_index - b, "bar", "bars") + " ago"
 
rowOf(float p, float lo, float rowH) => math.max(0, math.min(rowsN - 1, int(math.floor((p - lo) / rowH))))
 
// 0 intact · 1 tested: touched by a candle (any overlap of its high-low range, wick or body) · 2 price inside · 3 crossed by a close at least once
voidState(LvZone v, float c) => c >= v.bot and c <= v.top ? 2 : v.nCross > 0 ? 3 : v.touched ? 1 : 0
 
// What happened to the void since it was detected
histName(LvZone v) => v.nCross > 0 ? "crossed " + plural(v.nCross, "time", "times") : v.touched ? "tested" : "intact"
 
// Volume inside the void now, as a share of a normal row of the window it came from; it is removed at 100 %
volPct(LvZone v) => (v.initVol + v.newVol) / (v.refDens * (v.top - v.bot)) * 100
 
// Where the price is with respect to the void, in 50-bar ATR
posName(LvZone v, float c, float a) => c >= v.bot and c <= v.top ? "price inside" : v.bot > c ? str.tostring((v.bot - c) / a, "0.0") + " ATR above" : str.tostring((c - v.top) / a, "0.0") + " ATR below"
 
// ================== CLOSED-BAR STORE ==================
 
// Latest closed bars of the window; arrays avoid deep history references
var array<float> bH = array.new_float()
var array<float> bL = array.new_float()
var array<float> bV = array.new_float()
 
// Volume per price row of the stored window: each bar's volume is shared evenly over its high-low range
buildRows(float lo, float rowH) =>
    array<float> vol = array.new_float(rowsN, 0.0)
    int n = bH.size()
    if n > 0
        for i = 0 to n - 1
            float w = bV.get(i)
            if w > 0
                float h = bH.get(i)
                float l = bL.get(i)
                int r0 = rowOf(l, lo, rowH)
                int r1 = rowOf(h, lo, rowH)
                if r0 == r1
                    vol.set(r0, vol.get(r0) + w)
                else
                    float rng = h - l
                    for r = r0 to r1
                        float rl = lo + r * rowH
                        float ov = math.min(h, rl + rowH) - math.max(l, rl)
                        if ov > 0 and rng > 0
                            vol.set(r, vol.get(r) + w * ov / rng)
    vol
 
// ================== VOID ENGINE (closed bars only) ==================
 
var array<LvZone> act = array.new<LvZone>()
var array<LvZone> ret = array.new<LvZone>()
 
// Last event: 3/-3 crossed up/down · 4/-4 left a void up/down · 1 entered a void · 5 void absorbed · 2 new void
var int lastEv  = 0
var int lastEvB = na
var int lastNew = 0    // 1 above the price · -1 below · 0 at the price
 
bool evCrossUp = false
bool evCrossDn = false
bool evExitUp  = false
bool evExitDn  = false
bool evEnter   = false
bool evAbsorb  = false
bool evNewUp   = false
bool evNewDn   = false
bool evNewIn   = false
 
if barstate.isconfirmed
    // 1 · Follow every active void with this closed bar
    int i = 0
    while i < act.size()
        LvZone v = act.get(i)
        bool touch = high >= v.bot and low <= v.top
        if barVol > 0
            float rng = high - low
            float ov  = math.min(high, v.top) - math.max(low, v.bot)
            if rng > 0 and ov > 0
                v.newVol := v.newVol + barVol * ov / rng
            else if rng == 0 and touch
                v.newVol := v.newVol + barVol
        int side = close > v.top ? 1 : close < v.bot ? -1 : 0
        if touch
            v.touched   := true
            v.lastTouch := bar_index
        if side == 0 and v.prevSide != 0
            evEnter := true
        if v.prevSide == 0 and side != 0
            evExitUp := evExitUp or side == 1
            evExitDn := evExitDn or side == -1
        // A close on the other side of the void than the last close outside it = crossed
        if side != 0 and v.lastSide != 0 and side != v.lastSide
            evCrossUp := evCrossUp or side == 1
            evCrossDn := evCrossDn or side == -1
            v.nCross  := v.nCross + 1
        if side != 0
            v.lastSide := side
        v.prevSide := side
        bool absorbed = v.initVol + v.newVol >= ACCEPT * v.refDens * (v.top - v.bot)
        bool expired  = bar_index - v.lastTouch > expireB
        if absorbed or expired
            evAbsorb := evAbsorb or absorbed
            v.endBar := bar_index
            ret.push(v)
            act.remove(i)
        else
            i += 1
 
    // 2 · Store the closed bar
    bH.push(high)
    bL.push(low)
    bV.push(barVol)
    if bH.size() > winLen
        bH.shift()
        bL.shift()
        bV.shift()
 
    // 3 · Scan the window profile for new voids
    if bH.size() >= winLen and bar_index % scanStep == 0 and atr > 0 and bV.sum() > 0
        float lo   = bL.min()
        float rowH = (bH.max() - lo) / rowsN
        if rowH > 0
            array<float> vol = buildRows(lo, rowH)
            float med = vol.median()
            if med > 0
                float thr = thrPct / 100.0 * med
                int gapRows = int(math.floor(mergeAtr * atr / rowH))
                // Runs of thin rows, joined when the rows between them are few and the joined zone stays thin
                array<int> ms = array.new_int()
                array<int> me = array.new_int()
                int s = -1
                for r = 0 to rowsN
                    bool thin = false
                    if r < rowsN
                        thin := vol.get(r) < thr
                    if thin and s < 0
                        s := r
                    else if not thin and s >= 0
                        int e = r - 1
                        bool joined = false
                        if ms.size() > 0
                            int pa = ms.last()
                            if s - me.last() - 1 <= gapRows
                                float sm = 0.0
                                for k = pa to e
                                    sm += vol.get(k)
                                if sm / (e - pa + 1) < thr
                                    me.set(me.size() - 1, e)
                                    joined := true
                        if not joined
                            ms.push(s)
                            me.push(e)
                        s := -1
                // A void needs heavier volume (at least the median row) above and below it, and the minimum height
                if ms.size() > 0
                    for k = 0 to ms.size() - 1
                        int a = ms.get(k)
                        int b = me.get(k)
                        float lm = 0.0
                        float rm = 0.0
                        if a > 0
                            for r = 0 to a - 1
                                lm := math.max(lm, vol.get(r))
                        if b < rowsN - 1
                            for r = b + 1 to rowsN - 1
                                rm := math.max(rm, vol.get(r))
                        if lm >= med and rm >= med and (b - a + 1) * rowH >= minWAtr * atr
                            float vb = lo + a * rowH
                            float vt = lo + (b + 1) * rowH
                            // A zone already followed, or removed less than one window ago, is not detected again
                            bool clash = false
                            if act.size() > 0
                                for j = 0 to act.size() - 1
                                    LvZone o = act.get(j)
                                    if vt > o.bot and vb < o.top
                                        clash := true
                            if not clash and ret.size() > 0
                                for j = 0 to ret.size() - 1
                                    LvZone o = ret.get(j)
                                    if vt > o.bot and vb < o.top and bar_index - o.endBar < winLen
                                        clash := true
                            if not clash
                                float iv = 0.0
                                for r = a to b
                                    iv += vol.get(r)
                                int sd = close > vt ? 1 : close < vb ? -1 : 0
                                act.push(LvZone.new(top = vt, bot = vb, bar0 = barNow, left = bar_index - bH.size() + 1, initVol = iv, refDens = med / rowH, newVol = 0.0, prevSide = sd, lastSide = sd, touched = false, lastTouch = barNow, nCross = 0, endBar = na))
                                evNewUp := evNewUp or sd == -1
                                evNewDn := evNewDn or sd == 1
                                evNewIn := evNewIn or sd == 0
        // Too many voids followed: drop the one untouched for the longest time
        while act.size() > MAX_TRACK
            int jOld = 0
            for j = 1 to act.size() - 1
                LvZone o = act.get(j)
                LvZone p = act.get(jOld)
                if o.lastTouch < p.lastTouch
                    jOld := j
            LvZone d = act.get(jOld)
            d.endBar := bar_index
            ret.push(d)
            act.remove(jOld)
 
    while ret.size() > RET_KEEP
        ret.shift()
 
    int ev = evCrossUp ? 3 : evCrossDn ? -3 : evExitUp ? 4 : evExitDn ? -4 : evEnter ? 1 : evAbsorb ? 5 : evNewUp or evNewDn or evNewIn ? 2 : 0
    if ev != 0
        lastEv  := ev
        lastEvB := bar_index
    if evNewUp or evNewDn or evNewIn
        lastNew := evNewUp ? 1 : evNewDn ? -1 : 0
 
// ================== READINGS (one value per bar, for external tools) ==================
 
int   lvInside    = 0
int   lvNearState = -1
float lvDistUp    = 999.0
float lvDistDn    = 999.0
int   lvActive    = act.size()
int   iUp         = -1
int   iDn         = -1
int   iIn         = -1
if act.size() > 0
    float bestD = na
    int   iNear = -1
    for j = 0 to act.size() - 1
        LvZone o = act.get(j)
        bool inside = close >= o.bot and close <= o.top
        if inside
            lvInside := 1
            iIn := iIn < 0 ? j : iIn
        if o.bot > close
            if iUp < 0
                iUp := j
            else
                LvZone u = act.get(iUp)
                if o.bot < u.bot
                    iUp := j
        if o.top < close
            if iDn < 0
                iDn := j
            else
                LvZone w = act.get(iDn)
                if o.top > w.top
                    iDn := j
        float dd = inside ? 0.0 : math.min(math.abs(o.bot - close), math.abs(o.top - close))
        if na(bestD) or dd < bestD
            bestD := dd
            iNear := j
    LvZone nv = act.get(iNear)
    lvNearState := voidState(nv, close)
    if atr > 0
        if iUp >= 0
            LvZone u = act.get(iUp)
            lvDistUp := (u.bot - close) / atr
        if iDn >= 0
            LvZone w = act.get(iDn)
            lvDistDn := (close - w.top) / atr
int lvLastEv = lastEv
int lvBarsEv = na(lastEvB) ? 999 : bar_index - lastEvB
int lvVolume = bV.size() == 0 ? -1 : bV.sum() <= 0 ? 0 : isTick ? 2 : 1
 
 
// ================== VISIBLE RANGE (display only) ==================
 
// Price span of the visible candles, of their left and right parts (where the panel can sit), the first
// visible bar and the number of visible bars. Used only to place and size the drawing and the panel;
// nothing in the voids, the states, the events or the readings uses them
int   visL  = chart.left_visible_bar_time
int   visR  = chart.right_visible_bar_time
bool  inVis = not na(visL) and not na(visR) and time >= visL and time <= visR
float sideW = inVis ? (visR - visL) * SIDE_SHARE : na
bool  inRgt = inVis and time >= visR - sideW
bool  inLft = inVis and time <= visL + sideW
 
var float visHi = na
var float visLo = na
var float rgtHi = na
var float rgtLo = na
var float lftHi = na
var float lftLo = na
var int   visLB = na
var int   nVis  = 0
if inVis
    visHi := na(visHi) ? high : math.max(visHi, high)
    visLo := na(visLo) ? low : math.min(visLo, low)
    visLB := na(visLB) ? bar_index : visLB
    nVis  += 1
if inRgt
    rgtHi := na(rgtHi) ? high : math.max(rgtHi, high)
    rgtLo := na(rgtLo) ? low : math.min(rgtLo, low)
if inLft
    lftHi := na(lftHi) ? high : math.max(lftHi, high)
    lftLo := na(lftLo) ? low : math.min(lftLo, low)
 
// Approximate height of one label as a share of the visible price span (a chart pane of about 600 px)
float visSpan = not na(visHi) and not na(visLo) ? visHi - visLo : na
float lblH    = not na(visSpan) and visSpan > 0 ? visSpan * (labelSize == "Small" ? 0.045 : labelSize == "Large" ? 0.08 : 0.06) : 0.0
 
// What the drawing occupies, read by the panel to choose its corner
float profTopY = na
float profBotY = na
float lblTopY  = na
float lblBotY  = na
float drawHi   = na
float drawLo   = na
int   nDrawn   = 0
 
// ================== DRAWING (last bar only) ==================
 
var array<box>   drawBoxes  = array.new_box()
var array<label> drawLabels = array.new_label()
 
if barstate.islast
    while drawBoxes.size() > 0
        box.delete(drawBoxes.pop())
    while drawLabels.size() > 0
        label.delete(drawLabels.pop())
    // The profile appears only once the window is full, with a width that follows the visible bars
    bool  profOn = showProf and bH.size() >= winLen and bV.sum() > 0
    int   profWN = math.min(profW, math.max(PROF_MIN, int(math.round(nVis * PROF_SHARE))))
    int   xP0    = bar_index + PROF_GAP
    int   xEnd   = profOn ? xP0 + profWN : xP0
    float span   = maxDist * atr
    bool  visOk  = not na(visSpan) and visSpan > 0
    // Boxes and labels stay within the prices of the visible candles, half a label from their edges: above them
    // TradingView draws the indicator legend, below them the time axis
    float safeHi = visOk ? visHi - lblH / 2 : na
    float safeLo = visOk ? visLo + lblH / 2 : na
    if atr > 0
        // Window profile of the latest closed bars, cut at the display distance and at the visible prices
        if profOn
            float lo   = bL.min()
            float rowH = (bH.max() - lo) / rowsN
            if rowH > 0
                array<float> vol = buildRows(lo, rowH)
                float mx  = vol.max()
                float thr = thrPct / 100.0 * vol.median()
                if mx > 0
                    for r = 0 to rowsN - 1
                        float v  = vol.get(r)
                        float rb = lo + r * rowH
                        float rt = rb + rowH
                        if v > 0 and rt >= close - span and rb <= close + span and (not visOk or (rt >= visLo and rb <= visHi))
                            int w = math.max(1, int(math.round(profWN * v / mx)))
                            drawBoxes.push(box.new(xP0, rt - rowH * 0.06, xP0 + w, rb + rowH * 0.06, border_width = 0, bgcolor = color.new(v < thr ? voidCol : profCol, profTr)))
                            profTopY := na(profTopY) ? rt : math.max(profTopY, rt)
                            profBotY := na(profBotY) ? rb : math.min(profBotY, rb)
        // Voids drawn: the one around the price and the nearest ones above and below within the display distance
        array<int>  sel    = array.new_int()
        array<bool> picked = array.new_bool(act.size(), false)
        if act.size() > 0
            if iIn >= 0
                sel.push(iIn)
                picked.set(iIn, true)
            for side = 0 to 1
                for n = 1 to perSide
                    int best = -1
                    float bestD = na
                    for j = 0 to act.size() - 1
                        LvZone o = act.get(j)
                        float d = side == 0 ? o.bot - close : close - o.top
                        bool inView = not visOk or (o.bot < safeHi and o.top > safeLo)
                        if not picked.get(j) and d > 0 and d <= span and inView and (na(bestD) or d < bestD)
                            best  := j
                            bestD := d
                    if best >= 0
                        sel.push(best)
                        picked.set(best, true)
        array<float>  ly = array.new_float()
        array<string> lt = array.new_string()
        array<int>    lx = array.new_int()
        nDrawn := sel.size()
        if sel.size() > 0
            for k = 0 to sel.size() - 1
                LvZone o = act.get(sel.get(k))
                bool ins = close >= o.bot and close <= o.top
                int  xL  = math.max(o.left, bar_index - 4999)
                drawBoxes.push(box.new(xL, o.top, xEnd, o.bot, border_color = color.new(voidCol, ins ? 0 : bordTr), border_width = ins ? 2 : 1, border_style = o.nCross > 0 ? line.style_dashed : line.style_solid, bgcolor = color.new(voidCol, ins ? math.max(fillTrE - 10, 0) : fillTrE)))
                drawHi := na(drawHi) ? o.top : math.max(drawHi, o.top)
                drawLo := na(drawLo) ? o.bot : math.min(drawLo, o.bot)
                // Middle of the void, moved inside the visible prices when the void sticks out of them
                float yMid = (o.top + o.bot) / 2
                ly.push(visOk ? math.max(math.min(yMid, math.min(o.top, safeHi)), math.max(o.bot, safeLo)) : yMid)
                // Left edge of the visible part of the void: inside its window the void had the fewest candles
                lx.push(math.min(bar_index, math.max(xL, nz(visLB, xL)) + 1))
                lt.push(posName(o, close, atr) + " · " + histName(o) + " · vol " + str.tostring(volPct(o), "0") + " %")
        // Labels pushed apart so close voids never overlap their text, also when the chart is zoomed out
        if showLbl and ly.size() > 0
            array<int> ord = ly.sort_indices(order.descending)
            float sep   = math.max(labelSep * atr, lblH)
            float prevY = na
            for k = 0 to ord.size() - 1
                int   q = ord.get(k)
                float y = ly.get(q)
                if not na(prevY)
                    y := math.min(y, prevY - sep)
                prevY := y
                // A label pushed under the visible prices would sit on the time axis: it is not drawn
                if not visOk or y >= safeLo
                    lblTopY := na(lblTopY) ? y : math.max(lblTopY, y)
                    lblBotY := na(lblBotY) ? y : math.min(lblBotY, y)
                    drawLabels.push(label.new(lx.get(q), y, lt.get(q), style = label.style_label_left, color = color.new(voidCol, 15), textcolor = #ffffff, size = lblSz))
 
// ================== PANEL ==================
 
evTxt(int c) => c == 3 ? "Crossed a void up" : c == -3 ? "Crossed a void down" : c == 4 ? "Left a void up" : c == -4 ? "Left a void down" : c == 1 ? "Entered a void" : c == 5 ? "Void absorbed" : c == 2 ? (lastNew == 1 ? "New void above" : lastNew == -1 ? "New void below" : "New void at the price") : "None yet"
 
evCol(int c) => c == 3 or c == 4 ? bullCol : c == -3 or c == -4 ? bearCol : c == 0 ? textCol : voidCol
 
voidRow(int j, bool full) =>
    string t = "None within " + str.tostring(maxDist, "0") + " ATR"
    if j >= 0 and atr > 0
        LvZone o = act.get(j)
        float d = o.bot > close ? (o.bot - close) / atr : (close - o.top) / atr
        if d <= maxDist
            t := full ? fmt(o.bot) + "–" + fmt(o.top) + " · " + str.tostring(d, "0.0") + " ATR · " + histName(o) + " · vol " + str.tostring(volPct(o), "0") + " % · " + plural(bar_index - o.bar0, "bar", "bars") : str.tostring(d, "0.0") + " ATR · " + histName(o)
    t
 
panelRow(table t, int r, string k, string v, color vc, color bg) =>
    table.cell(t, 0, r, k, text_color = cellTxt, bgcolor = bg, text_size = panSz, text_halign = text.align_left)
    table.cell(t, 1, r, v, text_color = vc, bgcolor = bg, text_size = panSz, text_halign = text.align_left)
 
if showPanel
    panelPosTV = switch panelPos
        "Top Right"    => position.top_right
        "Top Left"     => position.top_left
        "Bottom Right" => position.bottom_right
        "Bottom Left"  => position.bottom_left
        => position.top_right
 
    var table panel = table.new(panelPosTV, 2, 10, frame_color = isDark ? #363a45 : #b2b5be, frame_width = 1, border_color = isDark ? #434651 : #c8cbda, border_width = 1)
 
    if barstate.islast
        bgMain = color.new(cellBg, panelTransp)
        bgHead = color.new(headerBg, panelTransp)
        bgSub  = color.new(subHeaderBg, panelTransp)
        table.clear(panel, 0, 0, 1, 9)
        bool full = panelDetail == "Full"
 
        int   nBars = bV.size()
        float totV  = bV.sum()
        int   nZero = 0
        if nBars > 0
            for k = 0 to nBars - 1
                nZero += bV.get(k) <= 0 ? 1 : 0
        bool  noVol = nBars == 0 or totV <= 0
        float zPct  = noVol ? 0.0 : nZero * 100.0 / nBars
        bool  vWarn = isTick or zPct > 20
        // Row of the footer when the panel starts at the top row: the panel has nRows + 1 rows
        int nRows = noVol ? 3 : 5 + (full ? 2 : 0) + (full or vWarn ? 1 : 0)
 
        // Keep the panel off the drawing: when the chosen corner has less room than the panel needs, the panel
        // goes to the first other corner with enough room (same side first), or to the one with the most room.
        // Right corners: the latest candles and the profile. Left corners: the oldest visible candles and the labels
        string pos = panelPosTV
        if panelAvoid and not na(visSpan) and visSpan > 0 and not na(rgtHi) and not na(lftHi)
            bool  lastIn = visR >= time
            float scHi   = math.max(visHi, nz(drawHi, visHi))
            float scLo   = math.min(visLo, nz(drawLo, visLo))
            float scSpan = scHi - scLo
            float rTop   = lastIn and not na(profTopY) ? math.max(rgtHi, profTopY) : rgtHi
            float rBot   = lastIn and not na(profBotY) ? math.min(rgtLo, profBotY) : rgtLo
            float lTop   = not na(lblTopY) ? math.max(lftHi, lblTopY + lblH / 2) : lftHi
            float lBot   = not na(lblBotY) ? math.min(lftLo, lblBotY - lblH / 2) : lftLo
            // Room per corner: 0 top right, 1 bottom right, 2 top left, 3 bottom left (less room where an empty row is kept
            // next to the panel: the TradingView legend above it at the top left, the logo or the round button under it at
            // the bottom)
            array<float> room = array.from((scHi - rTop) / scSpan, (rBot - scLo) / scSpan - ICON_PCT / 100, (scHi - lTop) / scSpan - LEGEND_PCT / 100, (lBot - scLo) / scSpan - LOGO_PCT / 100)
            float need = (nRows + 1) * (panelSize == "Small" ? 0.028 : 0.035)
            // The void labels sit at the left edge, under any left panel: a left corner where the panel does not fit above the
            // highest label (top) or under the lowest one (bottom) would cover a label, and it is not taken when no corner has
            // enough room
            bool lblTL = not na(lblTopY) and (scHi - (lblTopY + lblH / 2)) / scSpan - LEGEND_PCT / 100 < need
            bool lblBL = not na(lblBotY) and (lblBotY - lblH / 2 - scLo) / scSpan - LOGO_PCT / 100 < need
            array<bool> onLbl = array.from(false, false, lblTL, lblBL)
            int   pi   = panelPos == "Top Right" ? 0 : panelPos == "Bottom Right" ? 1 : panelPos == "Top Left" ? 2 : 3
            // Corners tried in order: the chosen one, the other one on the same side, then the other side
            array<int> tryOrd = array.from(pi, pi % 2 == 0 ? pi + 1 : pi - 1, (pi + 2) % 4, pi % 2 == 0 ? (pi + 3) % 4 : (pi + 1) % 4)
            int pick = -1
            int best = -1
            for k = 0 to 3
                int cn = tryOrd.get(k)
                if pick < 0 and room.get(cn) >= need
                    pick := cn
                if not onLbl.get(cn) and (best < 0 or room.get(cn) > room.get(best))
                    best := cn
            int cs = pick >= 0 ? pick : best >= 0 ? best : pi
            pos := cs == 0 ? position.top_right : cs == 1 ? position.bottom_right : cs == 2 ? position.top_left : position.bottom_left
 
        // Top left: an empty, transparent row above the panel keeps its first rows clear of the TradingView legend
        int r0 = pos == position.top_left and nRows < 9 ? 1 : 0
        if r0 == 1
            table.cell(panel, 0, 0, "", height = LEGEND_PCT)
            table.merge_cells(panel, 0, 0, 1, 0)
        table.cell(panel, 0, r0, "EDO LIQUIDITY VOIDS", text_color = textCol, bgcolor = bgHead, text_size = panSz)
        table.merge_cells(panel, 0, r0, 1, r0)
        int r = r0 + 1
        if noVol
            panelRow(panel, r, "State", "No volume · nothing calculated", warnCol, bgMain)
            r += 1
            panelRow(panel, r, "Why", "Voids need traded volume: use a future or an ETF", numTxt, bgMain)
            r += 1
        else
            string stTxt = "Outside the voids"
            color  stCol = textCol
            if iIn >= 0
                LvZone o = act.get(iIn)
                stTxt := full ? "Inside a void · " + fmt(o.bot) + "–" + fmt(o.top) + " · " + histName(o) + " · vol " + str.tostring(volPct(o), "0") + " %" : "Inside a void · " + histName(o)
                stCol := voidCol
            else if nBars < winLen and act.size() == 0
                stTxt := "Collecting bars · " + str.tostring(nBars) + " of " + str.tostring(winLen)
                stCol := warnCol
            panelRow(panel, r, "State", stTxt, stCol, bgMain)
            r += 1
            panelRow(panel, r, "Void above", voidRow(iUp, full), iUp >= 0 ? textCol : numTxt, bgMain)
            r += 1
            panelRow(panel, r, "Void below", voidRow(iDn, full), iDn >= 0 ? textCol : numTxt, bgMain)
            r += 1
            if full
                int nA = 0
                int nB = 0
                if act.size() > 0
                    for k = 0 to act.size() - 1
                        LvZone o = act.get(k)
                        nA += o.bot > close ? 1 : 0
                        nB += o.top < close ? 1 : 0
                panelRow(panel, r, "Tracked", str.tostring(act.size()) + " · " + str.tostring(nA) + " above · " + str.tostring(nB) + " below · " + str.tostring(nDrawn) + " drawn", textCol, bgMain)
                r += 1
                panelRow(panel, r, "Window", str.tostring(winLen) + " bars · " + str.tostring(rowsN) + " rows · thin < " + str.tostring(thrPct, "0") + " % · scan " + str.tostring(scanStep), numTxt, bgMain)
                r += 1
            string vTxt = isTick ? "Tick (FX / CFD) · low-activity zones" : zPct > 20 ? "Sparse · " + str.tostring(zPct, "0") + " % of bars without volume" : "Traded"
            if full or vWarn
                panelRow(panel, r, "Volume", vTxt, vWarn ? warnCol : textCol, bgMain)
                r += 1
            string evRow = lastEv == 0 ? "None yet" : evTxt(lastEv) + " · " + agoTxt(lastEvB)
            panelRow(panel, r, "Last event", evRow, evCol(lastEv), bgMain)
            r += 1
        table.cell(panel, 0, r, full ? "Closed bars · ATR 50 · context, not a signal" : "Closed bars · not a signal", text_color = numTxt, bgcolor = bgSub, text_size = panSz)
        table.merge_cells(panel, 0, r, 1, r)
 
        // Bottom corners: an empty, transparent row under the panel keeps its last row clear of the TradingView logo
        // (left) and of the round TradingView button (right). The outer frame is hidden whenever an empty row is kept
        // (top left or bottom) so it does not draw a box around it; the line between the cells closes the panel
        bool atBot = pos == position.bottom_left or pos == position.bottom_right
        if atBot and r < 9
            table.cell(panel, 0, r + 1, "", height = pos == position.bottom_left ? LOGO_PCT : ICON_PCT)
            table.merge_cells(panel, 0, r + 1, 1, r + 1)
        table.set_frame_width(panel, atBot or r0 == 1 ? 0 : 1)
        table.set_position(panel, pos)
 
// ================== MARKERS ==================
 
// Display only: a crossing triangle is skipped when another one was drawn less than Min Bars Between Crossing
// Markers before. The events, the panel and the alerts keep every crossing
var int lastMkB = na
bool mkUp = false
bool mkDn = false
if showMarks and (evCrossUp or evCrossDn) and (na(lastMkB) or bar_index - lastMkB >= markGap)
    mkUp    := evCrossUp
    mkDn    := evCrossDn
    lastMkB := bar_index
 
plotshape(mkUp, "Void crossed up", shape.triangleup, location.belowbar, bullCol, size = size.small)
plotshape(mkDn, "Void crossed down", shape.triangledown, location.abovebar, bearCol, size = size.small)
plotshape(showNewMk and (evNewUp or evNewDn or evNewIn), "New void", shape.diamond, location.abovebar, voidCol, size = size.tiny)
 
// ================== ALERTS ==================
 
alertcondition(evEnter,   "Entered a void",        "Edo Liquidity Voids — A bar closed inside a volume void on {{ticker}}")
alertcondition(evCrossUp, "Crossed a void up",     "Edo Liquidity Voids — A close went through a volume void from below to above on {{ticker}}")
alertcondition(evCrossDn, "Crossed a void down",   "Edo Liquidity Voids — A close went through a volume void from above to below on {{ticker}}")
alertcondition(evExitUp,  "Left a void upward",    "Edo Liquidity Voids — Price closed above a volume void after closing inside it on {{ticker}}")
alertcondition(evExitDn,  "Left a void downward",  "Edo Liquidity Voids — Price closed below a volume void after closing inside it on {{ticker}}")
alertcondition(evNewUp,   "New void above price",  "Edo Liquidity Voids — A new volume void was detected above the price on {{ticker}}")
alertcondition(evNewDn,   "New void below price",  "Edo Liquidity Voids — A new volume void was detected below the price on {{ticker}}")
alertcondition(evAbsorb,  "Void absorbed",         "Edo Liquidity Voids — Enough volume traded inside a void that it is no longer thin on {{ticker}}")

← 返回列表