本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Sessions Highs and Low Levels (Mitigation)", shorttitle="Sessions Highs and Low Levels (Mitigation)", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
// ───────────────────────── INPUTS ─────────────────────────
gV = "Configuración de visibilidad"
showUnm = input.bool(true, "Mostrar Líneas NO Mitigadas", group=gV)
showMit = input.bool(true, "Mostrar Líneas Mitigadas", group=gV)
maxUnm = input.int(200, "Máx. líneas Expuestas", minval=1, maxval=250, group=gV)
maxMit = input.int(200, "Máx. líneas Mitigadas", minval=1, maxval=250, group=gV)
mitCol = input.color(color.new(#b22833, 0), "Color Mitigada", group=gV)
tz = input.string("Europe/Madrid", "Zona horaria de los horarios", group=gV)
showBox = input.bool(true, "Mostrar cajas de sesión", group=gV)
lblOff = input.int(0, "Desplazamiento del final de línea (velas)", minval=0, maxval=50, group=gV)
gS = "Configuración sesiones"
showAsia = input.bool(true, "Asia", inline="a", group=gS)
colAsia = input.color(#7b1fa2, "", inline="a", group=gS)
sesAsia = input.session("2300-0700", "Horario", group=gS)
showLon = input.bool(true, "Londres", inline="l", group=gS)
colLon = input.color(#2962ff, "", inline="l", group=gS)
sesLon = input.session("0900-1300", "Horario", group=gS)
showNY = input.bool(true, "NY", inline="n", group=gS)
colNY = input.color(#d32f2f, "", inline="n", group=gS)
sesNY = input.session("1400-1800", "Horario", group=gS)
gH = "Configuración HTF"
showD = input.bool(true, "Diario", inline="d", group=gH)
colD = input.color(#787b86, "", inline="d", group=gH)
showW = input.bool(true, "Semanal", inline="w", group=gH)
colW = input.color(#787b86, "", inline="w", group=gH)
showM = input.bool(true, "Mensual", inline="m", group=gH)
colM = input.color(#787b86, "", inline="m", group=gH)
prevCol = input.color(color.white, "Color \"previous\" (PDH/PDL/PWH/PWL/PMH/PML)", group=gH)
mergeLv = input.bool(true, "Acumular niveles coincidentes (ej. LL/DL)", group=gH)
useSessCol = input.bool(true, "Niveles acumulados con sesión: usar color de la sesión", group=gH)
gP = "Perfil de volumen (POC / VAH / VAL)"
showVP = input.bool(false, "Mostrar VAH / VAL / POC", group=gP)
vpPeriod = input.string("Día actual", "Periodo del perfil", options=["Día actual", "Día anterior", "Semana anterior", "Mes anterior", "Rango de fechas"], group=gP, tooltip="Día actual: perfil en desarrollo. Día/Semana/Mes anterior: perfil completo del periodo ya terminado, dibujado hasta la vela actual. Rango de fechas: usa las fechas de inicio y fin de abajo.")
vpStartT = input.time(timestamp("1 Nov 2026 00:00 +0100"), "Fecha inicio (Rango de fechas)", group=gP)
vpEndT = input.time(timestamp("14 Nov 2026 00:00 +0100"), "Fecha fin (Rango de fechas)", group=gP, tooltip="La fecha fin no se incluye. Para incluir un día completo, pon el día siguiente a las 00:00.")
vpMode = input.string("Día completo", "Filtro horario (rango de tiempo)", options=["Día completo", "Asia", "Londres", "NY", "Personalizado"], group=gP, tooltip="Solo cuentan las velas dentro de este horario. Asia, Londres y NY usan los horarios de 'Configuración sesiones'. En 'Día actual', además, el perfil se reinicia al empezar cada rango ('Día completo' empieza a las 00:00 de la zona horaria elegida).")
sesCustom = input.session("0800-1800", "Horario personalizado", group=gP)
vpRows = input.int(70, "Filas del perfil", minval=10, maxval=300, group=gP)
vaPct = input.float(70, "Área de valor (%)", minval=10, maxval=99, step=1, group=gP)
pocCol = input.color(#ffd600, "POC", inline="poc", group=gP)
pocW = input.int(1, "Grosor", minval=1, maxval=4, inline="poc", group=gP)
vahCol = input.color(#4dd0e1, "VAH", inline="vah", group=gP)
vahW = input.int(1, "Grosor", minval=1, maxval=4, inline="vah", group=gP)
valCol = input.color(#4dd0e1, "VAL", inline="val", group=gP)
valW = input.int(1, "Grosor", minval=1, maxval=4, inline="val", group=gP)
vpStyleS = input.string("Continua", "Estilo de línea", options=["Continua", "Discontinua", "Punteada"], group=gP)
vpLabels = input.bool(true, "Mostrar etiquetas (POC / VAH / VAL)", group=gP)
keepPrev = input.bool(false, "Conservar periodos anteriores (solo 'Día actual')", group=gP)
maxPrev = input.int(5, "Máx. periodos anteriores", minval=1, maxval=30, group=gP)
// ───────────────────────── TIPOS ─────────────────────────
// Estado de cada parte HTF: 0 = no aplica, 1 = "previous" (PDH...), 2 = normal (DH...)
type Lvl
line ln
label lb
float price
bool isHigh
string sTxt
color sCol
color hCol
int hRank
int dSt
int wSt
int mSt
type Sess
box bx
float hi
float lo
int hiBar
int loBar
type HTF
float hi
float lo
int hiB
int loB
bool full
var array<Lvl> unmit = array.new<Lvl>()
var array<Lvl> mit = array.new<Lvl>()
var Sess asia = Sess.new()
var Sess lon = Sess.new()
var Sess ny = Sess.new()
var HTF dT = HTF.new()
var HTF wT = HTF.new()
var HTF mT = HTF.new()
// ───────────────────────── FUNCIONES ─────────────────────────
joinTxt(string a, string b) =>
a == "" ? b : (b == "" ? a : a + "/" + b)
getSt(Lvl l, int tf) =>
tf == 1 ? l.dSt : tf == 2 ? l.wSt : l.mSt
setSt(Lvl l, int tf, int st) =>
if tf == 1
l.dSt := st
else if tf == 2
l.wSt := st
else
l.mSt := st
true
lvlText(Lvl l) =>
string hl = l.isHigh ? "H" : "L"
string t = l.sTxt
t := joinTxt(t, l.dSt == 0 ? "" : (l.dSt == 1 ? "PD" : "D") + hl)
t := joinTxt(t, l.wSt == 0 ? "" : (l.wSt == 1 ? "PW" : "W") + hl)
t := joinTxt(t, l.mSt == 0 ? "" : (l.mSt == 1 ? "PM" : "M") + hl)
t
lvlColor(Lvl l) =>
bool hasH = l.dSt > 0 or l.wSt > 0 or l.mSt > 0
bool isPrev = l.dSt == 1 or l.wSt == 1 or l.mSt == 1
color c = isPrev ? prevCol : (hasH ? ((l.sTxt != "" and useSessCol) ? l.sCol : l.hCol) : l.sCol)
c
restyle(Lvl l) =>
color c = lvlColor(l)
line.set_color(l.ln, showUnm ? c : na)
label.set_text(l.lb, showUnm ? lvlText(l) : "")
label.set_textcolor(l.lb, c)
true
// Al empezar un nuevo día/semana/mes, lo que era "previous" pasa a ser normal
demote(int tf) =>
if unmit.size() > 0
for i = 0 to unmit.size() - 1
Lvl l = unmit.get(i)
if getSt(l, tf) == 1
setSt(l, tf, 2)
restyle(l)
if mit.size() > 0
for j = 0 to mit.size() - 1
Lvl m = mit.get(j)
if getSt(m, tf) == 1
setSt(m, tf, 2)
label.set_text(m.lb, lvlText(m))
true
mergeInto(Lvl l, int x1, string txt, color col, int rank) =>
if rank > 0
setSt(l, rank, 1)
if rank > l.hRank
l.hCol := col
l.hRank := rank
else
if l.sTxt == ""
l.sCol := col
l.sTxt := joinTxt(l.sTxt, txt)
int nx = math.min(line.get_x1(l.ln), x1)
line.set_x1(l.ln, nx)
restyle(l)
true
// rank: 0 = nivel de sesión; 1 = diario, 2 = semanal, 3 = mensual
addLevel(float price, bool isHigh, int x1, string txt, color col, int rank) =>
bool merged = false
if mergeLv and unmit.size() > 0
for i = 0 to unmit.size() - 1
Lvl l = unmit.get(i)
if not merged and l.isHigh == isHigh and math.abs(l.price - price) <= syminfo.mintick * 0.5
mergeInto(l, x1, txt, col, rank)
merged := true
if not merged
line ln = line.new(x1, price, x1 + 1, price, xloc.bar_index, extend.none, col, line.style_solid, 1)
// Etiqueta a la derecha del final de la línea, centrada en el precio (margen fijo en píxeles)
label lb = label.new(bar_index, price, txt, xloc.bar_index, yloc.price, color.new(color.black, 100), label.style_label_left, col, size.small)
Lvl nl = Lvl.new(ln, lb, price, isHigh, rank > 0 ? "" : txt, col, col, rank, 0, 0, 0)
if rank > 0
setSt(nl, rank, 1)
restyle(nl)
unmit.push(nl)
if unmit.size() > maxUnm
Lvl old = unmit.shift()
line.delete(old.ln)
label.delete(old.lb)
true
checkMitigation() =>
int i = unmit.size() - 1
while i >= 0
Lvl l = unmit.get(i)
bool hit = l.isHigh ? high > l.price : low < l.price
if hit
unmit.remove(i)
if showMit
int x1 = line.get_x1(l.ln)
int x2 = math.max(bar_index, x1 + 1)
line.set_x2(l.ln, x2)
line.set_style(l.ln, line.style_dashed)
line.set_color(l.ln, mitCol)
label.set_style(l.lb, l.isHigh ? label.style_label_down : label.style_label_up)
label.set_x(l.lb, math.round((x1 + x2) / 2.0))
label.set_text(l.lb, lvlText(l))
label.set_textcolor(l.lb, mitCol)
mit.push(l)
if mit.size() > maxMit
Lvl old = mit.shift()
line.delete(old.ln)
label.delete(old.lb)
else
line.delete(l.ln)
label.delete(l.lb)
i -= 1
true
// Los niveles NO mitigados llegan hasta la vela actual y su etiqueta
// queda justo a la derecha del final de la línea
moveEnds() =>
if unmit.size() > 0
for i = 0 to unmit.size() - 1
Lvl l = unmit.get(i)
int xe = bar_index + lblOff
line.set_x2(l.ln, math.max(xe, line.get_x1(l.ln) + 1))
label.set_x(l.lb, xe)
true
updateSession(Sess s, bool enabled, bool inS, bool prevIn, color col, string hT, string lT) =>
if enabled
if inS and not prevIn
s.hi := high
s.lo := low
s.hiBar := bar_index
s.loBar := bar_index
if showBox
s.bx := box.new(bar_index, high, bar_index, low, border_color=color.new(col, 70), bgcolor=color.new(col, 90))
else if inS
if high > s.hi
s.hi := high
s.hiBar := bar_index
if low < s.lo
s.lo := low
s.loBar := bar_index
if showBox
box.set_right(s.bx, bar_index)
box.set_top(s.bx, s.hi)
box.set_bottom(s.bx, s.lo)
else if prevIn
addLevel(s.hi, true, s.hiBar, hT, col, 0)
addLevel(s.lo, false, s.loBar, lT, col, 0)
true
// Sigue el máximo/mínimo del periodo HTF en curso y, al cambiar de periodo,
// dibuja los niveles del periodo anterior (como "previous") desde la vela exacta del extremo
updateHTF(HTF t, bool enabled, bool newP, color col, int rank) =>
if newP
bool had = not na(t.hi)
demote(rank)
if enabled and t.full
addLevel(t.hi, true, t.hiB, "", col, rank)
addLevel(t.lo, false, t.loB, "", col, rank)
t.hi := high
t.lo := low
t.hiB := bar_index
t.loB := bar_index
t.full := had
else
if na(t.hi)
t.hi := high
t.lo := low
t.hiB := bar_index
t.loB := bar_index
t.full := false
else
if high > t.hi
t.hi := high
t.hiB := bar_index
if low < t.lo
t.lo := low
t.loB := bar_index
true
// Perfil de volumen: reparte el volumen de cada vela entre las filas que cubre su rango,
// calcula el POC y expande el área de valor desde el POC hasta el % indicado
calcProfile(array<float> hA, array<float> lA, array<float> vA, int rows, float vaP) =>
float top = array.max(hA)
float bot = array.min(lA)
float rng = top - bot
int nr = rng <= 0 ? 1 : rows
float rh = rng <= 0 ? syminfo.mintick : rng / nr
array<float> vol = array.new_float(nr, 0.0)
for k = 0 to hA.size() - 1
float h = hA.get(k)
float l = lA.get(k)
float v = vA.get(k)
int i0 = math.max(0, math.min(nr - 1, int(math.floor((l - bot) / rh))))
int i1 = math.max(0, math.min(nr - 1, int(math.floor((h - bot) / rh))))
if i0 == i1 or h - l <= 0
vol.set(i0, vol.get(i0) + v)
else
for r = i0 to i1
float rLo = bot + r * rh
float rHi = rLo + rh
float ov = math.min(h, rHi) - math.max(l, rLo)
if ov > 0
vol.set(r, vol.get(r) + v * ov / (h - l))
int poc = array.indexof(vol, array.max(vol))
float target = array.sum(vol) * vaP / 100
int up = poc
int dn = poc
float acc = vol.get(poc)
while acc < target and (up < nr - 1 or dn > 0)
float upV = (up + 1 <= nr - 1 ? vol.get(up + 1) : 0.0) + (up + 2 <= nr - 1 ? vol.get(up + 2) : 0.0)
float dnV = (dn - 1 >= 0 ? vol.get(dn - 1) : 0.0) + (dn - 2 >= 0 ? vol.get(dn - 2) : 0.0)
if upV >= dnV and up < nr - 1
up := math.min(up + 2, nr - 1)
acc += upV
else
dn := math.max(dn - 2, 0)
acc += dnV
[bot + (poc + 0.5) * rh, bot + (up + 1) * rh, bot + dn * rh]
// ───────────────────────── SESIONES ─────────────────────────
bool intraday = timeframe.isintraday
bool asiaIn = intraday and not na(time(timeframe.period, sesAsia, tz))
bool lonIn = intraday and not na(time(timeframe.period, sesLon, tz))
bool nyIn = intraday and not na(time(timeframe.period, sesNY, tz))
updateSession(asia, showAsia, asiaIn, asiaIn[1], colAsia, "AH", "AL")
updateSession(lon, showLon, lonIn, lonIn[1], colLon, "LH", "LL")
updateSession(ny, showNY, nyIn, nyIn[1], colNY, "NYH", "NYL")
// ───────────────────────── HTF ─────────────────────────
bool newD = timeframe.change("D")
bool newW = timeframe.change("W")
bool newM = timeframe.change("M")
updateHTF(dT, showD, newD, colD, 1)
updateHTF(wT, showW, newW, colW, 2)
updateHTF(mT, showM, newM, colM, 3)
// ───────────────────────── MITIGACIÓN ─────────────────────────
// Después de crear los niveles, para detectar roturas en la propia vela de creación
checkMitigation()
// ───────────────────────── PERFIL DE VOLUMEN (POC / VAH / VAL) ─────────────────────────
var array<float> bH = array.new_float()
var array<float> bL = array.new_float()
var array<float> bV = array.new_float()
var int pStart = na
var bool pActive = false
var bool pvHas = false
var int pvStart = na
var float pvP = na
var float pvH = na
var float pvL = na
var line lP = na
var line lH = na
var line lL = na
var label tP = na
var label tH = na
var label tL = na
var array<line> prevLines = array.new<line>()
string vpSty = vpStyleS == "Continua" ? line.style_solid : vpStyleS == "Discontinua" ? line.style_dashed : line.style_dotted
string sesStr = vpMode == "Asia" ? sesAsia : vpMode == "Londres" ? sesLon : vpMode == "NY" ? sesNY : sesCustom
bool fullDay = vpMode == "Día completo"
bool vpSes = intraday and not na(time(timeframe.period, sesStr, tz))
int dayNow = dayofmonth(time, tz)
int dayPrev = dayofmonth(time[1], tz)
bool modeCur = vpPeriod == "Día actual"
bool modeCus = vpPeriod == "Rango de fechas"
bool modePrv = not modeCur and not modeCus
string lblPre = vpPeriod == "Día anterior" ? "PD " : vpPeriod == "Semana anterior" ? "PW " : vpPeriod == "Mes anterior" ? "PM " : ""
bool chgPrv = vpPeriod == "Día anterior" ? newD : vpPeriod == "Semana anterior" ? newW : newM
bool winIn = fullDay ? true : vpSes
bool inCus = time >= vpStartT and time < vpEndT and winIn
bool vpIn = fullDay ? intraday : vpSes
bool vpStart = fullDay ? (intraday and (bar_index == 0 or dayNow != dayPrev)) : (vpSes and not vpSes[1])
bool vpEnd = fullDay ? (vpStart and bar_index > 0) : (not vpSes and vpSes[1])
// Valores a dibujar en la última vela
float dP = na
float dH = na
float dL = na
int dS = na
if showVP
if modeCur
// Día actual: perfil en desarrollo que se reinicia al empezar cada rango
// Fin del periodo: se retiran las líneas "en vivo" y, si se pide, se conservan sus valores finales
if vpEnd and pActive
if not na(lP)
line.delete(lP)
line.delete(lH)
line.delete(lL)
label.delete(tP)
label.delete(tH)
label.delete(tL)
lP := na
lH := na
lL := na
tP := na
tH := na
tL := na
if keepPrev and bH.size() > 0
[fp, fh, fl] = calcProfile(bH, bL, bV, vpRows, vaPct)
int fe = math.max(bar_index - 1, pStart + 1)
prevLines.push(line.new(pStart, fp, fe, fp, xloc.bar_index, extend.none, pocCol, vpSty, pocW))
prevLines.push(line.new(pStart, fh, fe, fh, xloc.bar_index, extend.none, vahCol, vpSty, vahW))
prevLines.push(line.new(pStart, fl, fe, fl, xloc.bar_index, extend.none, valCol, vpSty, valW))
while prevLines.size() > maxPrev * 3
line.delete(prevLines.shift())
pActive := false
// Inicio del periodo: se reinicia el perfil
if vpStart
bH.clear()
bL.clear()
bV.clear()
pStart := bar_index
pActive := true
// Acumulación de datos de cada vela dentro del rango
if vpIn and pActive
bH.push(high)
bL.push(low)
bV.push(nz(volume) > 0 ? volume : 1.0)
if barstate.islast and pActive and vpIn and bH.size() > 0
[cp, ch, cl] = calcProfile(bH, bL, bV, vpRows, vaPct)
dP := cp
dH := ch
dL := cl
dS := pStart
else if modePrv
// Día / semana / mes anterior: se calcula el perfil completo del periodo terminado
if chgPrv
if bH.size() > 0
[qp, qh, ql] = calcProfile(bH, bL, bV, vpRows, vaPct)
pvP := qp
pvH := qh
pvL := ql
pvStart := pStart
pvHas := true
bH.clear()
bL.clear()
bV.clear()
pStart := bar_index
if na(pStart)
pStart := bar_index
if winIn
bH.push(high)
bL.push(low)
bV.push(nz(volume) > 0 ? volume : 1.0)
if barstate.islast and pvHas
dP := pvP
dH := pvH
dL := pvL
dS := pvStart
else
// Rango de fechas personalizado
if inCus
if bH.size() == 0
pStart := bar_index
bH.push(high)
bL.push(low)
bV.push(nz(volume) > 0 ? volume : 1.0)
if barstate.islast and bH.size() > 0
[ap, ah, al] = calcProfile(bH, bL, bV, vpRows, vaPct)
dP := ap
dH := ah
dL := al
dS := pStart
// Líneas rectas: del inicio del periodo a la vela actual, en el valor del perfil
if barstate.islast and not na(dP)
int xe = bar_index + lblOff
int xs = dS
int xr = math.max(xe, xs + 1)
if na(lP)
lP := line.new(xs, dP, xr, dP, xloc.bar_index, extend.none, pocCol, vpSty, pocW)
lH := line.new(xs, dH, xr, dH, xloc.bar_index, extend.none, vahCol, vpSty, vahW)
lL := line.new(xs, dL, xr, dL, xloc.bar_index, extend.none, valCol, vpSty, valW)
tP := label.new(xr, dP, vpLabels ? lblPre + "POC" : "", xloc.bar_index, yloc.price, color.new(color.black, 100), label.style_label_left, pocCol, size.small)
tH := label.new(xr, dH, vpLabels ? lblPre + "VAH" : "", xloc.bar_index, yloc.price, color.new(color.black, 100), label.style_label_left, vahCol, size.small)
tL := label.new(xr, dL, vpLabels ? lblPre + "VAL" : "", xloc.bar_index, yloc.price, color.new(color.black, 100), label.style_label_left, valCol, size.small)
else
line.set_xy1(lP, xs, dP)
line.set_xy2(lP, xr, dP)
line.set_xy1(lH, xs, dH)
line.set_xy2(lH, xr, dH)
line.set_xy1(lL, xs, dL)
line.set_xy2(lL, xr, dL)
label.set_xy(tP, xr, dP)
label.set_xy(tH, xr, dH)
label.set_xy(tL, xr, dL)
// ───────────────────────── FINAL DE LÍNEAS Y ETIQUETAS ─────────────────────────
if barstate.islast
moveEnds()