本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
// FUTURES TPO PROFILE ON CFD CHARTS
// Time Price Opportunity (market profile) per session, drawn on the chart
// symbol's price and tied to the REAL futures contract (auto-detected):
// - a TPO period only prints where the futures contract actually traded, so
// the dead hours of a 24h CFD or a futures holiday never inflate the profile,
// - next to the TPO (time) histogram, the futures VOLUME histogram of the same
// session is drawn on the same rows: time at price on the left, volume at
// price on the right, and the label reports how far the volume POC sits from
// the TPO POC.
// CFD tick volume is never used. Volume placement uses intrabars (1-min
// futures bars by default), matched by timestamp to the chart symbol's
// intrabar high/low, the same method as the fixed-range futures profile.
indicator("Futures TPO Profile — CFD Charts", shorttitle = "Fut TPO", overlay = true,
max_boxes_count = 500, max_lines_count = 100, max_labels_count = 200)
// ---- session ----
sessMode = input.string("Auto (cash hours)", "Session", options = ["Auto (cash hours)", "Custom"], group = "Session",
tooltip = "Auto: FDAX 09:00-17:30 Berlin, FTSE 08:00-16:30 London, NQ/ES/YM 09:30-16:00 New York. Unknown symbols use the custom session below.")
sessCustom = input.session("0900-1730", "…custom session", group = "Session",
tooltip = "The session needs a break between days (a 24h session without a gap would never reset).")
tzCustom = input.string("Europe/Berlin", "…custom timezone", group = "Session")
perMin = input.int(30, "TPO period (minutes)", options = [5, 10, 15, 30, 60], group = "Session")
ibN = input.int(2, "Initial balance (periods)", minval = 1, maxval = 6, group = "Session")
// ---- profile ----
rowsIn = input.int(40, "Rows", minval = 10, maxval = 80, group = "Profile",
tooltip = "Rows per session. Each row is one TPO and one volume box, so more rows and more sessions use up the 500-box budget faster.")
rowPts = input.float(0.0, "Row height (points, 0 = use Rows)", minval = 0, group = "Profile",
tooltip = "0 = each session's range is split into the number of rows above. Otherwise a fixed point height per row (max. 80 rows).")
vaPct = input.float(70, "Value area %", minval = 50, maxval = 90, step = 5, group = "Profile")
nPast = input.int(2, "Finished sessions to keep", minval = 1, maxval = 4, group = "Profile")
// ---- volume ----
volMode = input.string("Futures symbol", "Volume source", options = ["Chart (CFD)", "Futures symbol"], group = "Volume",
tooltip = "Futures = real exchange volume of the matching contract. Chart = this chart's own volume (use on a native futures chart).")
autoFut = input.bool(true, "Auto-detect futures symbol", group = "Volume")
futManual = input.symbol("EUREX:FDAX1!", "…manual otherwise", group = "Volume")
precIn = input.string("Auto", "Intrabar precision", options = ["Auto", "1 min", "5 min", "15 min", "Off (chart bars)"], group = "Volume",
tooltip = "Volume is placed at the high/low of these sub-bars instead of the whole chart bar. Auto: 1 min up to 15m charts, 5 min above. Falls back to chart bars where no intrabar history exists.")
useChart = volMode == "Chart (CFD)"
useFut = not useChart
// ---- display ----
tpoStyle = input.string("Letters on latest session", "TPO display", options = ["Blocks", "Letters on latest session"], group = "Display",
tooltip = "Letters: the latest session shows one letter per period (A = first period). Older sessions always use blocks.")
showVol = input.bool(true, "Show futures volume histogram", group = "Display")
widthPct = input.int(40, "Histogram width (% of session)", minval = 10, maxval = 100, group = "Display")
showIB = input.bool(true, "Show initial balance", group = "Display")
showSingles = input.bool(true, "Highlight single prints", group = "Display")
tpoCol = input.color(color.new(color.gray, 0), "TPO", group = "Display")
singleCol = input.color(color.new(color.orange, 0), "Single prints", group = "Display")
volCol = input.color(color.new(color.teal, 0), "Futures volume", group = "Display")
pocCol = input.color(color.red, "TPO POC", group = "Display")
vaCol = input.color(color.blue, "Value area", group = "Display")
vpocCol = input.color(color.yellow, "Volume POC", group = "Display")
ibCol = input.color(color.purple, "Initial balance", group = "Display")
// ---- auto-detection: chart symbol -> matching futures contract ----
f_detectFut() =>
s = str.lower(syminfo.ticker) + " " + str.lower(syminfo.prefix) + " " + str.lower(syminfo.description)
isNQ = str.contains(s, "nas") or str.contains(s, "ndx") or str.contains(s, "us100") or str.contains(s, "ustec") or str.contains(s, "tech100") or str.contains(s, "nq1") or str.contains(s, "nq!")
isYM = str.contains(s, "dow") or str.contains(s, "us30") or str.contains(s, "dji") or str.contains(s, "ym1") or str.contains(s, "ym!") or str.contains(s, "wall street")
isDAX = str.contains(s, "dax") or str.contains(s, "ger40") or str.contains(s, "de40") or str.contains(s, "german")
isFTSE = str.contains(s, "ftse") or str.contains(s, "uk100") or str.contains(s, "ukx")
isES = str.contains(s, "us500") or str.contains(s, "sp500") or str.contains(s, "spx") or str.contains(s, "s&p") or str.contains(s, "es1") or str.contains(s, "es!")
isDAX ? "EUREX:FDAX1!" : isFTSE ? "ICEEUR:Z1!" : isNQ ? "CME_MINI:NQ1!" :
isYM ? "CBOT_MINI:YM1!" : isES ? "CME_MINI:ES1!" : syminfo.tickerid
futSym = autoFut ? f_detectFut() : futManual
// Short contract name for the status label: "EUREX:FDAX1!" -> "FDAX".
f_root(string sym) =>
parts = str.split(sym, ":")
r = array.get(parts, array.size(parts) - 1)
str.replace_all(str.replace_all(r, "1!", ""), "!", "")
futRoot = f_root(futSym)
// ---- session per future (cash hours, the classic profile session) ----
isEU = str.contains(futSym, "FDAX") or str.contains(futSym, "FESX")
isUK = str.contains(futSym, "ICEEUR:Z")
isUS = str.contains(futSym, "NQ") or str.contains(futSym, "ES1") or str.contains(futSym, "YM") or str.contains(futSym, "RTY")
known = isEU or isUK or isUS
useAuto = sessMode == "Auto (cash hours)" and known
sessStr = useAuto ? (isEU ? "0900-1730" : isUK ? "0800-1630" : "0930-1600") : sessCustom
tzStr = useAuto ? (isEU ? "Europe/Berlin" : isUK ? "Europe/London" : "America/New_York") : tzCustom
// ---- intrabar timeframe (never higher than the chart) ----
chartSec = timeframe.in_seconds()
autoTf = chartSec <= 60 ? timeframe.period : chartSec <= 900 ? "1" : "5"
reqTf = precIn == "Auto" ? autoTf : precIn == "1 min" ? "1" : precIn == "5 min" ? "5" : precIn == "15 min" ? "15" : timeframe.period
ltf = timeframe.in_seconds(reqTf) > chartSec ? timeframe.period : reqTf
[cT, cH, cL, cV] = request.security_lower_tf(syminfo.tickerid, ltf, [time, high, low, volume])
[fT, fV] = request.security_lower_tf(futSym, ltf, [time, volume], ignore_invalid_symbol = true)
// Chart-bar fallback. gaps_on: a chart bar without a futures bar returns na
// instead of repeating the last futures volume.
futVolBar = request.security(futSym, timeframe.period, volume, gaps = barmerge.gaps_on, ignore_invalid_symbol = true)
// ---- session gate from the chart's own timestamp (no foreign-symbol anchor) ----
inS = not na(time(timeframe.period, sessStr, tzStr))
gapNs = not na(time[1]) and time - time[1] > 2 * 3600000
newS = inS and (not inS[1] or gapNs)
endS = not inS and inS[1]
perMs = perMin * 60000
tfTooBig = chartSec > perMin * 60
// ---- per-session state ----
MAX_E = 20000
var array<float> pHi = array.new_float() // per TPO period: high where the future traded
var array<float> pLo = array.new_float()
var array<float> eLo = array.new_float() // volume entries: intrabar low/high + futures volume
var array<float> eHi = array.new_float()
var array<float> eV = array.new_float()
var int sBar = na
var int eBar = na
var int sT = na
var bool sDone = true
var int nIntra = 0
var int nMiss = 0
var int nCoarse = 0
var bool capHit = false
type SessDraw
array<box> bx
array<line> ln
array<label> lb
var array<SessDraw> ring = array.new<SessDraw>()
var SessDraw dev = na
f_kill(SessDraw d) =>
if not na(d)
for b in d.bx
box.delete(b)
for l in d.ln
line.delete(l)
for lb in d.lb
label.delete(lb)
f_push(float lo, float hi, float v) =>
ok = array.size(eV) < MAX_E
if ok
array.push(eLo, lo)
array.push(eHi, hi)
array.push(eV, v)
ok
f_tfText(string tf) =>
sec = timeframe.in_seconds(tf)
tf == timeframe.period ? "chart bars" : sec < 3600 ? str.tostring(sec / 60) + "m intrabars" : str.tostring(sec / 3600) + "h intrabars"
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// ---- build one session's drawing from the current state arrays ----
f_build(int x0, int x1, bool latest) =>
d = SessDraw.new(array.new_box(), array.new_line(), array.new_label())
nP = array.size(pHi)
float sHi = na
float sLo = na
if nP > 0
for p = 0 to nP - 1
h = array.get(pHi, p)
if not na(h)
sHi := math.max(nz(sHi, h), h)
sLo := math.min(nz(sLo, array.get(pLo, p)), array.get(pLo, p))
if not na(sHi)
// ---- row grid ----
float base = sLo
float rowW = (sHi - sLo) / rowsIn
int nRows = rowsIn
if rowPts > 0
base := math.floor(sLo / rowPts) * rowPts
rowW := rowPts
nRows := int(math.ceil((sHi - base) / rowPts))
if nRows > 80
nRows := 80
rowW := (sHi - base) / 80
if rowW <= 0
rowW := syminfo.mintick
nRows := 1
nRows := math.max(1, nRows)
// ---- TPO counts (time at price): one per period and row touched ----
cnt = array.new_int(nRows, 0)
txt = array.new_string(nRows, "")
for p = 0 to nP - 1
h = array.get(pHi, p)
if not na(h)
loK = math.max(0, math.min(nRows - 1, int(math.floor((array.get(pLo, p) - base) / rowW))))
hiK = math.max(0, math.min(nRows - 1, int(math.floor((h - base) / rowW))))
ch = str.substring(LETTERS, math.min(p, 51), math.min(p, 51) + 1)
for k = loK to hiK
array.set(cnt, k, array.get(cnt, k) + 1)
array.set(txt, k, array.get(txt, k) + ch)
// TPO POC: most periods; ties go to the row nearest the session middle
mid = (nRows - 1) / 2.0
maxC = 0
pocI = 0
totalC = 0
for k = 0 to nRows - 1
c = array.get(cnt, k)
totalC += c
if c > maxC or (c == maxC and math.abs(k - mid) < math.abs(pocI - mid))
maxC := c
pocI := k
// value area by TPO count, expanded from the POC
vaC = array.get(cnt, pocI)
loI = pocI
hiI = pocI
target = totalC * vaPct / 100.0
while vaC < target and (loI > 0 or hiI < nRows - 1)
upC = hiI < nRows - 1 ? array.get(cnt, hiI + 1) : -1
dnC = loI > 0 ? array.get(cnt, loI - 1) : -1
if upC >= dnC
hiI += 1
vaC += math.max(upC, 0)
else
loI -= 1
vaC += math.max(dnC, 0)
pocPrice = base + (pocI + 0.5) * rowW
vah = base + (hiI + 1) * rowW
val = base + loI * rowW
// ---- futures volume at price on the same rows ----
vols = array.new_float(nRows, 0.0)
nE = array.size(eV)
if nE > 0
for i = 0 to nE - 1
loK = math.max(0, math.min(nRows - 1, int(math.floor((array.get(eLo, i) - base) / rowW))))
hiK = math.max(0, math.min(nRows - 1, int(math.floor((array.get(eHi, i) - base) / rowW))))
share = array.get(eV, i) / (hiK - loK + 1)
for k = loK to hiK
array.set(vols, k, array.get(vols, k) + share)
maxV = array.max(vols)
vpocI = array.indexof(vols, maxV)
vpocPrice = base + (vpocI + 0.5) * rowW
// ---- geometry: TPO grows right from the session start, volume left from its end ----
profW = math.max(2, int(math.round((x1 - x0 + 1) * widthPct / 100.0)))
letters = latest and tpoStyle == "Letters on latest session"
for k = 0 to nRows - 1
y1 = base + k * rowW
y2 = y1 + rowW
inVa = k >= loI and k <= hiI
c = array.get(cnt, k)
if c > 0 and not letters
w = math.max(1, int(math.round(profW * c / maxC)))
col = showSingles and c == 1 ? singleCol : tpoCol
array.push(d.bx, box.new(x0, y2, x0 + w, y1, border_color = na,
bgcolor = color.new(col, inVa ? 45 : 70)))
if c > 0 and letters
tc = showSingles and c == 1 ? singleCol : color.new(tpoCol, inVa ? 0 : 40)
array.push(d.lb, label.new(x0, (y1 + y2) / 2, array.get(txt, k), style = label.style_label_left,
color = color.new(color.black, 100), textcolor = tc, size = size.tiny,
text_font_family = font.family_monospace))
v = array.get(vols, k)
if showVol and maxV > 0 and v > 0
w = math.max(1, int(math.round(profW * v / maxV)))
array.push(d.bx, box.new(x1 - w, y2, x1, y1, border_color = na,
bgcolor = color.new(volCol, inVa ? 45 : 70)))
array.push(d.ln, line.new(x0, pocPrice, x1, pocPrice, color = pocCol, width = 2))
array.push(d.ln, line.new(x0, vah, x1, vah, color = vaCol, style = line.style_dashed))
array.push(d.ln, line.new(x0, val, x1, val, color = vaCol, style = line.style_dashed))
if showVol and maxV > 0
array.push(d.ln, line.new(x0, vpocPrice, x1, vpocPrice, color = vpocCol, style = line.style_dotted, width = 2))
// initial balance: range of the first ibN periods in which the future traded
if showIB
float ibH = na
float ibL = na
for p = 0 to math.min(ibN, nP) - 1
h = array.get(pHi, p)
if not na(h)
ibH := math.max(nz(ibH, h), h)
ibL := math.min(nz(ibL, array.get(pLo, p)), array.get(pLo, p))
if not na(ibH)
array.push(d.ln, line.new(x0, ibH, x1, ibH, color = color.new(ibCol, 20), style = line.style_dotted))
array.push(d.ln, line.new(x0, ibL, x1, ibL, color = color.new(ibCol, 20), style = line.style_dotted))
if latest
array.push(d.lb, label.new(x1, pocPrice, "TPO POC " + str.tostring(pocPrice, format.mintick),
style = label.style_label_left, color = color.new(pocCol, 20), textcolor = color.white, size = size.small))
array.push(d.lb, label.new(x1, vah, "VAH " + str.tostring(vah, format.mintick),
style = label.style_label_left, color = color.new(vaCol, 30), textcolor = color.white, size = size.small))
array.push(d.lb, label.new(x1, val, "VAL " + str.tostring(val, format.mintick),
style = label.style_label_left, color = color.new(vaCol, 30), textcolor = color.white, size = size.small))
if showVol and maxV > 0
array.push(d.lb, label.new(x1, vpocPrice, "Vol POC " + str.tostring(vpocPrice, format.mintick),
style = label.style_label_left, color = color.new(vpocCol, 20), textcolor = color.black, size = size.small))
// ---- status: volume source, precision, session, POC distance ----
hasVol = useChart or nE > 0
src = useChart ? "Chart volume" : hasVol ? "Futures volume: " + futRoot + " ✓" : "⚠ Futures volume: " + futRoot + " — no data this session"
prec = f_tfText(ltf)
if nIntra > 0 and nMiss > 0
prec += " (" + str.tostring(100.0 * (nIntra - nMiss) / nIntra, "#") + "% matched)"
if nCoarse > 0
prec += " · " + str.tostring(nCoarse) + " bars at chart resolution"
if capHit
prec += " · ⚠ entry cap reached"
info = "TPO " + str.tostring(perMin) + "m · " + sessStr + " " + tzStr + (useAuto ? "" : " (custom)")
if hasVol and maxV > 0
dist = vpocPrice - pocPrice
info += "\nVol POC vs TPO POC: " + (dist >= 0 ? "+" : "") + str.tostring(dist, format.mintick)
if tfTooBig
info += "\n⚠ Chart timeframe above the TPO period — use " + str.tostring(perMin) + " min or lower"
array.push(d.lb, label.new(x0, sHi, src + " · " + prec + "\n" + info,
style = label.style_label_down, color = color.new(color.black, 25), textcolor = color.white,
size = size.small, textalign = text.align_left))
d
f_store(SessDraw d) =>
array.push(ring, d)
while array.size(ring) > nPast
f_kill(array.shift(ring))
// ---- session close: keep the finished profile ----
if (endS or newS) and not na(sBar) and not sDone
f_store(f_build(sBar, eBar, false))
sDone := true
// ---- session start: reset the state ----
if newS
array.clear(pHi)
array.clear(pLo)
array.clear(eLo)
array.clear(eHi)
array.clear(eV)
sBar := bar_index
sT := time
sDone := false
nIntra := 0
nMiss := 0
nCoarse := 0
capHit := false
// ---- collect: futures volume entries + TPO period ranges where the future traded ----
if inS and not na(sBar) and not sDone
eBar := bar_index
barV = 0.0
nC = array.size(cT)
if useFut
nF = array.size(fT)
if nC > 0 and nF > 0
j = 0
for i = 0 to nF - 1
v = array.get(fV, i)
if not na(v) and v > 0
t = array.get(fT, i)
while j < nC and array.get(cT, j) < t
j += 1
matched = j < nC and array.get(cT, j) == t
lo = matched ? array.get(cL, j) : low
hi = matched ? array.get(cH, j) : high
if not f_push(lo, hi, v)
capHit := true
barV += v
nIntra += 1
if not matched
nMiss += 1
else if not na(futVolBar) and futVolBar > 0
if not f_push(low, high, futVolBar)
capHit := true
barV += futVolBar
nCoarse += 1
else
if nC > 0
for i = 0 to nC - 1
v = array.get(cV, i)
if not na(v) and v > 0
if not f_push(array.get(cL, i), array.get(cH, i), v)
capHit := true
barV += v
nIntra += 1
else if not na(volume) and volume > 0
if not f_push(low, high, volume)
capHit := true
barV += volume
nCoarse += 1
// A period prints a TPO only on bars where volume actually traded.
if barV > 0
pIdx = int((time - sT) / perMs)
while array.size(pHi) <= pIdx
array.push(pHi, na)
array.push(pLo, na)
array.set(pHi, pIdx, math.max(nz(array.get(pHi, pIdx), high), high))
array.set(pLo, pIdx, math.min(nz(array.get(pLo, pIdx), low), low))
// ---- latest session: redraw with letters and labels on every update ----
if barstate.islast
f_kill(dev)
dev := na
if inS and not sDone and not na(sBar)
dev := f_build(sBar, bar_index, true)
else if sDone and array.size(ring) > 0 and array.size(pHi) > 0
// market closed: the last finished session becomes the labeled one
f_kill(array.pop(ring))
array.push(ring, f_build(sBar, eBar, true))