本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=6
indicator("MTF Delta Ladder (Top-Down Delta)", "MTF Delta", overlay = true, max_labels_count = 500, max_boxes_count = 50, max_lines_count = 50)
// ───────────────────────────── Inputs ─────────────────────────────
grpSrc = "Delta source"
ltfIn = input.timeframe("", "Intrabar timeframe (blank = auto)", group = grpSrc,
tooltip = "Delta is built from lower-timeframe bars inside each chart candle. Each intrabar's volume is counted as buying if it closed up, selling if it closed down (tick rule on ties). Leave blank for auto: 1-minute on intraday charts, 5-minute on 2h+ charts, 1-hour on daily+.")
grpBar = "Chart candle deltas"
showBarD = input.bool(true, "Show delta under each candle", group = grpBar)
barLookback = input.int(150, "How many recent candles", minval = 1, maxval = 450, group = grpBar)
barTxtSize = input.string(size.tiny, "Text size", options = [size.tiny, size.small, size.normal], group = grpBar)
grpHTF = "Higher-timeframe candles (right of price)"
en1 = input.bool(true, "", inline = "h1", group = grpHTF)
tf1 = input.timeframe("15", "HTF 1", inline = "h1", group = grpHTF)
en2 = input.bool(true, "", inline = "h2", group = grpHTF)
tf2 = input.timeframe("60", "HTF 2", inline = "h2", group = grpHTF)
en3 = input.bool(true, "", inline = "h3", group = grpHTF)
tf3 = input.timeframe("240", "HTF 3", inline = "h3", group = grpHTF)
firstOffset = input.int(8, "Distance from last candle (bars)", minval = 2, group = grpHTF)
spacing = input.int(8, "Spacing between HTF candles (bars)", minval = 3, group = grpHTF)
halfW = input.int(2, "HTF candle half-width (bars)", minval = 1, maxval = 5, group = grpHTF)
showTimer = input.bool(true, "Show countdown to HTF close", group = grpHTF)
closedMode = input.string("Last traded candle", "When session is closed", options = ["Last traded candle", "Previous completed candle", "Off"], group = grpHTF,
tooltip = "When the market is closed the newest HTF candle is often an empty stub (flat line, Δ 0).\n\nLast traded candle: if the current HTF candle has no real trading, show the most recent HTF candle that did.\nPrevious completed candle: always show the candle before the current one while closed.\nOff: original behaviour.")
grpRoll = "Multi-day timeframes (D / W / M)"
rollOn = input.bool(true, "Count in trading days (rolling)", group = grpRoll,
tooltip = "Daily-and-above HTFs become a rolling window of the most recent trading days, skipping weekends and empty sessions.\n\n3D = last 3 trading days (e.g. Thu, Fri, Mon)\n1W = last 5 trading days\n2W = last 10 trading days\n1M = last 21 trading days\n\nThe chart must have enough history loaded to cover the window (lower chart timeframes load fewer days).")
daysPerWeek = input.int(5, "Trading days per week", minval = 1, maxval = 7, group = grpRoll, tooltip = "5 for futures/stocks/forex, 7 for crypto.")
daysPerMonth = input.int(21, "Trading days per month", minval = 1, maxval = 31, group = grpRoll)
grpStyle = "Style"
bullCol = input.color(color.new(#089981, 0), "Bullish", inline = "c", group = grpStyle)
bearCol = input.color(color.new(#f23645, 0), "Bearish", inline = "c", group = grpStyle)
wickCol = input.color(color.new(#808080, 0), "Wick", inline = "c", group = grpStyle)
compact = input.bool(true, "Compact numbers (12.4K)", group = grpStyle)
// ───────────────────────────── Helpers ─────────────────────────────
fmtNum(float x) =>
float a = math.abs(x)
string s = x > 0 ? "+" : x < 0 ? "-" : ""
if not compact or a < 10000
s + str.tostring(a, "#")
else if a < 1000000
s + str.tostring(a / 1000, "#.#") + "K"
else
s + str.tostring(a / 1000000, "#.##") + "M"
fmtTF(string tf) =>
int secs = timeframe.in_seconds(tf)
if secs >= 604800
tf
else if secs % 86400 == 0
str.tostring(secs / 86400) + "D"
else if secs % 3600 == 0
str.tostring(secs / 3600) + "h"
else if secs % 60 == 0
str.tostring(secs / 60) + "m"
else
str.tostring(secs) + "s"
fmtCountdown(int closeTime) =>
string out = ""
if not na(closeTime)
int total = math.max(0, int(math.floor((closeTime - timenow) / 1000)))
int hh = int(math.floor(total / 3600))
int mm = int(math.floor((total % 3600) / 60))
int ss = total % 60
out := hh > 0 ? str.format("{0}:{1,number,00}:{2,number,00}", hh, mm, ss) : str.format("{0}:{1,number,00}", mm, ss)
out
// ───────────────────────────── Per-candle delta ─────────────────────────────
autoLtf() =>
int s = timeframe.in_seconds()
s < 60 ? timeframe.period : s <= 3600 ? "1" : s < 86400 ? "5" : "60"
string ltf = ltfIn == "" ? autoLtf() : timeframe.in_seconds(ltfIn) > timeframe.in_seconds() ? timeframe.period : ltfIn
[cArr, oArr, vArr] = request.security_lower_tf(syminfo.tickerid, ltf, [close, open, volume])
var float lastC = na
float barDelta = 0.0
int n = array.size(cArr)
if n > 0
for i = 0 to n - 1
float c = cArr.get(i)
float o = oArr.get(i)
float v = nz(vArr.get(i))
int dir = c > o ? 1 : c < o ? -1 : na(lastC) ? 0 : c > lastC ? 1 : c < lastC ? -1 : 0
barDelta += dir * v
lastC := c
else
// No intrabar data (e.g. very old history): fall back to the chart candle itself
barDelta := (close > open ? 1 : close < open ? -1 : 0) * nz(volume)
lastC := close
if barstate.islast and na(volume)
runtime.error("This symbol has no volume data, so delta can't be calculated.")
// Delta labels under chart candles (managed queue so HTF labels never get garbage-collected)
var label[] barLabels = array.new<label>()
if showBarD and bar_index >= last_bar_index - barLookback
barLabels.push(label.new(bar_index, low, fmtNum(barDelta), yloc = yloc.belowbar, style = label.style_none,
textcolor = barDelta >= 0 ? bullCol : bearCol, size = barTxtSize))
if barLabels.size() > barLookback + 1
label.delete(barLabels.shift())
// ───────────────────────────── HTF aggregation ─────────────────────────────
// Builds the forming HTF candle (OHLC + delta) from chart candles since the HTF bar opened,
// so it stays correct on the live bar and when the chart is first loaded mid-period.
// Also remembers the last completed HTF candle that actually traded, used when the session is closed.
type Candle
float o
float h
float l
float c
float d
float v
// A "stub" is an HTF candle with no real trading in it (no volume, or a single flat price)
isStub(Candle k) =>
na(k.o) or k.v == 0 or k.h == k.l
aggTF(string tf, float dlt) =>
var Candle cur = Candle.new(na, na, na, na, 0.0, 0.0)
var Candle prv = Candle.new(na, na, na, na, na, na)
if timeframe.change(tf) or na(cur.o)
// Store the candle that just finished, but only if it actually traded,
// so empty closed-session stubs never overwrite the last real candle
if not isStub(cur)
prv := cur.copy()
cur.o := open
cur.h := high
cur.l := low
cur.d := 0.0
cur.v := 0.0
else
cur.h := math.max(cur.h, high)
cur.l := math.min(cur.l, low)
cur.c := close
cur.d += dlt
cur.v += nz(volume)
[cur, prv]
[cur1, prv1] = aggTF(tf1, barDelta)
[cur2, prv2] = aggTF(tf2, barDelta)
[cur3, prv3] = aggTF(tf3, barDelta)
// Market is closed when the last chart candle's close time is already in the past
bool mktClosed = barstate.islast and not na(time_close) and timenow > time_close
// ───────────────────────────── Trading-day history (for rolling D / W / M) ─────────────────────────────
// One record per trading session (TradingView's "D" session, so futures' Sunday-evening open
// belongs to Monday). Weekends never create a record; empty sessions are skipped when summing.
var array<float> dyO = array.new<float>()
var array<float> dyH = array.new<float>()
var array<float> dyL = array.new<float>()
var array<float> dyC = array.new<float>()
var array<float> dyD = array.new<float>()
var array<float> dyV = array.new<float>()
var array<int> dyT = array.new<int>()
if timeframe.change("D") or dyO.size() == 0
dyO.push(open)
dyH.push(high)
dyL.push(low)
dyC.push(close)
dyD.push(0.0)
dyV.push(0.0)
dyT.push(time_tradingday)
if dyO.size() > 400
dyO.shift()
dyH.shift()
dyL.shift()
dyC.shift()
dyD.shift()
dyV.shift()
dyT.shift()
else
int jj = dyO.size() - 1
dyH.set(jj, math.max(dyH.get(jj), high))
dyL.set(jj, math.min(dyL.get(jj), low))
int jLast = dyO.size() - 1
dyC.set(jLast, close)
dyD.set(jLast, dyD.get(jLast) + barDelta)
dyV.set(jLast, dyV.get(jLast) + nz(volume))
// How many trading days a TF covers (0 = not a multi-day TF / rolling off)
rollDays(string tf) =>
int n = 0
if rollOn and timeframe.in_seconds() <= 86400
int secs = timeframe.in_seconds(tf)
if str.endswith(tf, "M")
string m = str.replace(tf, "M", "")
n := (m == "" ? 1 : int(str.tonumber(m))) * daysPerMonth
else if secs >= 604800 and secs % 604800 == 0
n := int(secs / 604800) * daysPerWeek
else if secs >= 86400 and secs % 86400 == 0
n := int(secs / 86400)
n
// Sum the last n trading days that actually traded; `skip` drops the newest k traded days first
rollWindow(int n, int skip) =>
Candle k = Candle.new(na, na, na, na, 0.0, 0.0)
int got = 0
int skipped = 0
int tFirst = na
int tLast = na
int sz = dyO.size()
if sz > 0
for i = sz - 1 to 0
bool stub = dyV.get(i) == 0 or dyH.get(i) == dyL.get(i)
if not stub
if skipped < skip
skipped += 1
else
if got == 0
k.c := dyC.get(i)
k.h := dyH.get(i)
k.l := dyL.get(i)
tLast := dyT.get(i)
else
k.h := math.max(k.h, dyH.get(i))
k.l := math.min(k.l, dyL.get(i))
k.o := dyO.get(i)
k.d += dyD.get(i)
k.v += dyV.get(i)
tFirst := dyT.get(i)
got += 1
if got >= n
break
string fmtD = n <= 7 ? "EEE" : "d MMM"
string rng = got == 0 ? "" : got == 1 ? str.format_time(tFirst, fmtD, "UTC") : str.format_time(tFirst, fmtD, "UTC") + " – " + str.format_time(tLast, fmtD, "UTC")
if got > 0 and got < n
rng += " (" + str.tostring(got) + "/" + str.tostring(n) + "d loaded)"
[k, rng]
// ───────────────────────────── HTF drawing ─────────────────────────────
drawHTF(bool en, string tf, Candle cur, Candle prv, int offset) =>
var box body = box.new(na, na, na, na, xloc = xloc.bar_index, border_width = 1)
var line wick = line.new(na, na, na, na, xloc = xloc.bar_index, width = 1)
var label lbl = label.new(na, na, "", xloc = xloc.bar_index, style = label.style_label_down, color = color(na), size = size.small)
if barstate.islast
bool lowerThanChart = timeframe.in_seconds(tf) < timeframe.in_seconds()
// While closed, swap to the last traded candle when the current one is an empty stub
bool usePrev = mktClosed and closedMode != "Off" and not na(prv.o) and (closedMode == "Previous completed candle" or isStub(cur))
Candle k = usePrev ? prv : cur
string sub = ""
int nDays = rollDays(tf)
if nDays > 0
// Rolling trading-day window: empty/closed sessions are already skipped,
// so while closed it naturally ends on the last day that traded
int skip = mktClosed and closedMode == "Previous completed candle" ? 1 : 0
[w, rng] = rollWindow(nDays, skip)
k := w
sub := rng
usePrev := skip == 1
float o = k.o
float h = k.h
float l = k.l
float c = k.c
float d = k.d
if en and not na(o) and not lowerThanChart
int x = bar_index + offset
color col = c >= o ? bullCol : bearCol
box.set_lefttop(body, x - halfW, math.max(o, c))
box.set_rightbottom(body, x + halfW, math.min(o, c))
box.set_bgcolor(body, col)
box.set_border_color(body, col)
line.set_xy1(wick, x, h)
line.set_xy2(wick, x, l)
line.set_color(wick, wickCol)
// Rolling windows roll forward at each daily close, so count down to that
string timer = mktClosed ? "closed" : fmtCountdown(time_close(nDays > 0 ? "D" : tf))
string head = showTimer ? fmtTF(tf) + " (" + timer + ")" : fmtTF(tf)
label.set_xy(lbl, x, h)
label.set_text(lbl, head + (sub != "" ? "\n" + sub : "") + "\nΔ " + fmtNum(d) + (usePrev ? " ·prev" : ""))
label.set_textcolor(lbl, d >= 0 ? bullCol : bearCol)
else
box.set_bgcolor(body, color(na))
box.set_border_color(body, color(na))
line.set_color(wick, color(na))
label.set_text(lbl, en and lowerThanChart ? fmtTF(tf) + "\n(below chart TF)" : "")
label.set_xy(lbl, bar_index + offset, close)
label.set_textcolor(lbl, chart.fg_color)
drawHTF(en1, tf1, cur1, prv1, firstOffset)
drawHTF(en2, tf2, cur2, prv2, firstOffset + spacing)
drawHTF(en3, tf3, cur3, prv3, firstOffset + spacing * 2)