Delta Flow Candles [JOAT]

officialjackofalltrades · study · 691 行 · 点赞 72 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © officialjackofalltrades
//@version=6
indicator("Delta Flow Candles [JOAT]", "Delta Flow Candles [JOAT]", overlay = true,
     max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, behind_chart = false)   // candles must draw IN FRONT of the chart's own candles (v6 default is behind)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 0. SAFETY
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
max_bars_back(time, 5000)
// Scale anchor: a script that only draws boxes / lines / labels can land on its own price scale on a customer's
// chart. One invisible plot pins it to the price scale. display.pane keeps it out of the status line and data window.
plot(close, "Scale anchor (invisible)", color = color.new(#000000, 100), display = display.pane, editable = false)
 
float atrK = ta.atr(14)          // shared ATR for tag padding and lane gaps
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 7. DELTA INPUTS (declared first so they lead the Settings dialog; the kit blocks follow)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G0 = "Delta candles"
string candleMode = input.string("Delta", "Candle mode", options = ["Delta", "Volume", "Off"], group = G0,
     tooltip = "Delta = each candle coloured by its delta score: bull colour when buying controlled the bar, bear colour when selling did, grey when it was balanced; quiet bars fade. Volume = the candle's own direction (close vs open) in the bull / bear colour with the brightness set by relative volume only (no delta). Off = no candles drawn (tags, dashboard and alerts keep working). Hide TradingView's own candles (Chart settings > Symbol > untick Body, Borders and Wick) or both sets draw on top of each other.")
bool   useLtf     = input.bool(false, "Intrabar delta (1m)", group = G0,
     tooltip = "Off (default) = the chart-bar proxy: the close position in the bar's range blended with the body direction, no request calls. On = the bar's volume is split from its lower-timeframe bars (1m on charts below 1H, 5m on 1H-4H, 15m on 4H-1D, 30m on daily, 4H on weekly and above; never below 1 minute because free accounts have no seconds data). Each intrabar is split by the same close-position rule and the parts are summed. Bars with no intrabar data (older history, 1m charts, symbols without volume) fall back to the proxy. Intrabar deltas usually run smaller than the proxy, so they have their own colour and strong-bar thresholds below.")
float  closeW     = input.float(0.7, "Close-position weight", minval = 0.0, maxval = 1.0, step = 0.05, group = G0,
     tooltip = "How the split is made. 1.0 = purely by where the close sits in the high-low range (close on the high = all buying). 0.0 = purely by the body direction (green body = all buying). 0.7 leans on the close position and lets the body break ties.")
int    fullPx     = input.int(70, "Full colour at |delta| % (proxy / intrabar)", minval = 10, maxval = 100, group = G0, inline = "fc")
int    fullLtf    = input.int(35, "", minval = 5, maxval = 100, group = G0, inline = "fc",
     tooltip = "The |delta| at which a candle reaches the brightest bull or hottest bear colour. The plain theme colour is reached at three quarters of it, and a bar under ~12 % of it stays grey. First value for the chart proxy, second for intrabar delta.")
int    volLen     = input.int(20, "Volume average length", minval = 2, maxval = 500, group = G0,
     tooltip = "Relative volume = this bar's volume / the simple average of the last N bars. Used by the quiet-bar fade, the Volume mode, the strong-bar test and the dashboard.")
bool   fadeQuiet  = input.bool(true, "Fade quiet bars / full colour at (x avg volume)", group = G0, inline = "fq")
float  satAt      = input.float(1.0, "", minval = 0.4, maxval = 5.0, step = 0.1, group = G0, inline = "fq",
     tooltip = "Delta mode: a bar's colour saturation also follows its relative volume. At or above this multiple of the average volume the colour is full; below it the candle fades toward a soft grey, completely at 0.25x. Symbols without volume never fade.")
float  volFull    = input.float(2.0, "Volume mode: full colour at (x avg volume)", minval = 1.0, maxval = 6.0, step = 0.1, group = G0,
     tooltip = "Volume mode only: candles at 0.5x average volume or less are grey, the plain theme colour is reached at three quarters of the way to this multiple, and the brightest colour at it.")
 
string G0t = "Delta tags"
bool   showTags   = input.bool(true, "Delta % tags on strong bars / size", group = G0t, inline = "tg")
string tagSizeS   = input.string("Small", "", options = ["Small", "Normal", "Large"], group = G0t, inline = "tg",
     tooltip = "A short tag (\"+62 %\") on every closed bar whose delta AND relative volume both pass the two tests below: above the wick when buying led, below it when selling led. Hover a tag for the buy / sell share and the volume. Tags are moved further away from price when a nearby tag already holds the slot, and only the newest ones are kept (Limits).")
int    strongPx   = input.int(50, "Strong bar: |delta| % at least (proxy / intrabar)", minval = 5, maxval = 100, group = G0t, inline = "sd")
int    strongLtf  = input.int(25, "", minval = 5, maxval = 100, group = G0t, inline = "sd",
     tooltip = "First value for the chart proxy, second for intrabar delta. Together with the relative-volume test this defines a strong bar: it gets a tag, it counts in the dashboard's strong-bar row and it can fire an alert.")
float  strongRv   = input.float(1.8, "Strong bar: relative volume at least", minval = 0.5, maxval = 10.0, step = 0.1, group = G0t,
     tooltip = "The bar's volume as a multiple of the average volume. 1.8 = at least 80 % more volume than usual. Symbols without volume have no strong bars.")
float  tagGapAtr  = input.float(0.6, "Tag spacing (ATR)", minval = 0.1, maxval = 3.0, step = 0.1, group = G0t,
     tooltip = "Minimum vertical gap between two tags within 6 bars of each other, in ATR(14). The script also uses at least 1/38 of the recent price span, so tags stay apart on symbols whose price scale spans thousands of points.")
bool   showSess   = input.bool(true, "Session delta tag at the right edge", group = G0t,
     tooltip = "One tag right of the last bar with the delta of the current session (daily charts: week, weekly: month, monthly: year) and its buy share, the same numbers as the dashboard row.")
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 1. THEME
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G1 = "Theme"
string theme  = input.string("Delta Cyan / Pink", "Theme", group = G1,
     options = ["JOAT Signature", "Midnight Blue / Red", "Aurora Night", "Delta Cyan / Pink", "Paper & Ink", "Lime Ember", "Custom"],
     tooltip = "Named presets. Delta Cyan / Pink is the delta-map pair; JOAT Signature is the brand pair. Paper & Ink is the clean black / white preset: buying-led candles are solid ink, selling-led candles are hollow. Custom uses the colour pickers below.")
int    bright = input.int(3, "Brightness", minval = 1, maxval = 5, group = G1,
     tooltip = "1 = faint, 3 = as designed, 5 = vivid. Scales every fill and glow transparency; solid lines and plates stay solid.")
string bgMode = input.string("Auto", "Chart background", options = ["Auto", "Dark", "Light"], group = G1,
     tooltip = "Auto reads the luminance of the chart background and swaps every role so it stays readable on a white chart.")
color  inBull  = input.color(#5CF0D7, "Custom bull / bear",     group = G1, inline = "c1")
color  inBear  = input.color(#B32AC3, "",                       group = G1, inline = "c1")
color  inAcc   = input.color(#FFFFFF, "Custom accent / neutral", group = G1, inline = "c2")
color  inNeu   = input.color(#787B86, "",                       group = G1, inline = "c2")
color  inTxt   = input.color(#D1D4DC, "Custom text / panel",    group = G1, inline = "c3")
color  inPanel = input.color(#0E1116, "",                       group = G1, inline = "c3")
color  inGlow  = input.color(#5CF0D7, "Custom glow",            group = G1, inline = "c4")
 
// f_lum: relative luminance 0..1 of any colour (Rec. 601 weights). Used for light / dark awareness and plate ink.
f_lum(color c) =>
    (0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)) / 255.0
 
bool isLight = bgMode == "Light" ? true : bgMode == "Dark" ? false : f_lum(chart.bg_color) > 0.5
bool isMono  = theme == "Paper & Ink"
 
// Roles, resolved once. Defaults = JOAT Signature. Each preset overrides every role, with the white-chart swap.
color cBull   = isLight ? #12B5A0 : #5CF0D7
color cBear   = isLight ? #8E1FA0 : #B32AC3
color cAcc    = isLight ? #131722 : #FFFFFF
color cNeu    = #787B86
color cTxt    = isLight ? #131722 : #D1D4DC
color cPanel  = isLight ? #FFFFFF : #0E1116
color cGlow   = isLight ? #12B5A0 : #5CF0D7
color cCandle = cAcc                       // colour for the "Mono" candle paint (white bodies on black, ink on white)
if theme == "Midnight Blue / Red"
    cBull   := #2962FF
    cBear   := #F23645
    cAcc    := isLight ? #131722 : #FFFFFF
    cNeu    := #787B86
    cTxt    := isLight ? #131722 : #D1D4DC
    cPanel  := isLight ? #FFFFFF : #0B0F13
    cGlow   := #2962FF
    cCandle := cAcc
else if theme == "Aurora Night"
    cBull   := isLight ? #00A86B : #00E676
    cBear   := isLight ? #C2185B : #E040FB
    cAcc    := isLight ? #B59A00 : #FDD835
    cNeu    := #5C6BC0
    cTxt    := isLight ? #1A1F2E : #E6F1FF
    cPanel  := isLight ? #F4F6FB : #0A0E17
    cGlow   := isLight ? #0097A7 : #00BCD4   // the outer aurora hue (cyan); bear outer is #7C4DFF
    cCandle := cNeu
else if theme == "Delta Cyan / Pink"
    cBull   := isLight ? #0097A7 : #00E5FF
    cBear   := isLight ? #D81B60 : #FF2E88
    cAcc    := isLight ? #B59A00 : #FFD600
    cNeu    := #6B7280
    cTxt    := isLight ? #111827 : #F8FAFC
    cPanel  := isLight ? #FFFFFF : #111827
    cGlow   := isLight ? #0097A7 : #00E5FF
    cCandle := cNeu
else if theme == "Paper & Ink"
    color ink = isLight ? #111827 : #F0F3FA
    cBull   := ink
    cBear   := ink                            // same ink; bear objects carry direction by DASHED style (kBearStyle)
    cAcc    := #2962FF                        // the one accent: "live / nearest"; #F23645 is reserved for "broken"
    cNeu    := #B2B5BE
    cTxt    := ink
    cPanel  := isLight ? #FFFFFF : #131722
    cGlow   := #2962FF
    cCandle := ink
else if theme == "Lime Ember"
    cBull   := isLight ? #64DD17 : #B2FF59    // below-price liquidity
    cBear   := isLight ? #2962FF : #448AFF    // above-price liquidity
    cAcc    := #FF9800                        // ember: POC / peak row
    cNeu    := #787B86
    cTxt    := isLight ? #131722 : #E0E0E0
    cPanel  := isLight ? #FFFFFF : #161A25
    cGlow   := #FF9800
    cCandle := cNeu
else if theme == "Custom"
    cBull   := inBull
    cBear   := inBear
    cAcc    := inAcc
    cNeu    := inNeu
    cTxt    := inTxt
    cPanel  := inPanel
    cGlow   := inGlow
    cCandle := inAcc
 
color  cBroken   = #F23645                                            // grey-or-red for dead things; Paper & Ink "broken"
string kBearStyle = isMono ? line.style_dashed : line.style_solid    // Paper & Ink: direction by style, not hue
int    kPanelT    = isLight ? 8 : 15                                  // panel alpha: 92 % on white, 85 % on dark
 
// f_t: brightness-aware transparency. Scales the OPACITY (100 - t) by 0.5x .. 1.5x so faint things stay faint
// and solid things stay solid; fills (t >= 40) get +4 on a white chart and are floored at 92 in Paper & Ink.
f_t(int t) =>
    float op = 100.0 - t
    float k  = 1.0 + (bright - 3) * 0.25
    float tt = 100.0 - op * k
    if t >= 40
        if isMono
            tt := math.max(tt, 92.0)
        if isLight
            tt += 4.0
    math.min(100, math.max(0, math.round(tt)))
 
// f_ink: black or white text for a solid plate of colour c, by luminance.
f_ink(color c) =>
    f_lum(c) > 0.55 ? #0B0F13 : #FFFFFF
 
// f_grad: 3-stop gradient c1 (t = 0) -> c2 (t = 0.5) -> c3 (t = 1).
f_grad(color c1, color c2, color c3, float t) =>
    float tt = math.min(1.0, math.max(0.0, nz(t, 0.5)))
    tt < 0.5 ? color.from_gradient(tt, 0.0, 0.5, c1, c2) : color.from_gradient(tt, 0.5, 1.0, c2, c3)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 4a. LAYOUT — clamps (defined early because the glow and text helpers use them)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_xo: a drawing anchored further back than ~5,000 bars kills the script on a LIVE bar (RE10143) and a Basic
// account only has 5,000 bars anyway. f_xr: nothing may be drawn more than 500 bars ahead.
f_xo(int b) =>
    math.max(b, bar_index - 4990)
f_xr(int b) =>
    math.min(b, bar_index + 490)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 2. GLOW
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_glowBox: N concentric boxes. Halo h (1..layers-1) is padded h * 0.05 ATR outward and fades toward 97;
// the last element of the returned array is the CORE box (fill baseT, 1-px border). Keep the array so the
// retirement helpers can delete all layers together.
f_glowBox(int x1, float top, int x2, float bot, color c, int layers, int baseT) =>
    array<box> out = array.new<box>()
    int   xl  = f_xo(math.min(x1, x2))
    int   xr  = f_xr(math.max(x1, x2))
    float hi  = math.max(top, bot)
    float lo  = math.min(top, bot)
    float pad = nz(atrK, (hi - lo) * 0.2) * 0.05
    int   n   = math.max(1, layers)
    if n > 1
        for i = 1 to n - 1
            int h  = n - i                                        // outermost first so the core draws on top
            int tH = f_t(math.min(99, baseT + math.round(float(97 - baseT) * h / n)))
            array.push(out, box.new(xl, hi + pad * h, xr, lo - pad * h,
                 border_color = color.new(c, 100), border_width = 1, bgcolor = color.new(c, tH)))
    array.push(out, box.new(xl, hi, xr, lo,
         border_color = color.new(c, f_t(math.max(0, baseT - 50))), border_width = 1, bgcolor = color.new(c, f_t(baseT))))
    out
 
// f_glowLine: a solid core line of `width` with layers-1 wider, fainter halos beneath it. Last element = core.
f_glowLine(int x1, float y1, int x2, float y2, color c, int layers, int width) =>
    array<line> out = array.new<line>()
    int xl = f_xo(x1)
    int xr = f_xr(x2)
    int n  = math.max(1, layers)
    if n > 1
        for i = 1 to n - 1
            int h  = n - i
            int tH = f_t(math.min(99, 70 + math.round(27.0 * h / n)))
            array.push(out, line.new(xl, y1, xr, y2, color = color.new(c, tH), width = math.max(1, width + 2 * h)))
    array.push(out, line.new(xl, y1, xr, y2, color = color.new(c, f_t(0)), width = math.max(1, width)))
    out
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 3. TEXT
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_plate: label on a SOLID plate of colour c, text in f_ink(c). sty = label.style_*, sz = size.*
f_plate(int x, float y, string txt, color c, string sty, string sz) =>
    label.new(f_xr(f_xo(x)), y, txt, xloc = xloc.bar_index, yloc = yloc.price, color = c, style = sty,
         textcolor = f_ink(c), size = sz)
 
// f_tag: plateless text (transparent background, coloured text). Evolves f_tag of [JOAT] Fibonacci Vault.
f_tag(int x, float y, string txt, color c, string sty, string sz) =>
    label.new(f_xr(f_xo(x)), y, txt, xloc = xloc.bar_index, yloc = yloc.price, color = color.new(#000000, 100),
         style = sty, textcolor = c, size = sz)
 
// f_px: price with thousands separators at mintick precision: 24,550.25  /  1.08432  /  —
f_px(float p) =>
    string out = "—"
    if not na(p)
        string s = str.tostring(math.abs(p), format.mintick)
        array<string> parts = str.split(s, ".")
        string ip = array.get(parts, 0)
        string fp = ""
        if array.size(parts) > 1
            fp := "." + array.get(parts, 1)
        string g = ""
        int n = str.length(ip)
        if n > 0
            for i = 0 to n - 1
                g += str.substring(ip, i, i + 1)
                int rem = n - 1 - i
                if rem > 0 and rem % 3 == 0
                    g += ","
        out := (p < 0 ? "-" : "") + g + fp
    out
 
// f_k: compact numbers: 1.2K  3.4M  2.1B  (below 1,000: up to two decimals)
f_k(float v) =>
    string out = "—"
    if not na(v)
        float  a   = math.abs(v)
        string sgn = v < 0 ? "-" : ""
        if a >= 1e9
            out := sgn + str.tostring(a / 1e9, "#.#") + "B"
        else if a >= 1e6
            out := sgn + str.tostring(a / 1e6, "#.#") + "M"
        else if a >= 1e3
            out := sgn + str.tostring(a / 1e3, "#.#") + "K"
        else
            out := sgn + str.tostring(a, "#.##")
    out
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 4b. LAYOUT — label lane de-collision + object retirement
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// Lane register: every right-edge label asks f_lane for a y. The register is cleared at the start of each
// last-bar redraw (f_laneReset) so the slots are recomputed from scratch every tick.
var array<float> laneReg = array.new<float>()
 
f_laneReset() =>
    array.clear(laneReg)
 
// f_lane: returns the nearest free y to `y`, trying y, y - gap, y + gap, y - 2gap, y + 2gap ... (gap = ATR mult)
f_lane(float y, float gapAtrMult) =>
    float gap = math.max(nz(atrK) * gapAtrMult, syminfo.mintick * 2)
    float out = y
    for k = 0 to 24
        float off  = math.ceil(k / 2.0) * gap
        float cand = k % 2 == 0 ? y + off : y - off
        bool  free = true
        for r in laneReg
            if math.abs(r - cand) < gap * 0.999
                free := false
        if free
            out := cand
            break
    array.push(laneReg, out)
    out
 
// Retirement: push every new object into one array per kind, then cap it. Oldest leaves first (array.shift).
// This script draws labels only (delta tags + one session tag), so only the label cap is an input.
string G3 = "Limits (free account)"
int maxLabels = input.int(12, "Max delta tags kept", minval = 1, maxval = 50, group = G3,
     tooltip = "Only the newest strong-bar tags stay on the chart; older ones are deleted first, so history never litters. Tags older than 4,990 bars are also removed (free accounts load about 5,000 bars).")
 
f_capBoxes(array<box> a, int maxN) =>
    while array.size(a) > math.max(0, maxN)
        box.delete(array.shift(a))
f_capLines(array<line> a, int maxN) =>
    while array.size(a) > math.max(0, maxN)
        line.delete(array.shift(a))
f_capLabels(array<label> a, int maxN) =>
    while array.size(a) > math.max(0, maxN)
        label.delete(array.shift(a))
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 5. DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string G2 = "Dashboard"
bool   showDash    = input.bool(true, "Show dashboard", group = G2)
string dashPos     = input.string("Top Right", "Dashboard position", group = G2,
     options = ["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"])
string dashSize    = input.string("Small", "Dashboard size", options = ["Tiny", "Small", "Normal", "Large"], group = G2)
bool   dashCompact = input.bool(false, "Compact dashboard", group = G2, tooltip = "Fewer rows for phones: header, the session delta row and the Read line.")
bool   dashTint    = input.bool(true, "Tinted value cells", group = G2, tooltip = "Value cells carry a faint tint of their own colour.")
 
f_pos(string s) =>
    switch s
        "Top Left"      => position.top_left
        "Top Center"    => position.top_center
        "Top Right"     => position.top_right
        "Middle Left"   => position.middle_left
        "Middle Center" => position.middle_center
        "Middle Right"  => position.middle_right
        "Bottom Left"   => position.bottom_left
        "Bottom Center" => position.bottom_center
        => position.bottom_right
 
f_size(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Small"  => size.small
        "Normal" => size.normal
        "Large"  => size.large
        => size.small
 
// f_dashNew: panel in cPanel at the theme alpha, 1-px neutral frame. Rows = header + data rows + Read line.
f_dashNew(string pos, int cols, int rows) =>
    table.new(f_pos(pos), cols, rows, bgcolor = color.new(cPanel, kPanelT), frame_color = color.new(cNeu, 40),
         frame_width = 1, border_color = color.new(cNeu, 78), border_width = 1)
 
int dashRows = dashCompact ? 3 : 7                 // header + 5 rows + Read
var table dash = f_dashNew(dashPos, 2, dashRows)
var array<int> dCur    = array.from(0)     // row cursor (arrays are the only globals a function may mutate)
var array<int> dMerged = array.from(-1)    // row already merged for the Read line
 
// f_dBegin: clear and rewind; call once per last-bar redraw before f_dHead.
f_dBegin() =>
    table.clear(dash, 0, 0, 1, dashRows - 1)
    array.set(dCur, 0, 0)
 
// f_dHead: title band (bold, glow tint) with symbol · timeframe on the right.
f_dHead(string title) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        table.cell(dash, 0, r, " " + title + " ", text_color = cTxt, text_halign = text.align_left, text_size = f_size(dashSize),
             bgcolor = color.new(cGlow, isLight ? 80 : 70), text_formatting = text.format_bold)
        table.cell(dash, 1, r, syminfo.ticker + " · " + timeframe.period + " ", text_color = cTxt, text_halign = text.align_right,
             text_size = f_size(dashSize), bgcolor = color.new(cGlow, isLight ? 88 : 80))
        array.set(dCur, 0, r + 1)
 
// f_dRow: name | value, value text in valueColor with an optional tint cell (evolves the 51-series f_row / f_pill).
f_dRow(string name, string value, color valueColor, string tip) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        table.cell(dash, 0, r, " " + name, text_color = color.new(cTxt, 25), text_halign = text.align_left,
             text_size = f_size(dashSize), tooltip = tip)
        table.cell(dash, 1, r, value + " ", text_color = valueColor, text_halign = text.align_right, text_size = f_size(dashSize),
             bgcolor = dashTint ? color.new(valueColor, isLight ? 90 : 86) : color.new(cPanel, 100), tooltip = tip)
        array.set(dCur, 0, r + 1)
 
// f_dRead: the one-line "Read" sentence, merged across both columns, italic. Always the last row.
f_dRead(string txt) =>
    int r = array.get(dCur, 0)
    if r < dashRows
        if array.get(dMerged, 0) != r
            table.merge_cells(dash, 0, r, 1, r)
            array.set(dMerged, 0, r)
        table.cell(dash, 0, r, " " + txt + " ", text_color = cTxt, text_halign = text.align_left, text_size = f_size(dashSize),
             text_formatting = text.format_italic)
        array.set(dCur, 0, r + 1)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 6. CANDLES — the kit's barcolor() paint is replaced by this script's own plotcandle engine (section 10), driven
// by the "Candle mode" input above; a second candle input would only fight it. Colour helpers for that engine:
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// f_mix: blend colour a toward b by w (0 = a, 1 = b), keeping a's transparency.
f_mix(color a, color b, float w) =>
    color.rgb(color.r(a) + (color.r(b) - color.r(a)) * w, color.g(a) + (color.g(b) - color.g(a)) * w,
         color.b(a) + (color.b(b) - color.b(a)) * w, color.t(a))
 
// f_sat: push a colour away from its own grey (k > 1 = more saturated), channels clamped 0-255.
f_sat(color c, float k) =>
    float L = 0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)
    color.rgb(math.min(255, math.max(0, L + (color.r(c) - L) * k)), math.min(255, math.max(0, L + (color.g(c) - L) * k)),
         math.min(255, math.max(0, L + (color.b(c) - L) * k)), 0)
 
// Peak colours: strong buying = bright bull, strong selling = hot bear. On a white chart "stronger" means deeper.
color cHotBull = isMono ? cBull : isLight ? f_mix(cBull, #000000, 0.22) : f_mix(f_sat(cBull, 1.25), #FFFFFF, 0.22)
color cHotBear = isMono ? cBear : isLight ? f_mix(f_sat(cBear, 1.3), #000000, 0.15) : f_sat(cBear, 1.35)
 
// f_ramp: strength a (0..1) on side s (+1 buying, -1 selling, 0 none): grey -> theme colour (a = 0.75) -> peak (a = 1).
f_ramp(float a, int s) =>
    color base = s > 0 ? cBull : cBear
    color hot  = s > 0 ? cHotBull : cHotBear
    s == 0 ? cNeu : a < 0.75 ? color.from_gradient(a, 0.12, 0.75, cNeu, base) : color.from_gradient(a, 0.75, 1.0, base, hot)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 8. DELTA ENGINE
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// Volume guard (evolves Volume Delta Pressure [JOAT] 132-140): forex / index symbols without volume still get a
// delta score from the close position, but no relative volume, no fade and no strong bars.
float vol        = nz(volume)
bool  barHasVol  = not na(volume) and volume > 0.0
var bool anyVol  = false
if barHasVol
    anyVol := true
 
// f_buyFrac: share of a bar's volume credited to buyers: close position in the range blended with body direction
// (evolves the range / body proxy of Volume Delta Pressure [JOAT] 180-188).
f_buyFrac(float o, float h, float l, float c) =>
    float rng = h - l
    float cf  = rng > 0.0 ? (c - l) / rng : 0.5
    float df  = c > o ? 1.0 : c < o ? 0.0 : 0.5
    math.max(0.0, math.min(1.0, cf * closeW + df * (1.0 - closeW)))
 
// f_split: [buy volume, sell volume] of the bar it runs on; evaluated on each intrabar by request.security_lower_tf.
f_split() =>
    float v  = nz(volume)
    float bf = f_buyFrac(open, high, low, close)
    [v * bf, v * (1.0 - bf)]
 
// f_autoLTF (evolves Volume Delta Pressure [JOAT] 111-113): the intrabar timeframe, never below 1 minute.
f_autoLTF() =>
    int s = timeframe.in_seconds(timeframe.period)
    s >= 604800 ? "240" : s >= 86400 ? "30" : s >= 14400 ? "15" : s >= 3600 ? "5" : "1"
 
int    tfSec      = timeframe.in_seconds(timeframe.period)
bool   ltfAllowed = tfSec > 60                     // a 1m (or seconds) chart has no 1-minute intrabars to split
string ltfTf      = f_autoLTF()
string ltfName    = ltfTf == "240" ? "4H" : ltfTf + "m"
 
// Intrabar split: ONE request, made only when the option is on (dynamic request inside the if).
float ltfBuy  = na
float ltfSell = na
int   ltfN    = 0
if useLtf and ltfAllowed
    [bA, sA] = request.security_lower_tf(syminfo.tickerid, ltfTf, f_split())
    ltfN := array.size(bA)
    if ltfN > 0 and array.size(sA) == ltfN
        ltfBuy  := array.sum(bA)
        ltfSell := array.sum(sA)
bool usedLtf = ltfN > 0 and nz(ltfBuy) + nz(ltfSell) > 0.0
 
// Final split of this bar. The proxy splits the bar's own volume (weight 1 per bar on symbols without volume).
float bfBar  = f_buyFrac(open, high, low, close)
float wBar   = anyVol ? vol : 1.0
float buyV   = usedLtf ? ltfBuy  : wBar * bfBar
float sellV  = usedLtf ? ltfSell : wBar * (1.0 - bfBar)
float totV   = buyV + sellV
float dScore = totV > 0.0 ? (buyV - sellV) / totV : 0.0          // -1 .. +1
float dPct   = 100.0 * dScore
float buyPct = totV > 0.0 ? 100.0 * buyV / totV : 50.0
 
// Relative volume.
float volAvg = ta.sma(vol, volLen)
float rv     = anyVol and nz(volAvg) > 0.0 ? vol / volAvg : 1.0
 
// Strong bar = |delta| and relative volume both above the inputs (threshold by the source this bar used).
float fullAt     = (usedLtf ? fullLtf : fullPx) / 100.0
float strongAt   = (usedLtf ? strongLtf : strongPx) / 100.0
bool  strongBar  = anyVol and barHasVol and math.abs(dScore) >= strongAt and rv >= strongRv
bool  strongBuy  = strongBar and dScore > 0.0
bool  strongSell = strongBar and dScore < 0.0
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 9. SESSION DELTA (reset at the session / day start; daily charts by week, weekly by month, monthly by year)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string rstTf      = timeframe.isintraday ? "D" : timeframe.isdaily ? "W" : timeframe.isweekly ? "M" : "12M"
string perName    = timeframe.isintraday ? "Session" : timeframe.isdaily ? "Week" : timeframe.isweekly ? "Month" : "Year"
string perWord    = timeframe.isintraday ? "today" : timeframe.isdaily ? "this week" : timeframe.isweekly ? "this month" : "this year"
bool   newPer     = timeframe.change(rstTf)
 
var float sBuy  = 0.0
var float sSell = 0.0
var int   nBuy  = 0
var int   nSell = 0
if newPer
    sBuy  := 0.0
    sSell := 0.0
    nBuy  := 0
    nSell := 0
sBuy  += buyV                                       // includes the live bar (rolled back and re-added every tick)
sSell += sellV
if barstate.isconfirmed                             // strong bars are counted once the bar has closed
    if strongBuy
        nBuy += 1
    if strongSell
        nSell += 1
float sTot    = sBuy + sSell
float sessPct = sTot > 0.0 ? 100.0 * (sBuy - sSell) / sTot : 0.0
float sessBuy = sTot > 0.0 ? 100.0 * sBuy / sTot : 50.0
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 10. CANDLES (plotcandle) + PLOT COUNT
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// PLOT COUNT (TradingView limit 64, RE10140; the local compiler does not check it). Counted by hand:
//   scale anchor plot(close), const colour (section 0) ............ 1 x 1 =  1
//   plotcandle: open / high / low / close ......................... 4
//               + series body colour + series wick colour
//               + series border colour ............................ 3     =  7
//   alertcondition x 2 (section 13) ............................... 2 x 1 =  2
//   TOTAL ......................................................... 10 of 64 (target <= 56)
//
// Delta mode: strength = |delta| / full-colour delta, side = sign of the delta; the quiet-bar fade (relative volume
// 0.25x -> full-colour multiple) blends the candle toward a soft grey. Volume mode: side = close vs open, strength
// from relative volume only (0.5x grey -> full-colour multiple at the peak colour).
bool  isDelta = candleMode == "Delta"
int   sD      = dScore > 0.0005 ? 1 : dScore < -0.0005 ? -1 : 0
int   sV      = close > open ? 1 : close < open ? -1 : 0
int   side    = isDelta ? sD : sV
float aD      = math.min(1.0, math.abs(dScore) / fullAt)
float aV      = math.min(1.0, math.max(0.0, (rv - 0.5) / math.max(0.1, volFull - 0.5)))
color core    = f_ramp(isDelta ? aD : aV, side)
float q       = isDelta and fadeQuiet and anyVol ? math.min(1.0, math.max(0.0, (rv - 0.25) / math.max(0.05, satAt - 0.25))) : 1.0
 
// Body: core colour at full volume, a soft grey (55 transparency) on the quietest bars.
color quietBody = color.new(f_mix(core, cNeu, 0.6), 55)
color bodyC     = color.from_gradient(q, 0.0, 1.0, quietBody, color.new(core, 0))
// Wick and border: a shade brighter than the body (lighter on a dark chart, deeper on a white one), less faded.
color rimBase   = isLight ? f_mix(core, #000000, 0.25) : f_mix(core, #FFFFFF, 0.3)
color quietRim  = color.new(f_mix(rimBase, cNeu, 0.5), 35)
color rimC      = color.from_gradient(q, 0.0, 1.0, quietRim, color.new(rimBase, 0))
// Paper & Ink: one ink for both sides, so selling-led candles are hollow (border and wick only).
if isMono and side < 0
    bodyC := color.new(bodyC, 100)
 
bool candleOn = candleMode != "Off"
plotcandle(candleOn ? open : na, candleOn ? high : na, candleOn ? low : na, candleOn ? close : na, "Delta Flow Candles",
     color = bodyC, wickcolor = rimC, bordercolor = rimC, display = display.pane)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 11. DELTA % TAGS (closed strong bars only, de-collided, newest N kept)
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
f_pct(float v) =>
    int r = math.round(nz(v))
    (r > 0 ? "+" : r < 0 ? "-" : "") + str.tostring(math.abs(r)) + " %"
 
string tagSz = tagSizeS == "Large" ? size.large : tagSizeS == "Normal" ? size.normal : size.small
 
// Lane gap: the larger of the input x ATR and 1/38 of the recent span (lesson: ATR alone fails on wide scales).
float span   = nz(ta.highest(high, 300) - ta.lowest(low, 300), nz(atrK, high - low) * 20.0)
float tagGap = math.max(tagGapAtr * nz(atrK, high - low), span / 38.0)
float tagPad = 0.12 * nz(atrK, high - low)
 
// Tag lane (evolves the kit's f_lane for bar tags): a tag's text centre must keep one gap from every recent tag
// within 6 bars; if the slot is taken the tag moves further AWAY from price (up above the wick, down below it).
var array<int>   tagXs = array.new<int>()
var array<float> tagCs = array.new<float>()
f_tagLane(int x, float y0, int s, float gap) =>
    // at most two steps away from the wick; a tag that still has no room is skipped (returns na) so no tag floats
    // far from its candle (chart check 2026-11-06: tags stepped up to 10 gaps away)
    float y   = y0
    bool  ok  = false
    for k = 0 to 2
        float c   = y + s * gap * 0.5
        bool  hit = false
        int   n   = array.size(tagXs)
        if n > 0
            for i = 0 to n - 1
                if math.abs(x - array.get(tagXs, i)) <= 3 and math.abs(array.get(tagCs, i) - c) < gap * 0.999
                    hit := true
        if not hit
            ok := true
            break
        y += s * gap
    if ok
        array.push(tagXs, x)
        array.push(tagCs, y + s * gap * 0.5)
        if array.size(tagXs) > 40
            array.shift(tagXs)
            array.shift(tagCs)
    ok ? y : na
 
var array<label> tagLbls = array.new<label>()
if showTags and barstate.isconfirmed and strongBar
    int    up   = dScore > 0.0 ? 1 : -1
    float  y0   = up == 1 ? high + tagPad : low - tagPad
    float  ty   = f_tagLane(bar_index, y0, up, tagGap)
    color  tc   = up == 1 ? cHotBull : cHotBear
    label  lb   = na(ty) ? na : f_tag(bar_index, ty, f_pct(dPct), tc, up == 1 ? label.style_label_down : label.style_label_up, tagSz)
    if not na(lb)
        label.set_tooltip(lb, "Delta " + f_pct(dPct) + " · buy " + str.tostring(buyPct, "0") + " % / sell " + str.tostring(100.0 - buyPct, "0")
             + " %\nRelative volume " + str.tostring(rv, "0.0") + "x · volume " + f_k(vol) + "\nSource: " + (usedLtf ? "intrabar " + ltfName : "chart proxy"))
        array.push(tagLbls, lb)
        f_capLabels(tagLbls, maxLabels)
 
// Free-account guard: nothing stays anchored more than 4,990 bars back.
if barstate.islast and array.size(tagLbls) > 0
    for i = array.size(tagLbls) - 1 to 0
        label lbOld = array.get(tagLbls, i)
        if label.get_x(lbOld) < bar_index - 4990
            label.delete(lbOld)
            array.remove(tagLbls, i)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 12. SESSION TAG (right edge) + DASHBOARD
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
string perShort = str.lower(perName)
color  sessCol  = math.abs(sessPct) < 5.0 ? cNeu : sessPct > 0 ? cHotBull : cHotBear
color  lastCol  = f_ramp(aD, sD)
string srcTxt   = usedLtf ? "intrabar · " + ltfName : not useLtf ? "chart proxy" : not ltfAllowed ? "proxy · 1m chart" : "proxy · no " + ltfName + " data"
 
var label sessLbl = na
if barstate.islast
    f_laneReset()
    // seed the lane with the text centres of the delta tags on the last 5 bars, so the session tag steps around them
    int nT = array.size(tagXs)
    if nT > 0
        for i = 0 to nT - 1
            if array.get(tagXs, i) >= bar_index - 5
                array.push(laneReg, array.get(tagCs, i))
    if showSess
        string stxt = perShort + " " + f_pct(sessPct) + " · " + str.tostring(sessBuy, "0") + " % buy"
        float  sy   = f_lane(close, tagGap / math.max(nz(atrK), syminfo.mintick))
        if na(sessLbl)
            sessLbl := f_tag(bar_index + 2, sy, stxt, sessCol, label.style_label_left, size.small)
        else
            label.set_xy(sessLbl, f_xr(f_xo(bar_index + 2)), sy)
            label.set_text(sessLbl, stxt)
            label.set_textcolor(sessLbl, sessCol)
        label.set_tooltip(sessLbl, perName + " delta since the " + perShort + " start: (buy volume - sell volume) / total volume. Strong bars "
             + perWord + ": " + str.tostring(nBuy) + " buy-led, " + str.tostring(nSell) + " sell-led. Source: " + srcTxt + ".")
    else if not na(sessLbl)
        label.delete(sessLbl)
        sessLbl := na
 
if showDash and barstate.islast
    f_dBegin()
    f_dHead("DELTA FLOW")
 
    if not dashCompact
        f_dRow("Last bar delta", f_pct(dPct) + " · " + str.tostring(buyPct, "0") + "/" + str.tostring(100.0 - buyPct, "0"), sD == 0 ? cNeu : lastCol,
             "Delta of the newest bar: (buy volume - sell volume) / its volume, then the buy / sell share in %. Live while the bar forms, final when it closes. +100 % = every unit credited to buyers, -100 % = to sellers, near 0 = a balanced bar. Order-flow readers look at it next to the bar's range: a wide bar with a weak delta, or a strong delta that went nowhere, shows absorption. On the chart: the newest candle's colour.")
 
    f_dRow(perName + " delta", f_pct(sessPct) + " · " + str.tostring(sessBuy, "0") + " % buy", sessCol,
         "Sum of buy minus sell volume since the " + perShort + " started, as a % of the total volume traded in it, and the buy share. Intraday charts reset at the start of each trading day (the exchange session day), daily charts each week, weekly charts each month. A persistent positive value describes a " + perShort + " where buyers controlled most of the volume; a value drifting back toward 0 describes control fading. On the chart: the tag right of the last bar.")
 
    if not dashCompact
        f_dRow("Strong bars " + perWord, str.tostring(nBuy) + " buy · " + str.tostring(nSell) + " sell", nBuy > nSell ? cHotBull : nSell > nBuy ? cHotBear : cNeu,
             "Closed bars " + perWord + " whose |delta| reached " + str.tostring(usedLtf ? strongLtf : strongPx) + " % or more on at least " + str.tostring(strongRv, "0.0") + "x the average volume, split by side. These are the bars where one side was clearly in control on real participation; a one-sided count describes a " + perShort + " driven by that side. On the chart: the delta % tags.")
 
        string rvWord = rv >= 1.5 ? "heavy" : rv < 0.7 ? "quiet" : "normal"
        f_dRow("Relative volume", anyVol ? str.tostring(rv, "0.0") + "x · " + rvWord : "no volume", anyVol ? (rv >= 1.5 ? cAcc : rv < 0.7 ? cNeu : cTxt) : cNeu,
             "Volume of the newest bar as a multiple of its " + str.tostring(volLen) + "-bar average. Heavy volume gives a bar's delta more weight; a strong delta on quiet volume says little. On the chart: quiet bars fade toward grey (Delta mode) or the whole colour follows it (Volume mode).")
 
        f_dRow("Delta source", srcTxt, usedLtf ? cGlow : cTxt,
             "chart proxy = the split comes from each chart bar (close position in the range blended with the body direction), no extra data. intrabar = the bar's volume split from its " + ltfName + " bars (the 'Intrabar delta (1m)' option), closer to the real order flow. 'proxy · no data' = the option is on but this bar has no intrabar data (older history, or a 1m chart, which has nothing finer than 1 minute on a free account).")
 
    // Read line: clauses joined with "; ", a new line started whenever the current one would pass ~60 characters.
    string sessClause = math.abs(sessPct) < 5.0 ? perShort + " balanced (" + f_pct(sessPct) + ")" :
         (sessPct > 0 ? "buyers" : "sellers") + " led the " + perShort + " (" + f_pct(sessPct) + ")"
    string strongClause = not anyVol ? "no volume: colours use the close position only" :
         nBuy + nSell == 0 ? "no strong bars " + perWord :
         str.tostring(nBuy) + " strong buy-led vs " + str.tostring(nSell) + " sell-led " + perWord
    string lastClause = "last bar " + (math.abs(dPct) < 15.0 ? "balanced" : dPct > 0 ? "buy-led" : "sell-led")
         + (anyVol ? (rv < 0.7 ? " on quiet volume" : rv >= 1.5 ? " on heavy volume" : "") : "")
    array<string> readParts = array.from(sessClause, strongClause, lastClause)
    string readTxt = ""
    int    readLen = 0
    for p in readParts
        if readLen == 0
            readTxt += p
            readLen := str.length(p)
        else if readLen + 2 + str.length(p) > 60
            readTxt += ";\n " + p
            readLen := str.length(p)
        else
            readTxt += "; " + p
            readLen += 2 + str.length(p)
    f_dRead(readTxt)
 
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
// 13. ALERTS (events, not signals; use "Once per bar close")
// ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════
alertcondition(strongBuy and barstate.isconfirmed,  "Strong buy-led bar",  "Delta Flow Candles: a bar closed with buyers in control of its volume on heavy relative volume")
alertcondition(strongSell and barstate.isconfirmed, "Strong sell-led bar", "Delta Flow Candles: a bar closed with sellers in control of its volume on heavy relative volume")

← 返回列表