本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Perfil de la sesion TPO simple", shorttitle = "Perfil sesion", overlay = true, max_boxes_count = 500)
// A light time-at-price profile of the regular session, computed on the data of THIS chart: the session in progress
// and the one before it (or the last two when the market is closed).
//
// Each 30-minute period that traded at a price row adds one block to that row, so the length of a row is the number
// of periods that traded there. Colours: the row with the most periods (POC; ties go to the row closest to the middle
// of the range, then the higher one), the 70% value area grown from it one row at a time, and the rest.
// Row size: a round number of ticks that gives about 45 rows for a typical session.
//
// It is a drawing of structure, not a signal. The profile of the session in progress changes until the session ends;
// the profile of a finished session does not.
// --- BEGIN GENERATED CONSTANTS
// Written by scripts/build_tradingview_constants.py. Do not edit by hand.
// 29 markets, statistics through 2026-10-16. Frequencies, counts and session hours only.
string DATA_THROUGH = "2026-10-16"
f_parent(string r) =>
switch r
"MES" => "ES"
"MNQ" => "NQ"
"M2K" => "RTY"
"MYM" => "YM"
"MGC" => "GC"
"SIL" => "SI"
"MHG" => "HG"
"MCL" => "CL"
"QM" => "CL"
"MNG" => "NG"
"QG" => "NG"
"MBT" => "BTC"
"MET" => "ETH"
"M6E" => "6E"
"M6A" => "6A"
"M6B" => "6B"
"E7" => "6E"
"J7" => "6J"
"XC" => "ZC"
"XK" => "ZS"
"XW" => "ZW"
"10Y" => "ZN"
"MTN" => "ZN"
"MWN" => "ZB"
=> r
f_lvSess(string r) =>
switch r
"NKD" => "0900-1515"
=> "0930-1600"
f_lvTz(string r) =>
switch r
"NKD" => "Asia/Tokyo"
=> "America/New_York"
f_ownSess(string r) =>
switch r
"6A" => "0820-1500"
"6B" => "0820-1500"
"6C" => "0820-1500"
"6E" => "0820-1500"
"6J" => "0820-1500"
"6M" => "0820-1500"
"6N" => "0820-1500"
"6S" => "0820-1500"
"CL" => "0900-1430"
"GC" => "0820-1330"
"HG" => "0810-1300"
"NG" => "0900-1430"
"NKD" => "0900-1515"
"PA" => "0830-1300"
"PL" => "0820-1305"
"SI" => "0820-1330"
"ZB" => "0820-1500"
"ZC" => "0930-1420"
"ZF" => "0820-1500"
"ZN" => "0820-1500"
"ZS" => "0930-1420"
"ZT" => "0820-1500"
"ZW" => "0930-1420"
=> "0930-1600"
f_ownTz(string r) =>
switch r
"NKD" => "Asia/Tokyo"
=> "America/New_York"
// --- END GENERATED CONSTANTS
// --- BEGIN SHARED CORE
// One session state machine, fed bar by bar. The same code runs (a) inside a fixed-timeframe request, where the chart
// keeps enough sessions for the 20-session average range and the row size, and (b) on the chart bars (or on their
// intrabars when the chart timeframe does not line up with the session), for what happens inside today's session.
type Sess
int startMin = 570
int endMin = 960
string tz = "America/New_York"
int ibMin = 60
int orMin = 15
int rowTicks = 0
bool active = false
int count = 0
int finished = 0
int dayKey = 0
int startTime = 0
int elapsed = 0
int lastDow = 0
int lastMonth = 0
float o = na
float h = na
float l = na
float c = na
float orH = na
float orL = na
bool orDone = false
float ibH = na
float ibL = na
bool ibDone = false
bool brkOrUp = false
bool brkOrDn = false
bool brkIbUp = false
bool brkIbDn = false
bool gapFilled = false
float step = na
float nextStep = na
array<float> perH
array<float> perL
float pO = na
float pH = na
float pL = na
float pC = na
float pVAH = na
float pVAL = na
float pPOC = na
float pStep = na
int pDayKey = 0
int pDow = 0
int pStart = 0
array<float> pPerH
array<float> pPerL
array<float> ranges
array<float> trs
float atr = na
float wO = na
float wH = na
float wL = na
float pwH = na
float pwL = na
bool wPartial = true
float mO = na
float mH = na
float mL = na
float pmH = na
float pmL = na
bool mPartial = true
f_newSess(int startMin, int endMin, string tz, int ibMin, int orMin, int rowTicks) =>
Sess.new(startMin = startMin, endMin = endMin, tz = tz, ibMin = ibMin, orMin = orMin, rowTicks = rowTicks, perH = array.new<float>(), perL = array.new<float>(), pPerH = array.new<float>(), pPerL = array.new<float>(), ranges = array.new<float>(), trs = array.new<float>())
// "HHMM-HHMM" -> minutes of the day
f_sessStart(string s) =>
int(str.tonumber(str.substring(s, 0, 2)) * 60 + str.tonumber(str.substring(s, 2, 4)))
f_sessEnd(string s) =>
int(str.tonumber(str.substring(s, 5, 7)) * 60 + str.tonumber(str.substring(s, 7, 9)))
// Row size of the profile: a round number of ticks that gives about 45 rows for a typical session
// (the median range of up to 60 sessions before the one being read). rowTicks > 0 overrides it.
f_autoStep(array<float> ranges, int rowTicks, float fallbackRange) =>
float typical = fallbackRange
int n = ranges.size()
if n > 0
array<float> srt = ranges.copy()
srt.sort(order.ascending)
typical := srt.get(int(math.floor(n / 2)))
int k = int(math.max(1, math.ceil(nz(typical, syminfo.mintick * 45) / 45 / syminfo.mintick)))
int ticks = k
array<int> nice = array.from(1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 200, 250, 500, 1000)
bool found = false
for v in nice
if not found and v >= k
ticks := v
found := true
if rowTicks > 0
ticks := rowTicks
ticks * syminfo.mintick
f_row(float price, float step) =>
int(math.floor(price / step + 1e-9))
// Point of control and 70% value area from the highs and lows of the 30-minute periods of one session.
// POC = the row with the most periods; ties go to the row closest to the middle of the range, then the higher one.
// Value area = grown from the POC one row at a time toward the side with more periods (ties up) until 70%.
// A row is named by its lower price, like the profile page of the portal.
f_profile(array<float> perH, array<float> perL, float step) =>
float poc = na
float vah = na
float val = na
int bot = na
int top = na
int np = perH.size()
if np > 0 and not na(step) and step > 0
for i = 0 to np - 1
float ph = perH.get(i)
float pl = perL.get(i)
if not na(ph) and not na(pl)
int rl = f_row(pl, step)
int rh = f_row(ph, step)
bot := na(bot) ? rl : math.min(bot, rl)
top := na(top) ? rh : math.max(top, rh)
if not na(bot) and top - bot < 5000
int nrows = top - bot + 1
array<int> counts = array.new<int>(nrows, 0)
for i = 0 to np - 1
float ph = perH.get(i)
float pl = perL.get(i)
if not na(ph) and not na(pl)
int rl = f_row(pl, step) - bot
int rh = f_row(ph, step) - bot
for r = rl to rh
counts.set(r, counts.get(r) + 1)
int mx = counts.max()
float mid = (nrows - 1) / 2.0
int pr = -1
float best = na
for r = 0 to nrows - 1
if counts.get(r) == mx
float d = math.abs(r - mid)
if pr < 0 or d <= best
pr := r
best := d
int total = counts.sum()
int loR = pr
int hiR = pr
float acc = counts.get(pr)
while acc < 0.70 * total and (loR > 0 or hiR < nrows - 1)
int up = hiR < nrows - 1 ? counts.get(hiR + 1) : -1
int dn = loR > 0 ? counts.get(loR - 1) : -1
if up >= dn
hiR += 1
acc += up
else
loR -= 1
acc += dn
poc := math.round_to_mintick((bot + pr) * step)
vah := math.round_to_mintick((bot + hiR) * step)
val := math.round_to_mintick((bot + loR) * step)
[poc, vah, val]
// Closes the running session: its levels become the "prior session" ones.
method finish(Sess s) =>
if s.active
s.active := false
s.finished := s.finished + 1
float rng = s.h - s.l
[poc, vah, val] = f_profile(s.perH, s.perL, s.step)
float tr = na(s.pC) ? rng : math.max(rng, math.max(math.abs(s.h - s.pC), math.abs(s.l - s.pC)))
s.trs.push(tr)
if s.trs.size() > 20
s.trs.shift()
s.ranges.push(rng)
if s.ranges.size() > 60
s.ranges.shift()
s.atr := s.trs.size() >= 5 ? s.trs.avg() : na
s.nextStep := f_autoStep(s.ranges, s.rowTicks, rng)
s.pO := s.o
s.pH := s.h
s.pL := s.l
s.pC := s.c
s.pPOC := poc
s.pVAH := vah
s.pVAL := val
s.pStep := s.step
s.pDayKey := s.dayKey
s.pDow := s.lastDow
s.pStart := s.startTime
s.pPerH := s.perH.copy()
s.pPerL := s.perL.copy()
s.wH := na(s.wH) ? s.h : math.max(s.wH, s.h)
s.wL := na(s.wL) ? s.l : math.min(s.wL, s.l)
s.mH := na(s.mH) ? s.h : math.max(s.mH, s.h)
s.mL := na(s.mL) ? s.l : math.min(s.mL, s.l)
s.finished
// Opens a new session at the bar that starts at time t (off = minutes after the nominal session open).
method begin(Sess s, int t, int off, int key, int dow, float o) =>
bool first = s.lastDow == 0
bool newWeek = first or dow <= s.lastDow or t - s.startTime > 6 * 86400000
if newWeek
s.pwH := s.wPartial ? na : s.wH
s.pwL := s.wPartial ? na : s.wL
s.wPartial := first and dow != dayofweek.monday
s.wH := na
s.wL := na
s.wO := o
int mon = month(t, s.tz)
if mon != s.lastMonth
s.pmH := s.mPartial ? na : s.mH
s.pmL := s.mPartial ? na : s.mL
s.mPartial := first
s.mH := na
s.mL := na
s.mO := o
s.lastDow := dow
s.lastMonth := mon
s.dayKey := key
s.startTime := t - off * 60000
s.active := true
s.count := s.count + 1
s.o := o
s.h := na
s.l := na
s.c := na
s.orH := na
s.orL := na
s.orDone := false
s.ibH := na
s.ibL := na
s.ibDone := false
s.brkOrUp := false
s.brkOrDn := false
s.brkIbUp := false
s.brkIbDn := false
s.gapFilled := false
s.elapsed := 0
s.step := f_autoStep(s.ranges, s.rowTicks, na)
s.perH := array.new<float>()
s.perL := array.new<float>()
s.count
// One bar (or intrabar) that starts at time t and lasts dur minutes; done = the bar is complete.
method feed(Sess s, int t, int dur, bool done, float o, float h, float l, float c) =>
int mins = hour(t, s.tz) * 60 + minute(t, s.tz)
int dow = dayofweek(t, s.tz)
bool inWin = mins >= s.startMin and mins < s.endMin and dow != dayofweek.saturday and dow != dayofweek.sunday and not na(h) and not na(l)
int key = year(t, s.tz) * 10000 + month(t, s.tz) * 100 + dayofmonth(t, s.tz)
if s.active and (not inWin or key != s.dayKey)
s.finish()
if inWin
int off = mins - s.startMin
if key != s.dayKey
s.begin(t, off, key, dow, o)
s.h := na(s.h) ? h : math.max(s.h, h)
s.l := na(s.l) ? l : math.min(s.l, l)
s.c := c
s.elapsed := off + dur
// opening range: bars that start inside the window build it; the first bar after it fixes it
if off < s.orMin
s.orH := na(s.orH) ? h : math.max(s.orH, h)
s.orL := na(s.orL) ? l : math.min(s.orL, l)
else
s.orDone := true
if h > s.orH
s.brkOrUp := true
if l < s.orL
s.brkOrDn := true
if off < s.ibMin
s.ibH := na(s.ibH) ? h : math.max(s.ibH, h)
s.ibL := na(s.ibL) ? l : math.min(s.ibL, l)
else
s.ibDone := true
if h > s.ibH
s.brkIbUp := true
if l < s.ibL
s.brkIbDn := true
// gap against the previous session's last price: filled when price trades back at it
if not na(s.pC) and not s.gapFilled
if (s.o > s.pC and l <= s.pC) or (s.o < s.pC and h >= s.pC)
s.gapFilled := true
// highs and lows of the 30-minute periods (A = first 30 minutes)
int k = int(math.floor(off / 30))
while s.perH.size() <= k
s.perH.push(na)
s.perL.push(na)
float ph = s.perH.get(k)
float pl = s.perL.get(k)
s.perH.set(k, na(ph) ? h : math.max(ph, h))
s.perL.set(k, na(pl) ? l : math.min(pl, l))
// the bar that ends the window closes the session (once that bar is complete)
if done and s.elapsed >= s.endMin - s.startMin
s.finish()
s.count
// The deep-history context: prior-session levels, 20-session average true range of the regular session, row size,
// week and month references. Evaluated on a fixed timeframe so that a 1-minute chart has the same history as a
// 60-minute one. Everything it returns is final when the session it describes has ended.
f_ctx(int startMin, int endMin, string tz, int rowTicks, int dur) =>
var Sess s = f_newSess(startMin, endMin, tz, 60, 15, rowTicks)
s.feed(time, dur, barstate.isconfirmed, open, high, low, close)
[s.finished, s.pDayKey, s.pDow, s.lastMonth, s.pStart, s.pO, s.pH, s.pL, s.pC, s.pVAH, s.pVAL, s.pPOC, s.atr, s.trs.size(), s.pStep, s.nextStep, s.wO, s.wH, s.wL, s.pwH, s.pwL, s.wPartial, s.mO, s.mH, s.mL, s.pmH, s.pmL, s.mPartial]
// Timeframe of the deep-history context and of the intrabars: the coarsest of 15 / 5 / 1 minutes the session lines up with.
f_gridTf(int a, int b, int cap) =>
a % 15 == 0 and b % 15 == 0 and cap >= 15 ? 15 : a % 5 == 0 and b % 5 == 0 and cap >= 5 ? 5 : 1
// --- END SHARED CORE
// ------------------------------------------------------------------------------------------------------------ inputs
string G0 = "General"
string marketIn = input.string("Auto", "Mercado / Market", options = ["Auto", "ES", "NQ", "RTY", "YM", "NKD", "GC", "SI", "HG", "PL", "PA", "CL", "NG", "ZN", "ZB", "ZF", "ZT", "ZC", "ZS", "ZW", "6E", "6J", "6B", "6A", "6C", "6S", "6N", "6M", "BTC", "ETH"], group = G0)
bool sessAuto = input.bool(true, "Sesión según el mercado (la del perfil del portal)", group = G0)
string sessManual = input.session("0930-1600", "Sesión manual (HHMM-HHMM)", group = G0)
string tzManual = input.string("America/New_York", "Zona horaria de la sesión manual", group = G0)
string srcMode = input.string("Auto", "Datos para la sesión", options = ["Auto", "Velas del gráfico", "Intrabarras"], group = G0, tooltip = "Auto: usa las velas del gráfico cuando su temporalidad encaja con la apertura de la sesión y con los periodos de 30 minutos; si no encaja, usa intrabarras.")
int rowTicksIn = input.int(0, "Tamaño de fila en ticks (0 = automático)", minval = 0, group = G0)
int maxRows = input.int(150, "Máximo de filas por perfil", minval = 20, maxval = 240, group = G0, tooltip = "Si una sesión necesita más filas que este máximo, su perfil no se dibuja: sube el tamaño de fila.")
bool showPrev = input.bool(true, "Dibujar también la sesión anterior", group = G0)
bool showLetters = input.bool(false, "Letras de los periodos (A = primeros 30 minutos)", group = G0)
string G5 = "Colores / Colours"
color cPoc = input.color(color.new(#f59e0b, 20), "POC", group = G5)
color cIn = input.color(color.new(#a78bfa, 55), "Área de valor", group = G5)
color cOut = input.color(color.new(#8b98a8, 70), "Fuera del área de valor", group = G5)
color cTxt = input.color(#c9d1d9, "Letras", group = G5)
string root = marketIn == "Auto" ? f_parent(syminfo.root) : marketIn
string lvSpec = sessAuto ? f_lvSess(root) : sessManual
string lvTz = sessAuto ? f_lvTz(root) : tzManual
int lvStart = f_sessStart(lvSpec)
int lvEnd = f_sessEnd(lvSpec)
bool okTf = timeframe.isminutes and timeframe.multiplier <= 60
int mult = timeframe.multiplier
bool aligned = lvStart % mult == 0 and lvEnd % mult == 0 and 30 % mult == 0
bool useLtf = okTf and mult > 1 and (srcMode == "Intrabarras" or (srcMode == "Auto" and not aligned))
int ltfDur = f_gridTf(lvStart, lvEnd, mult - 1)
string ltfTf = str.tostring(ltfDur)
int ctxDur = f_gridTf(lvStart, lvEnd, 15)
string ctxTf = str.tostring(ctxDur)
// row size from the deep-history context (the same on a 1-minute chart as on a 60-minute one)
[cFin, cKey, cDow, cMon, cStart, cO, cH, cL, cC, cVAH, cVAL, cPOC, cAtr, cTrN, cStep, cNextStep, cWO, cWH, cWL, cPWH, cPWL, cWPartial, cMO, cMH, cML, cPMH, cPML, cMPartial] = request.security(syminfo.tickerid, ctxTf, f_ctx(lvStart, lvEnd, lvTz, rowTicksIn, ctxDur), lookahead = barmerge.lookahead_off)
var Sess lv = f_newSess(lvStart, lvEnd, lvTz, 60, 15, rowTicksIn)
int count0 = lv.count
int fin0 = lv.finished
if okTf
if useLtf
[lt, lo, lh, ll, lc] = request.security_lower_tf(syminfo.tickerid, ltfTf, [time, open, high, low, close])
int nl = lt.size()
if nl > 0
for i = 0 to nl - 1
bool done = i < nl - 1 or barstate.isconfirmed
lv.feed(lt.get(i), ltfDur, done, lo.get(i), lh.get(i), ll.get(i), lc.get(i))
else
lv.feed(time, mult, barstate.isconfirmed, open, high, low, close)
// the last two finished sessions (1 = the most recent) and the row size each was opened with
var float curStep = na
var array<float> h1 = array.new<float>()
var array<float> l1 = array.new<float>()
var float step1 = na
var int t1 = 0
var array<float> h2 = array.new<float>()
var array<float> l2 = array.new<float>()
var float step2 = na
var int t2 = 0
if lv.count != count0
curStep := na(cNextStep) ? lv.step : cNextStep
if lv.finished != fin0
h2 := h1
l2 := l1
step2 := step1
t2 := t1
h1 := lv.pPerH.copy()
l1 := lv.pPerL.copy()
step1 := curStep
t1 := lv.pStart
string LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
f_drawProfile(array<box> store, array<float> perH, array<float> perL, float step, int tStart) =>
int np = perH.size()
if np > 0 and not na(step) and step > 0
[poc, vah, val] = f_profile(perH, perL, step)
int bot = na
int top = na
for i = 0 to np - 1
float ph = perH.get(i)
float pl = perL.get(i)
if not na(ph) and not na(pl)
int rl = f_row(pl, step)
int rh = f_row(ph, step)
bot := na(bot) ? rl : math.min(bot, rl)
top := na(top) ? rh : math.max(top, rh)
if not na(bot) and not na(poc) and top - bot < maxRows
for r = bot to top
int cnt = 0
string txt = ""
for i = 0 to np - 1
float ph = perH.get(i)
float pl = perL.get(i)
if not na(ph) and not na(pl)
if r >= f_row(pl, step) and r <= f_row(ph, step)
cnt += 1
if showLetters and i < 26
txt += str.substring(LETTERS, i, i + 1)
if cnt > 0
float p0 = r * step
float pr = math.round_to_mintick(p0)
color bg = pr == poc ? cPoc : pr >= val and pr <= vah ? cIn : cOut
store.push(box.new(tStart, p0 + step, tStart + cnt * 30 * 60000, p0, xloc = xloc.bar_time, border_color = color.new(bg, 100), border_width = 1, bgcolor = bg, text = txt, text_size = size.tiny, text_color = cTxt, text_halign = text.align_left, text_valign = text.align_center))
store.size()
var array<box> boxes = array.new<box>()
var table note = table.new(position.bottom_right, 1, 1)
if barstate.islast
for b in boxes
b.delete()
boxes.clear()
if not okTf
table.cell(note, 0, 0, "Usa un gráfico de 1 a 60 minutos / use a chart of 1 to 60 minutes", text_color = cTxt, text_size = size.small)
else if lv.active
f_drawProfile(boxes, lv.perH, lv.perL, curStep, lv.startTime)
if showPrev
f_drawProfile(boxes, h1, l1, step1, t1)
else
f_drawProfile(boxes, h1, l1, step1, t1)
if showPrev
f_drawProfile(boxes, h2, l2, step2, t2)