Delta Profile XL

tgregg75 · study · 308 行 · 点赞 93 · TradingView 原页

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

Pine Script

//@version=6
indicator("Delta Profile XL", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_bars_back = 5000)
 
// ═══════════════════════════════ INPUTS ═══════════════════════════════
grpStyle = "🎛️ Style"
barStyle = input.string("Diverging", "Bar Style", options = ["Diverging", "One-Sided"], group = grpStyle, tooltip = "Diverging = rows grow right of a center axis when buying wins and left when selling wins, with the delta number just past each bar tip.\nOne-Sided = every row is a single bar growing from one baseline, colored by sign (green = net buying, red = net selling).")
diverging = barStyle == "Diverging"
 
grpCalc = "🧮 Calculation"
rows     = input.int(40, "Number of Rows", minval = 5, maxval = 100, group = grpCalc, tooltip = "Price is split into this many horizontal bins. Each row shows its net delta: buy volume minus sell volume. Fewer rows give taller bars and more readable numbers.")
ltfInput = input.timeframe("", "Intrabar Timeframe", group = grpCalc, tooltip = "Lower timeframe used to split each chart bar's volume into buying and selling. Leave blank for Auto: 1 minute on intraday charts, 5 minutes on daily charts, 60 minutes on weekly/monthly charts. Must be lower than or equal to the chart timeframe. Where intrabar data is unavailable (very old history, or a timeframe that is too high) the script falls back to the chart bar's own direction.")
 
grpProfile = "📊 Profile"
lookback     = input.int(200, "Lookback Bars", minval = 10, maxval = 5000, group = grpProfile, tooltip = "How many chart bars back the profile is built from. Also sets the price high/low range the profile spans.")
placement    = input.string("Right", "Placement", options = ["Right", "Left"], group = grpProfile, tooltip = "Which side of the latest candle the profile is drawn on. Right needs empty space to the right of the last candle: drag the chart left, or use a smaller Profile Width, so the bars are not hidden under the price scale.")
profileWidth = input.int(60, "Profile Width (bars)", minval = 10, maxval = 450, group = grpProfile, tooltip = "Total horizontal length, in bars, of the row with the largest absolute delta. In Diverging style this is split evenly on each side of the axis. Every other row scales proportionally.")
gap          = input.int(10, "Gap From Price (bars)", minval = 0, maxval = 40, group = grpProfile, tooltip = "Empty space, in bars, between the latest candle and the near edge of the profile.")
 
grpColor = "🎨 Colors & Lines"
posColor      = input.color(color.new(#26a69a, 20), "Buy Delta (Positive)", group = grpColor, tooltip = "Fill color for rows where buying volume exceeds selling volume.")
negColor      = input.color(color.new(#ef5350, 20), "Sell Delta (Negative)", group = grpColor, tooltip = "Fill color for rows where selling volume exceeds buying volume.")
showRowLabels = input.bool(true, "Show Delta Numbers In Bars", group = grpColor, tooltip = "Prints each row's net delta (buy minus sell volume) on its bar.")
rowLblSizeSel = input.string("Tiny", "Number Size", options = ["Tiny", "Small", "Normal"], group = grpColor, tooltip = "Text size of the delta numbers. Numbers use your chart's text color so they stay readable on light and dark themes.")
rowLblMinPct  = input.float(0, "Min Bar Size For Numbers (%)", minval = 0, maxval = 100, step = 5, group = grpColor, tooltip = "Hides the number on rows whose delta is below this percentage of the largest row. 0 labels every row. Raise it to clean up crowded profiles.")
numPosSel     = input.string("Bar Tip", "Number Position (One-Sided)", options = ["Bar Tip", "At Baseline"], group = grpColor, tooltip = "One-Sided style only. Bar Tip = the number sits just past the end of each bar (default). At Baseline = the number sits inside the bar at its start. Diverging style always puts numbers at the bar tips.")
numAtTip      = numPosSel == "Bar Tip"
showAxis      = input.bool(false, "Show Baseline / Axis", group = grpColor, tooltip = "Draws the zero-delta line the bars grow from (the center axis in Diverging style).")
axisColor     = input.color(color.new(color.gray, 30), "Baseline Color", group = grpColor, tooltip = "Color of the baseline / axis.")
showExtremes  = input.bool(true, "Show Max Buy / Max Sell Rows", group = grpColor, tooltip = "Draws a dashed line at the row with the largest positive delta (strongest net buying) and the row with the largest negative delta (strongest net selling).")
buyLineColor  = input.color(color.new(#00c853, 0), "Max Buy Color", group = grpColor, tooltip = "Line color for the strongest net-buying row.")
sellLineColor = input.color(color.new(#d50000, 0), "Max Sell Color", group = grpColor, tooltip = "Line color for the strongest net-selling row.")
extremeWidth  = input.int(1, "Max Row Line Width", minval = 1, maxval = 10, group = grpColor, tooltip = "Line thickness for the max buy and max sell rows.")
lblShow       = input.bool(true, "Show Net Delta Label", group = grpColor, tooltip = "Shows the profile's total delta and buy share above the profile.")
lblSizeSel    = input.string("Small", "Net Delta Label Size", options = ["Tiny", "Small", "Normal", "Large", "Huge"], group = grpColor, tooltip = "Text size of the net delta label.")
lblSize    = lblSizeSel == "Tiny" ? size.tiny : lblSizeSel == "Small" ? size.small : lblSizeSel == "Normal" ? size.normal : lblSizeSel == "Large" ? size.large : size.huge
rowLblSize = rowLblSizeSel == "Tiny" ? size.tiny : rowLblSizeSel == "Small" ? size.small : size.normal
 
grpTable = "📋 Stats Table"
showTable    = input.bool(true, "Show Stats Table", group = grpTable, tooltip = "Panel with total delta, buy/sell volume, buy share and the intrabar data source for the profile.")
tablePosSel  = input.string("Bottom Left", "Position", options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group = grpTable, tooltip = "Screen corner where the stats table is anchored. Bottom Left keeps it clear of a profile drawn on the right.")
tableSizeSel = input.string("Small", "Text Size", options = ["Tiny", "Small", "Normal"], group = grpTable, tooltip = "Font size used inside the stats table.")
tablePos  = tablePosSel == "Top Left" ? position.top_left : tablePosSel == "Top Right" ? position.top_right : tablePosSel == "Bottom Left" ? position.bottom_left : position.bottom_right
tableSize = tableSizeSel == "Tiny" ? size.tiny : tableSizeSel == "Normal" ? size.normal : size.small
 
// ═══════════════════════ SERIES (evaluated every bar) ═══════════════════════
rangeHigh = ta.highest(high, lookback)
rangeLow  = ta.lowest(low,  lookback)
halfWidth = math.max(1, int(profileWidth / 2))
 
// Intrabar timeframe: Auto picks 1m (intraday), 5m (daily), 60m (weekly/monthly); seconds charts use their own timeframe.
ltfAuto = timeframe.isseconds ? timeframe.period : timeframe.isintraday ? "1" : timeframe.isdaily ? "5" : "60"
ltf     = ltfInput == "" ? ltfAuto : ltfInput
ltfText = na(str.tonumber(ltf)) ? ltf : ltf + "m"
 
// ═══════════════════════ INTRABAR DATA STORE ═══════════════════════
// One element per intrabar (or one per chart bar when no intrabar data exists):
// high, low, volume, direction (+1 buy / -1 sell / 0 neutral), owning chart bar index,
// and a flag marking elements that fell back to the chart bar itself.
var array<float> sH = array.new<float>()
var array<float> sL = array.new<float>()
var array<float> sV = array.new<float>()
var array<int>   sD = array.new<int>()
var array<int>   sB = array.new<int>()
var array<int>   sF = array.new<int>()
 
// Pushes the current chart bar's intrabars into the store and returns how many elements were added.
// Direction: close above open is buying, below is selling. A flat intrabar compares its close with the
// previous intrabar's close (the first one uses the previous chart bar's close). Still flat = neutral.
f_collect(array<float> aO, array<float> aH, array<float> aL, array<float> aC, array<float> aV, float prevClose) =>
    int n = na(aV) ? 0 : array.size(aV)
    int added = 0
    if n > 0
        float pc = prevClose
        for k = 0 to n - 1 by 1
            float o_ = array.get(aO, k)
            float h_ = array.get(aH, k)
            float l_ = array.get(aL, k)
            float c_ = array.get(aC, k)
            float v_ = nz(array.get(aV, k))
            int dir_ = c_ > o_ ? 1 : c_ < o_ ? -1 : c_ > pc ? 1 : c_ < pc ? -1 : 0
            pc := c_
            if not na(h_) and not na(l_)
                array.push(sH, h_)
                array.push(sL, l_)
                array.push(sV, v_)
                array.push(sD, dir_)
                array.push(sB, bar_index)
                array.push(sF, 0)
                added += 1
    if added == 0
        int fdir = close > open ? 1 : close < open ? -1 : close > prevClose ? 1 : close < prevClose ? -1 : 0
        array.push(sH, high)
        array.push(sL, low)
        array.push(sV, nz(volume))
        array.push(sD, fdir)
        array.push(sB, bar_index)
        array.push(sF, 1)
        added := 1
    added
 
f_trim(int cap) =>
    while array.size(sH) > cap
        array.shift(sH)
        array.shift(sL)
        array.shift(sV)
        array.shift(sD)
        array.shift(sB)
        array.shift(sF)
 
// Spreads each element's volume across the rows its high-low range covers, into buy (up) or sell (dn).
// Only the rows an element actually touches are visited. Returns the number of fallback elements used.
f_accumulate(int fromIdx, int toIdx, float lo, float rowH, int nRows, array<float> up, array<float> dn) =>
    int fb = 0
    if toIdx >= fromIdx
        for i = fromIdx to toIdx by 1
            float bH = array.get(sH, i)
            float bL = array.get(sL, i)
            float bV = array.get(sV, i)
            int   bD = array.get(sD, i)
            fb += array.get(sF, i)
            if bD != 0 and bV > 0
                bool isUp = bD > 0
                float bRange = bH - bL
                if bRange <= 0
                    int idx = math.max(0, math.min(nRows - 1, int((bH - lo) / rowH)))
                    array.set(isUp ? up : dn, idx, array.get(isUp ? up : dn, idx) + bV)
                else
                    int r0 = math.max(0, int((bL - lo) / rowH))
                    int r1 = math.min(nRows - 1, int((bH - lo) / rowH))
                    for r = r0 to r1 by 1
                        float rLow = lo + r * rowH
                        float rHigh = rLow + rowH
                        float overlap = math.min(bH, rHigh) - math.max(bL, rLow)
                        if overlap > 0
                            array.set(isUp ? up : dn, r, array.get(isUp ? up : dn, r) + bV * overlap / bRange)
    fb
 
// Largest absolute row delta, the max-buy and max-sell row indexes, and the buy/sell totals.
f_delta_stats(array<float> up, array<float> dn, int nRows) =>
    float maxAbs = 0.0
    int   posIdx = -1
    int   negIdx = -1
    float posMax = 0.0
    float negMax = 0.0
    float totUp  = 0.0
    float totDn  = 0.0
    for r = 0 to nRows - 1 by 1
        float u = array.get(up, r)
        float s = array.get(dn, r)
        float dl = u - s
        totUp += u
        totDn += s
        maxAbs := math.max(maxAbs, math.abs(dl))
        if dl > posMax
            posMax := dl
            posIdx := r
        if dl < negMax
            negMax := dl
            negIdx := r
    [maxAbs, posIdx, negIdx, totUp, totDn]
 
f_delta_text(float u, float s) =>
    float dl  = u - s
    float tot = u + s
    float bp  = tot > 0 ? u / tot * 100 : 50.0
    "Δ " + (dl >= 0 ? "+" : "") + str.tostring(dl, format.volume) + "  |  Buy " + str.tostring(bp, "#") + "%"
 
// ═══════════════════════ PERSISTENT DRAWING STORAGE ═══════════════════════
var array<box>   cBoxes = array.new<box>()
var array<line>  cLines = array.new<line>()
var array<label> cLbls  = array.new<label>()
 
wipeProfile() =>
    for b in cBoxes
        box.delete(b)
    for l in cLines
        line.delete(l)
    for lb in cLbls
        label.delete(lb)
    array.clear(cBoxes)
    array.clear(cLines)
    array.clear(cLbls)
 
// Stats shown in the table.
var float  stUp    = 0.0
var float  stDn    = 0.0
var int    stFb    = 0
var int    stBars  = 1
var string stScope = ""
var table  statTable = na
 
// ═══════════════════════ INTRABAR REQUEST + COLLECTION ═══════════════════════
// ignore_invalid_timeframe = true returns na instead of halting when the timeframe is not usable.
[ltfO, ltfH, ltfL, ltfC, ltfV] = request.security_lower_tf(syminfo.tickerid, ltf, [open, high, low, close, volume], ignore_invalid_timeframe = true)
float prevCloseG = nz(close[1], open)
 
// Only the bars the profile can use are stored.
int  needBars = lookback + 2
bool inWindow = bar_index >= last_bar_index - needBars
 
// Confirmed bars are stored permanently.
if inWindow and barstate.isconfirmed
    f_collect(ltfO, ltfH, ltfL, ltfC, ltfV, prevCloseG)
    f_trim(90000)
 
// The still-forming realtime bar is appended temporarily, drawn, then removed (see cleanup at the end).
int liveAdded = 0
if barstate.islast and not barstate.isconfirmed
    liveAdded := f_collect(ltfO, ltfH, ltfL, ltfC, ltfV, prevCloseG)
 
// ═══════════════════════════════ PROFILE ═══════════════════════════════
if barstate.islast
    wipeProfile()
    if rangeHigh > rangeLow
        float rowH = (rangeHigh - rangeLow) / rows
        array<float> upV = array.new<float>(rows, 0.0)
        array<float> dnV = array.new<float>(rows, 0.0)
 
        int nElem   = array.size(sB)
        int fromIdx = nElem
        while fromIdx > 0 and array.get(sB, fromIdx - 1) > bar_index - lookback
            fromIdx -= 1
        int fb = f_accumulate(fromIdx, nElem - 1, rangeLow, rowH, rows, upV, dnV)
        [maxAbs, posIdx, negIdx, totUp, totDn] = f_delta_stats(upV, dnV, rows)
 
        stUp    := totUp
        stDn    := totDn
        stFb    := fb
        stBars  := math.max(1, math.min(lookback, bar_index + 1))
        stScope := str.tostring(lookback) + " bars"
 
        if maxAbs > 0
            bool isRight = placement == "Right"
            int anchor = bar_index
            // Horizontal layout: the whole profile spans spanL..spanR. One-Sided bars grow from baseX;
            // Diverging bars grow either side of axisX.
            int spanL  = isRight ? anchor + gap : anchor - gap - profileWidth
            int spanR  = spanL + profileWidth
            int axisX  = spanL + halfWidth
            int baseX  = isRight ? spanR : spanL
            int scaleW = diverging ? halfWidth : profileWidth
            for r = 0 to rows - 1 by 1
                float rLow  = rangeLow + r * rowH
                float rHigh = rLow + rowH
                float dl = array.get(upV, r) - array.get(dnV, r)
                if dl != 0
                    int w   = math.max(1, int(math.round(math.abs(dl) / maxAbs * scaleW)))
                    int bx1 = diverging ? (dl > 0 ? axisX : axisX - w) : (isRight ? baseX - w : baseX)
                    int bx2 = diverging ? (dl > 0 ? axisX + w : axisX) : (isRight ? baseX : baseX + w)
                    array.push(cBoxes, box.new(bx1, rHigh, bx2, rLow, xloc = xloc.bar_index, border_width = 0, bgcolor = dl > 0 ? posColor : negColor))
                    if showRowLabels and math.abs(dl) >= maxAbs * rowLblMinPct / 100
                        // Diverging: number past the bar tip. One-Sided: past the tip (Bar Tip) or inside at the baseline.
                        // lblLeftOfX = the number's box extends to the left of its anchor point.
                        bool lblLeftOfX = diverging ? dl < 0 : isRight
                        int lx = diverging ? (dl > 0 ? bx2 : bx1) : numAtTip ? (isRight ? bx1 : bx2) : baseX
                        string lst = lblLeftOfX ? label.style_label_right : label.style_label_left
                        array.push(cLbls, label.new(lx, rLow + rowH / 2, str.tostring(dl, format.volume), xloc = xloc.bar_index, style = lst, color = color(na), textcolor = chart.fg_color, size = rowLblSize))
            if showAxis
                int lineX = diverging ? axisX : baseX
                array.push(cLines, line.new(lineX, rangeLow, lineX, rangeHigh, xloc = xloc.bar_index, color = axisColor, width = 1, style = line.style_dotted))
            if showExtremes
                if posIdx >= 0
                    float py = rangeLow + posIdx * rowH + rowH / 2
                    array.push(cLines, line.new(spanL, py, spanR, py, xloc = xloc.bar_index, color = buyLineColor, width = extremeWidth, style = line.style_dashed))
                if negIdx >= 0
                    float ny = rangeLow + negIdx * rowH + rowH / 2
                    array.push(cLines, line.new(spanL, ny, spanR, ny, xloc = xloc.bar_index, color = sellLineColor, width = extremeWidth, style = line.style_dashed))
            if lblShow
                array.push(cLbls, label.new(axisX, rangeHigh, f_delta_text(totUp, totDn), xloc = xloc.bar_index, style = label.style_label_down, color = color.new(color.gray, 15), textcolor = color.white, size = lblSize))
 
// ═══════════════════════════════ STATS TABLE ═══════════════════════════════
if barstate.islast and showTable
    if na(statTable)
        statTable := table.new(position = tablePos, columns = 2, rows = 8, bgcolor = color.new(color.black, 10), frame_color = color.gray, frame_width = 1, border_color = color.gray, border_width = 1)
        table.merge_cells(statTable, 0, 0, 1, 0)
    float stDelta = stUp - stDn
    float stTot   = stUp + stDn
    string covText = stFb == 0 ? "Intrabar" : stFb >= stBars ? "Chart bars only" : "Partial (" + str.tostring(math.round((1 - stFb / stBars) * 100)) + "%)"
    table.cell(statTable, 0, 0, "Delta Profile XL", text_color = color.white, text_size = tableSize, bgcolor = color.new(color.blue, 55), text_halign = text.align_center)
    table.cell(statTable, 0, 1, "Window",     text_color = color.silver, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 1, 1, stScope,       text_color = color.white,  text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 0, 2, "Intrabar TF", text_color = color.silver, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 1, 2, ltfText,       text_color = color.white,  text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 0, 3, "Delta",       text_color = color.silver, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 1, 3, (stDelta >= 0 ? "+" : "") + str.tostring(stDelta, format.volume), text_color = stDelta >= 0 ? color.teal : color.red, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 0, 4, "Buy Volume",  text_color = color.silver, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 1, 4, str.tostring(stUp, format.volume), text_color = color.white, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 0, 5, "Sell Volume", text_color = color.silver, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 1, 5, str.tostring(stDn, format.volume), text_color = color.white, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 0, 6, "Buy Share",   text_color = color.silver, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 1, 6, stTot > 0 ? str.tostring(stUp / stTot * 100, "#") + "%" : "--", text_color = color.white, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 0, 7, "Data",        text_color = color.silver, text_size = tableSize, bgcolor = color.new(color.black, 10))
    table.cell(statTable, 1, 7, covText,       text_color = color.white,  text_size = tableSize, bgcolor = color.new(color.black, 10))
else if barstate.islast
    if not na(statTable)
        table.delete(statTable)
        statTable := na
 
// ═══════════════════════════════ CLEANUP ═══════════════════════════════
// Remove the temporary realtime-bar elements so the store only ever holds confirmed bars.
if liveAdded > 0
    for k = 1 to liveAdded by 1
        array.pop(sH)
        array.pop(sL)
        array.pop(sV)
        array.pop(sD)
        array.pop(sB)
        array.pop(sF)

← 返回列表