// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https\://mozilla.org/MPL/2.0/ // © IbraShipping //@version=6 indicator("DOMENEC UNIFICADO · Cintas, MTF, FVG y 500 velas", shorttitle="DOC UNIFICADO", overlay=true, max_bars_back=3000, max_lines_count=500, max_labels_count=500, max_boxes_count=500) // Integración del código aportado por el usuario. // Las reglas añadidas de gestión son orientativas. // No son reglas oficiales verificadas de Domènec. // ── Visibilidad original ── ug_verGenial = input.bool(true, "Mostrar Genial", group="VISIBILIDAD ORIGINAL") ug_verZona = input.bool(true, "Mostrar zona de corrección", group="VISIBILIDAD ORIGINAL") ug_colores = input.bool(true, "Colorear velas con Control Total", group="VISIBILIDAD ORIGINAL") ug_verDivergencias = input.bool(true, "Mostrar divergencias", group="VISIBILIDAD ORIGINAL") ug_verAgotamiento = input.bool(true, "Mostrar agotamiento", group="VISIBILIDAD ORIGINAL") ug_avisosAlCierre = input.bool(true, "Confirmar dibujos de Multiavisos al cierre", group="VISIBILIDAD ORIGINAL") ug_puedeDibujar = not ug_avisosAlCierre or barstate.isconfirmed // ── Funciones ── dema(source, length) => ema1 = ta.ema(source, length) ema2 = ta.ema(ema1, length) 2 * ema1 - ema2 f_wwma(length, source) => value = 0.0 value := (nz(value[1]) * (length - 1) + source) / length value dirmov(length) => up = ta.change(high) down = -ta.change(low) plusDM = na(up) ? na : (up > down and up > 0 ? up : 0) minusDM = na(down) ? na : (down > up and down > 0 ? down : 0) truerange = ta.rma(ta.tr, length) plus = fixnan(100 * ta.rma(plusDM, length) / truerange) minus = fixnan(100 * ta.rma(minusDM, length) / truerange) [plus, minus] f_adx(length, smoothing) => [plus, minus] = dirmov(length) total = plus + minus 100 * ta.rma(math.abs(plus - minus) / (total == 0 ? 1 : total), smoothing) // ── Túnel Domènec ── src = input.source(close, "Fuente EMA", group="TUNEL DOMENEC") periodoEMA = input.int(8, "EMA-8", minval=1, group="TUNEL DOMENEC") VelasBanda = 20 Desviacio = 3.14159265358979 var SmoothPrice = close var SmoothRange = 0.0 if bar_index > 1 SmoothPrice := (SmoothPrice[1] * (VelasBanda - 1) + close) / VelasBanda SmoothRange := (SmoothRange[1] * (VelasBanda - 1) + high - low) / VelasBanda Alt1 = SmoothPrice + SmoothRange * Desviacio Baix1 = SmoothPrice - SmoothRange * Desviacio Mitjana = (Alt1 + Baix1) / 2 Alt = dema(Alt1, VelasBanda) Baix = dema(Baix1, VelasBanda) c9 = (Mitjana + ta.sma(close, 34)) / 2 colorGenial = c9 > c9[1] ? color.blue : color.red // Bandas originales del Túnel Domènec (calculadas arriba, ahora visibles). ug_verBandas = input.bool(false, "Mostrar canal superior/central/inferior (opcional)", group="TUNEL DOMENEC") ug_rellenoBandas = input.bool(true, "Sombrear canal de bandas", group="TUNEL DOMENEC") ug_colorAlt = color.new(color.aqua, 0) ug_colorMed = color.new(color.silver, 0) ug_colorBaix = color.new(color.orange, 0) ug_plAlt = plot(ug_verBandas ? Alt : na, title="TÚNEL · Banda superior", color=ug_colorAlt, linewidth=2) ug_plMed = plot(ug_verBandas ? Mitjana : na, title="TÚNEL · Banda central", color=ug_colorMed, linewidth=2) ug_plBaix = plot(ug_verBandas ? Baix : na, title="TÚNEL · Banda inferior", color=ug_colorBaix, linewidth=2) fill(ug_plAlt, ug_plBaix, color=ug_verBandas and ug_rellenoBandas ? color.new(color.teal, 94) : na, title="TÚNEL · Canal") // ── TRES CINTAS DE COLORES ── // Ajuste para aproximarse mejor a la 2ª captura del usuario: // la zona de corrección se mantiene aparte y las cintas se desplazan a medias más lentas. ug_verCintas = input.bool(true, "Mostrar 3 cintas azul/amarilla/rosa", group="CINTAS · RECONSTRUCCIÓN") ug_cintaAzul1 = input.int(21, "Azul · EMA rápida", minval=1, group="CINTAS · RECONSTRUCCIÓN") ug_cintaAzul2 = input.int(34, "Azul · EMA lenta", minval=1, group="CINTAS · RECONSTRUCCIÓN") ug_cintaAma1 = input.int(55, "Amarilla · EMA rápida", minval=1, group="CINTAS · RECONSTRUCCIÓN") ug_cintaAma2 = input.int(89, "Amarilla · EMA lenta", minval=1, group="CINTAS · RECONSTRUCCIÓN") ug_cintaRos1 = input.int(120, "Rosa · EMA rápida", minval=1, group="CINTAS · RECONSTRUCCIÓN") ug_cintaRos2 = input.int(160, "Rosa · EMA lenta", minval=1, group="CINTAS · RECONSTRUCCIÓN") ug_cintaOpac = input.int(83, "Transparencia cintas", minval=0, maxval=95, group="CINTAS · RECONSTRUCCIÓN") ug_colorAzul = color.rgb(42, 97, 255) ug_colorAma = color.rgb(214, 179, 36) ug_colorRos = color.rgb(195, 20, 110) ug_a1 = plot(ug_verCintas ? ta.ema(close, ug_cintaAzul1) : na, title="CINTA AZUL rápida", color=color.new(ug_colorAzul, 10), linewidth=1) ug_a2 = plot(ug_verCintas ? ta.ema(close, ug_cintaAzul2) : na, title="CINTA AZUL lenta", color=color.new(ug_colorAzul, 10), linewidth=1) fill(ug_a1, ug_a2, color=ug_verCintas ? color.new(ug_colorAzul, ug_cintaOpac) : na, title="CINTA AZUL") ug_y1 = plot(ug_verCintas ? ta.ema(close, ug_cintaAma1) : na, title="CINTA AMARILLA rápida", color=color.new(ug_colorAma, 8), linewidth=1) ug_y2 = plot(ug_verCintas ? ta.ema(close, ug_cintaAma2) : na, title="CINTA AMARILLA lenta", color=color.new(ug_colorAma, 8), linewidth=1) fill(ug_y1, ug_y2, color=ug_verCintas ? color.new(ug_colorAma, ug_cintaOpac) : na, title="CINTA AMARILLA") ug_r1 = plot(ug_verCintas ? ta.ema(close, ug_cintaRos1) : na, title="CINTA ROSA rápida", color=color.new(ug_colorRos, 8), linewidth=1) ug_r2 = plot(ug_verCintas ? ta.ema(close, ug_cintaRos2) : na, title="CINTA ROSA lenta", color=color.new(ug_colorRos, 8), linewidth=1) fill(ug_r1, ug_r2, color=ug_verCintas ? color.new(ug_colorRos, ug_cintaOpac) : na, title="CINTA ROSA") // Genial Line de otros marcos. Se reconstruye con la misma fórmula original. // El desplazamiento [1] dentro de security devuelve la ÚLTIMA vela macro cerrada. f_genialMacro() => var float sp = na var float sr = 0.0 sp := na(sp[1]) ? close : (sp[1] * 19 + close) / 20 sr := na(sr[1]) ? 0.0 : (sr[1] * 19 + high - low) / 20 float genial = (sp + ta.sma(close, 34)) / 2 [genial[1], genial[2], close[1]] ug_verMacro = input.bool(true, "Dibujar Genial macro", group="GENIAL MULTITEMPORAL") ug_macroSem = input.bool(true, "Línea semanal", group="GENIAL MULTITEMPORAL") ug_macroDia = input.bool(true, "Línea diaria", group="GENIAL MULTITEMPORAL") ug_macro4h = input.bool(true, "Línea 4 horas", group="GENIAL MULTITEMPORAL") [ug_gW, ug_gWprev, ug_cW] = request.security(syminfo.tickerid, "1W", f_genialMacro(), lookahead=barmerge.lookahead_on) [ug_gD, ug_gDprev, ug_cD] = request.security(syminfo.tickerid, "1D", f_genialMacro(), lookahead=barmerge.lookahead_on) [ug_gH, ug_gHprev, ug_cH] = request.security(syminfo.tickerid, "240", f_genialMacro(), lookahead=barmerge.lookahead_on) plot(ug_verMacro and ug_macroSem ? ug_gW : na, "GENIAL · Semanal confirmada", color=color.fuchsia, linewidth=3, style=plot.style_stepline) plot(ug_verMacro and ug_macroDia ? ug_gD : na, "GENIAL · Diaria confirmada", color=color.yellow, linewidth=2, style=plot.style_stepline) plot(ug_verMacro and ug_macro4h ? ug_gH : na, "GENIAL · 4H confirmada", color=color.aqua, linewidth=2, style=plot.style_stepline) f_macroDireccion(float actual, float anterior) => na(actual) or na(anterior) ? "Sin datos" : actual > anterior ? "Sube" : actual < anterior ? "Baja" : "Lateral" f_macroPosicion(float precio, float nivel) => na(precio) or na(nivel) ? "—" : precio > nivel ? "Encima" : precio < nivel ? "Debajo" : "En línea" plot(ug_verGenial ? c9 : na, color=colorGenial, style=plot.style_cross, join=false, linewidth=2, title="GENIAL LINE") ema8 = ta.ema(src, periodoEMA) wilder8 = f_wwma(8, close) fillColor = ema8 > wilder8 ? color.new(color.green, 75) : color.new(color.red, 75) plotEMA = plot(ug_verZona ? ema8 : na, color=fillColor, linewidth=2, title="EMA 8 ZONA CORRECCION") plotWilder = plot(ug_verZona ? wilder8 : na, color=color.rgb(133, 56, 5), linewidth=2, style=plot.style_circles, title="Wilder 8 ZONA CORRECCION") fill(plotEMA, plotWilder, color=fillColor, title="ZONA CORRECCION") // ── Control Total ── periodoWilliams = input.int(40, "Período Williams %R", minval=1, group="CONTROL TOTAL") adxlen = input.int(7, "ADX Smoothing", minval=1, group="CONTROL TOTAL") wpr = ta.wpr(periodoWilliams) sigADX = f_adx(adxlen, adxlen) // Se conserva el orden de los colores originales. colorVela = color.rgb(128, 128, 128) if wpr < -50 and sigADX >= sigADX[1] and wpr > wpr[1] colorVela := color.rgb(0, 255, 0) if wpr > -50 and wpr < -27 and sigADX >= sigADX[1] and wpr > wpr[1] colorVela := color.rgb(120, 185, 70) if wpr > -27 and sigADX >= sigADX[1] and wpr > wpr[1] colorVela := color.rgb(70, 100, 70) if wpr > -50 and sigADX <= sigADX[1] and wpr < wpr[1] colorVela := color.rgb(255, 250, 0) if wpr < -50 and sigADX <= sigADX[1] and wpr < wpr[1] colorVela := color.rgb(250, 140, 0) if wpr > -50 and sigADX >= sigADX[1] and wpr < wpr[1] colorVela := color.rgb(255, 0, 0) if wpr < -50 and wpr > -72 and sigADX >= sigADX[1] and wpr < wpr[1] colorVela := color.rgb(210, 60, 130) if wpr < -72 and sigADX >= sigADX[1] and wpr < wpr[1] colorVela := color.rgb(100, 40, 50) if wpr < -50 and sigADX <= sigADX[1] and wpr > wpr[1] colorVela := color.rgb(0, 255, 255) if wpr > -50 and sigADX <= sigADX[1] and wpr > wpr[1] colorVela := color.rgb(30, 180, 230) cruceBajista = ta.crossunder(wpr, -50) cruceAlcista = ta.crossover(wpr, -50) if cruceBajista colorVela := color.rgb(255, 0, 255) if cruceAlcista colorVela := color.rgb(0, 0, 150) barcolor(ug_colores ? colorVela : na) // ── Multiavisos: parámetros ── N = input.int(25, "Periodos Divergencias", minval=1, maxval=2500, group="MULTIAVISOS") demaR = input.int(5, "DEMA Period r", minval=1, group="MULTIAVISOS") q = input.int(3, "DEMA Period q", minval=1, group="MULTIAVISOS") p = input.int(8, "Highest/Lowest Period", minval=1, group="MULTIAVISOS") Indicarmaxmin = input.bool(false, "Indicar Max/Min", group="MULTIAVISOS") IndicarCorreccion = input.bool(false, "Indicar Correccion", group="MULTIAVISOS") periode = input.int(30, "Periodo Cond1", minval=1, group="MULTIAVISOS") permitjdesv = input.int(120, "Periodo Desviacion", minval=1, group="MULTIAVISOS") ClaridaddeGrafico = input.int(2, "Claridad del grafico", minval=1, group="MULTIAVISOS") Usecajastoploss = input.bool(false, "Usar Cajas Stop Loss", group="MULTIAVISOS") sigmaALMA = input.int(4, "Sig ALMA", minval=1, group="MULTIAVISOS") Offs = input.float(0.85, "Offs ALMA", minval=0, maxval=1, group="MULTIAVISOS") fa = input.int(15, "fa ALMA", minval=1, maxval=2500, group="MULTIAVISOS") Sl = input.int(25, "Sl ALMA", minval=1, maxval=2500, group="MULTIAVISOS") Transparencia = input.int(70, "Transparencia Cajas", minval=0, maxval=100, group="MULTIAVISOS") AjusteSLatr = input.float(1.5, "Ajuste SL ATR", minval=0, group="MULTIAVISOS") NumVelasEst = input.int(3, "Num Velas Est", minval=1, maxval=2500, group="MULTIAVISOS") maximo = ta.highest(high, p) minimo = ta.lowest(low, p) rango = maximo - minimo oscilador = rango != 0 ? (close - minimo) / rango * 100 : 50.0 Oscilador1 = dema(oscilador, q) varoscil = dema(Oscilador1, demaR) // ── Divergencias ── maxOscAnterior = ta.highest(Oscilador1[2], N) minOscAnterior = ta.lowest(Oscilador1[2], N) maxPrecioAnterior = ta.highest(close[2], N) minPrecioAnterior = ta.lowest(close[2], N) if ug_verDivergencias and ug_puedeDibujar and bar_index > 11 + N if Oscilador1[1] > Oscilador1 and Oscilador1[1] > Oscilador1[2] if Oscilador1[1] < maxOscAnterior and close[1] > maxPrecioAnterior int indiceMax = na for i = 2 to N + 1 if close[i] == maxPrecioAnterior indiceMax := i break if not na(indiceMax) line.new(bar_index - indiceMax, close[indiceMax], bar_index - 1, close[1], color=color.rgb(180, 0, 0), width=1) if Oscilador1[1] < Oscilador1 and Oscilador1[1] < Oscilador1[2] if Oscilador1[1] > minOscAnterior and close[1] < minPrecioAnterior int indiceMin = na for i = 2 to N + 1 if close[i] == minPrecioAnterior indiceMin := i break if not na(indiceMin) line.new(bar_index - indiceMin, close[indiceMin], bar_index - 1, close[1], color=color.rgb(0, 150, 0), width=1) // ── Máximos, mínimos y correcciones ── desplazamiento = syminfo.mintick / ClaridaddeGrafico / 0.2 max80 = ta.highest(high, 80) min80 = ta.lowest(low, 80) ZC = ta.ema(close, 15) if Indicarmaxmin and ug_puedeDibujar if high >= max80 label.new(bar_index, high + 3 * desplazamiento, "Ma", style=label.style_label_down, color=color.rgb(0, 0, 200), textcolor=color.white) if low <= min80 label.new(bar_index, low - 3 * desplazamiento, "Mi", style=label.style_label_down, color=color.rgb(250, 0, 0), textcolor=color.white) if IndicarCorreccion and ug_puedeDibujar if close > ZC and close[1] > close[2] and close[2] > close[3] and close < close[1] label.new(bar_index, high + 6 * desplazamiento, "▼", style=label.style_label_down, color=color.rgb(250, 0, 0), textcolor=color.white) if close < ZC and close[1] < close[2] and close[2] < close[3] and close > close[1] label.new(bar_index, low - 6 * desplazamiento, "▲", style=label.style_label_up, color=color.rgb(0, 0, 150), textcolor=color.white) // ── Agotamiento ── maxCierre = ta.highest(close, periode) Cond1 = maxCierre != 0 ? (maxCierre - close) / maxCierre : 0.0 av1 = ta.sma(Cond1, permitjdesv) stdv1 = ta.stdev(Cond1, permitjdesv) Cond1zon = av1 + stdv1 Cond2 = ta.sma(close, periode) av2 = ta.sma(Cond2, permitjdesv) stdv2 = ta.stdev(Cond2, permitjdesv) Cond2zon = av2 - stdv2 if ug_verAgotamiento and ug_puedeDibujar and Cond1 > Cond1zon and Cond2 < Cond2zon label.new(bar_index, low - 60 * desplazamiento, "•", style=label.style_label_down, color=color.rgb(150, 0, 0, 20), textcolor=color.white) // ── ALMA ── m = Offs * (fa - 1) s = fa / sigmaALMA float WtdSum = 0.0 float CumWt = 0.0 for k = 0 to fa - 1 peso = math.exp(-((k - m) * (k - m)) / (2 * s * s)) WtdSum += peso * close[fa - 1 - k] CumWt += peso faMA = WtdSum / CumWt n = Offs * (Sl - 1) t = Sl / sigmaALMA float SWtdSum = 0.0 float SCumWt = 0.0 for k = 0 to Sl - 1 pesoLento = math.exp(-((k - n) * (k - n)) / (2 * t * t)) SWtdSum += pesoLento * close[Sl - 1 - k] SCumWt += pesoLento SlMA = SWtdSum / SCumWt ALMA = faMA - SlMA AtrValue = ta.atr(14) // ── Cajas originales de stop loss ── // Son independientes del trailing añadido. if Usecajastoploss and ug_puedeDibujar and bar_index >= NumVelasEst if ALMA > 0 nivelSL = low - AjusteSLatr * AtrValue referencia = close[NumVelasEst] box.new(left=bar_index - NumVelasEst, top=math.max(nivelSL, referencia), right=bar_index, bottom=math.min(nivelSL, referencia), bgcolor=color.rgb(0, 0, 150, Transparencia)) if ALMA < 0 nivelSL = high + AjusteSLatr * AtrValue referencia = close[NumVelasEst] box.new(left=bar_index - NumVelasEst, top=math.max(nivelSL, referencia), right=bar_index, bottom=math.min(nivelSL, referencia), bgcolor=color.rgb(250, 0, 0, Transparencia)) plot(ALMA, title="ALMA Oscillator", display=display.data_window) // ── Gestión: configuración ── ug_n = input.int(5, "Giro para rupturas: velas a cada lado", minval=1, maxval=100, group="GESTIÓN · Entradas") ug_filtrarGenial = input.bool(false, "Exigir también alineación con Genial", group="GESTIÓN · Entradas") ug_refModo = input.string("Zona completa", "Referencia de los dos cierres", options=["Zona completa", "EMA 8", "Wilder 8", "Genial"], group="GESTIÓN · Salidas") ug_usarDos = input.bool(true, "Salir también por dos cierres contrarios", group="GESTIÓN · Salidas") ug_giro = input.int(2, "Giro del trailing: velas a cada lado", minval=1, maxval=50, group="GESTIÓN · Trailing") ug_ticks = input.int(2, "Margen bajo mínimos / sobre máximos, en ticks", minval=1, maxval=1000, group="GESTIÓN · Trailing") ug_respaldo = input.int(10, "Velas del stop inicial si falta giro válido", minval=2, maxval=200, group="GESTIÓN · Trailing") ug_verSR = input.bool(false, "Mostrar soportes y resistencias", group="GESTIÓN · Aspecto") ug_verSenales = input.bool(true, "Mostrar entradas y salidas", group="GESTIÓN · Aspecto") ug_verStop = input.bool(true, "Mostrar trailing stop", group="GESTIÓN · Aspecto") ug_verAjustes = input.bool(false, "Marcar cada ajuste del stop", group="GESTIÓN · Aspecto") ug_verPanel = input.bool(true, "Mostrar panel", group="GESTIÓN · Aspecto") // ── Referencias de corrección ── ug_zonaSuperior = math.max(ema8, wilder8) ug_zonaInferior = math.min(ema8, wilder8) ug_refLargo = switch ug_refModo "EMA 8" => ema8 "Wilder 8" => wilder8 "Genial" => c9 => ug_zonaInferior ug_refCorto = switch ug_refModo "EMA 8" => ema8 "Wilder 8" => wilder8 "Genial" => c9 => ug_zonaSuperior ug_listo = not na(ug_refLargo) and not na(ug_refCorto) and not na(ug_zonaSuperior) and not na(c9[1]) ug_margen = ug_ticks * syminfo.mintick // Todos los cálculos históricos se ejecutan en cada vela. ug_ph = ta.pivothigh(high, ug_n, ug_n) ug_pl = ta.pivotlow(low, ug_n, ug_n) ug_phStop = ta.pivothigh(high, ug_giro, ug_giro) ug_plStop = ta.pivotlow(low, ug_giro, ug_giro) ug_minRespaldo = ta.lowest(low, ug_respaldo) ug_maxRespaldo = ta.highest(high, ug_respaldo) // ── Estado persistente ── var float ug_resistencia = na var float ug_soporte = na var float ug_ultimoMin = na var float ug_ultimoMax = na var int ug_sesgo = 0 var int ug_pos = 0 var int ug_barraEntrada = na var int ug_cuenta = 0 var float ug_stop = na var float ug_precioEntrada = na var float ug_refLCerrada = na var float ug_refCCerrada = na var string ug_fase = "Esperando datos" var color ug_colorFase = color.gray var string ug_evento = "Esperando ruptura válida" // Rupturas antes de actualizar los niveles. ug_rompeArriba = barstate.isconfirmed and not na(ug_resistencia) and close > ug_resistencia and close[1] <= ug_resistencia ug_rompeAbajo = barstate.isconfirmed and not na(ug_soporte) and close < ug_soporte and close[1] >= ug_soporte ug_permisoL = not ug_filtrarGenial or (close > c9 and c9 > c9[1]) ug_permisoC = not ug_filtrarGenial or (close < c9 and c9 < c9[1]) bool ug_entraL = false bool ug_entraC = false bool ug_saleL = false bool ug_saleC = false bool ug_tocado = false bool ug_ajuste = false bool ug_avisoUno = false // ── Histórico rodante de operaciones teóricas ── // Estadísticas de operaciones CERRADAS en las últimas 500 velas del gráfico. // No es Strategy Tester, no incluye comisiones, spread, deslizamiento ni financiación. ug_ventana = input.int(500, "Ventana estadística (velas)", minval=50, maxval=3000, group="RENDIMIENTO TEÓRICO") var array ug_histBarra = array.new() var array ug_histPct = array.new() var int ug_histGanadoras = 0 var int ug_histTotal = 0 var float ug_histRet = 0.0 // ── Gestión exclusivamente al cierre ── if barstate.isconfirmed ug_refLCerrada := ug_refLargo ug_refCCerrada := ug_refCorto if not na(ug_plStop) ug_ultimoMin := ug_plStop if not na(ug_phStop) ug_ultimoMax := ug_phStop // Sesgo por pendiente de Genial. if not na(c9[1]) if c9 > c9[1] ug_sesgo := 1 else if c9 < c9[1] ug_sesgo := -1 // Clasificación orientativa de la fase. if not ug_listo ug_fase := "Esperando datos" ug_colorFase := color.gray else if ug_sesgo == 1 and close > c9 ug_fase := close > ug_zonaSuperior ? "Impulso alcista" : "Corrección del sesgo alcista" ug_colorFase := close > ug_zonaSuperior ? color.green : color.orange else if ug_sesgo == -1 and close < c9 ug_fase := close < ug_zonaInferior ? "Impulso bajista" : "Corrección del sesgo bajista" ug_colorFase := close < ug_zonaInferior ? color.red : color.orange else ug_fase := "Transición / sin alineación" ug_colorFase := color.gray // Seguimiento de largo. if ug_pos == 1 ug_cuenta := ug_listo and close < ug_refLargo ? ug_cuenta + 1 : 0 // Primero se comprueba el stop previamente vigente. bool ug_hit = not na(ug_stop) and low <= ug_stop bool ug_dos = ug_usarDos and ug_cuenta >= 2 if ug_hit or ug_dos ug_saleL := true ug_tocado := ug_hit ug_evento := ug_hit ? "Stop largo tocado: " + str.tostring(ug_stop, format.mintick) : "Salida largo: dos cierres" // Precio teórico de salida: stop anterior si tocó; si no, cierre. float ug_salidaTeorica = ug_hit ? ug_stop : close float ug_pctOperacion = not na(ug_precioEntrada) and ug_precioEntrada != 0 ? (ug_salidaTeorica / ug_precioEntrada - 1) * 100 : na if not na(ug_pctOperacion) array.push(ug_histBarra, bar_index) array.push(ug_histPct, ug_pctOperacion) ug_pos := 0 ug_stop := na ug_precioEntrada := na else ug_avisoUno := ug_usarDos and ug_cuenta == 1 // El giro debe ser posterior a la entrada. if not na(ug_plStop) and bar_index - ug_giro > ug_barraEntrada float ug_candidato = ug_plStop - ug_margen // El stop largo solo puede subir. if ug_candidato > ug_stop and ug_candidato < close ug_stop := ug_candidato ug_ajuste := true ug_evento := "Subir stop: " + str.tostring(ug_stop, format.mintick) // Seguimiento de corto. else if ug_pos == -1 ug_cuenta := ug_listo and close > ug_refCorto ? ug_cuenta + 1 : 0 bool ug_hit = not na(ug_stop) and high >= ug_stop bool ug_dos = ug_usarDos and ug_cuenta >= 2 if ug_hit or ug_dos ug_saleC := true ug_tocado := ug_hit ug_evento := ug_hit ? "Stop corto tocado: " + str.tostring(ug_stop, format.mintick) : "Salida corto: dos cierres" // Precio teórico de salida: stop anterior si tocó; si no, cierre. float ug_salidaTeorica = ug_hit ? ug_stop : close float ug_pctOperacion = not na(ug_precioEntrada) and ug_precioEntrada != 0 ? (ug_precioEntrada / ug_salidaTeorica - 1) * 100 : na if not na(ug_pctOperacion) array.push(ug_histBarra, bar_index) array.push(ug_histPct, ug_pctOperacion) ug_pos := 0 ug_stop := na ug_precioEntrada := na else ug_avisoUno := ug_usarDos and ug_cuenta == 1 if not na(ug_phStop) and bar_index - ug_giro > ug_barraEntrada float ug_candidato = ug_phStop + ug_margen // El stop corto solo puede bajar. if ug_candidato < ug_stop and ug_candidato > close ug_stop := ug_candidato ug_ajuste := true ug_evento := "Bajar stop: " + str.tostring(ug_stop, format.mintick) // Sin seguimiento: buscar una entrada nueva. else ug_cuenta := 0 if ug_listo if ug_rompeArriba and not ug_rompeAbajo and close > ug_zonaSuperior and ug_permisoL ug_entraL := true ug_pos := 1 ug_barraEntrada := bar_index ug_precioEntrada := close ug_stop := not na(ug_ultimoMin) and ug_ultimoMin - ug_margen < close ? ug_ultimoMin - ug_margen : ug_minRespaldo - ug_margen ug_evento := "Entrada larga orientativa" else if ug_rompeAbajo and not ug_rompeArriba and close < ug_zonaInferior and ug_permisoC ug_entraC := true ug_pos := -1 ug_barraEntrada := bar_index ug_precioEntrada := close ug_stop := not na(ug_ultimoMax) and ug_ultimoMax + ug_margen > close ? ug_ultimoMax + ug_margen : ug_maxRespaldo + ug_margen ug_evento := "Entrada corta orientativa" // Actualización posterior de la estructura. if not na(ug_ph) ug_resistencia := ug_ph if not na(ug_pl) ug_soporte := ug_pl // ── Dibujos de gestión ── plot(ug_verSR ? ug_resistencia : na, "GESTIÓN · Resistencia", color=color.red, linewidth=2, style=plot.style_stepline) plot(ug_verSR ? ug_soporte : na, "GESTIÓN · Soporte", color=color.teal, linewidth=2, style=plot.style_stepline) // El nuevo stop rige desde la vela siguiente. // No se dibuja retrospectivamente sobre el giro. plot(ug_verStop and ug_pos != 0 ? ug_stop : na, "GESTIÓN · Stop siguiente vela", color=color.aqua, linewidth=2, style=plot.style_linebr, offset=1) plot(ug_pos != 0 ? ug_stop : na, "GESTIÓN · Stop confirmado", display=display.data_window) plotshape(ug_verSenales and ug_entraL, title="GESTIÓN · Entrada larga", style=shape.triangleup, location=location.belowbar, color=color.lime, size=size.small, text="L") plotshape(ug_verSenales and ug_entraC, title="GESTIÓN · Entrada corta", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="C") plotshape(ug_verSenales and ug_saleL, title="GESTIÓN · Salida largo", style=shape.xcross, location=location.abovebar, color=color.orange, size=size.small, text="SAL L") plotshape(ug_verSenales and ug_saleC, title="GESTIÓN · Salida corto", style=shape.xcross, location=location.belowbar, color=color.orange, size=size.small, text="SAL C") plotshape(ug_verAjustes and ug_ajuste, title="GESTIÓN · Ajuste stop", style=shape.diamond, location=location.abovebar, color=color.aqua, size=size.tiny, text="SL") // ── Panel ── var table ug_panel = table.new(position.top_right, 2, 19, bgcolor=color.new(color.black, 15), frame_color=color.gray, frame_width=1) if barstate.islast and ug_verPanel string ug_estado = ug_pos == 1 ? "Largo teórico activo" : ug_pos == -1 ? "Corto teórico activo" : "Sin seguimiento activo" string ug_sesgoTexto = ug_sesgo == 1 ? "Alcista por Genial" : ug_sesgo == -1 ? "Bajista por Genial" : "Sin definir" string ug_refTexto = ug_pos == 1 ? str.tostring(ug_refLCerrada, format.mintick) : ug_pos == -1 ? str.tostring(ug_refCCerrada, format.mintick) : str.tostring(ug_refLCerrada, format.mintick) + " / " + str.tostring(ug_refCCerrada, format.mintick) string ug_cuentaTexto = ug_pos == 0 ? "—" : not ug_usarDos ? "Desactivados" : str.tostring(ug_cuenta) + "/2" table.cell(ug_panel, 0, 0, "DOMENEC UNIFICADO", text_color=color.white, bgcolor=color.navy) table.cell(ug_panel, 1, 0, "Gestión al cierre", text_color=color.white, bgcolor=color.navy) table.cell(ug_panel, 0, 1, "Fase orientativa", text_color=color.white) table.cell(ug_panel, 1, 1, ug_fase, text_color=color.white, bgcolor=ug_colorFase) table.cell(ug_panel, 0, 2, "Sesgo", text_color=color.white) table.cell(ug_panel, 1, 2, ug_sesgoTexto, text_color=color.white) table.cell(ug_panel, 0, 3, "Seguimiento", text_color=color.white) table.cell(ug_panel, 1, 3, ug_estado, text_color=color.white) table.cell(ug_panel, 0, 4, "Referencia: " + ug_refModo, text_color=color.white) table.cell(ug_panel, 1, 4, ug_refTexto, text_color=color.white) table.cell(ug_panel, 0, 5, "Cierres contrarios", text_color=color.white) table.cell(ug_panel, 1, 5, ug_cuentaTexto, text_color=color.white) table.cell(ug_panel, 0, 6, "Stop siguiente vela", text_color=color.white) table.cell(ug_panel, 1, 6, ug_pos != 0 ? str.tostring(ug_stop, format.mintick) : "—", text_color=color.aqua) table.cell(ug_panel, 0, 7, "Entrada teórica", text_color=color.white) table.cell(ug_panel, 1, 7, ug_pos != 0 ? str.tostring(ug_precioEntrada, format.mintick) : "—", text_color=color.white) table.cell(ug_panel, 0, 8, "Salida habilitada", text_color=color.white) table.cell(ug_panel, 1, 8, ug_usarDos ? "Stop o dos cierres" : "Solo trailing", text_color=color.white) table.cell(ug_panel, 0, 9, "Último evento", text_color=color.white) table.cell(ug_panel, 1, 9, ug_evento, text_color=color.white) // Purgar operaciones cuyo CIERRE ya no pertenece a la ventana móvil. if barstate.isconfirmed while array.size(ug_histBarra) > 0 and array.get(ug_histBarra, 0) <= bar_index - ug_ventana array.shift(ug_histBarra) array.shift(ug_histPct) if barstate.islast and ug_verPanel int ug_nTrades = array.size(ug_histPct) int ug_nWins = 0 float ug_sumaPct = 0.0 float ug_brutoMas = 0.0 float ug_brutoMenos = 0.0 if ug_nTrades > 0 for j = 0 to ug_nTrades - 1 float r = array.get(ug_histPct, j) ug_nWins += r > 0 ? 1 : 0 ug_sumaPct += r ug_brutoMas += math.max(r, 0) ug_brutoMenos += math.min(r, 0) float ug_pctAcierto = ug_nTrades > 0 ? ug_nWins * 100.0 / ug_nTrades : na float ug_mediaPct = ug_nTrades > 0 ? ug_sumaPct / ug_nTrades : na float ug_factor = ug_brutoMenos < 0 ? ug_brutoMas / math.abs(ug_brutoMenos) : na table.cell(ug_panel, 0, 10, "GENIAL · MACRO", bgcolor=color.navy, text_color=color.white) table.cell(ug_panel, 1, 10, "Nivel | Tendencia | Precio", bgcolor=color.navy, text_color=color.white) table.cell(ug_panel, 0, 11, "Semanal (1W)", text_color=color.fuchsia) table.cell(ug_panel, 1, 11, str.tostring(ug_gW, format.mintick) + " | " + f_macroDireccion(ug_gW, ug_gWprev) + " | " + f_macroPosicion(ug_cW, ug_gW), text_color=color.white) table.cell(ug_panel, 0, 12, "Diaria (1D)", text_color=color.yellow) table.cell(ug_panel, 1, 12, str.tostring(ug_gD, format.mintick) + " | " + f_macroDireccion(ug_gD, ug_gDprev) + " | " + f_macroPosicion(ug_cD, ug_gD), text_color=color.white) table.cell(ug_panel, 0, 13, "4 horas (4H)", text_color=color.aqua) table.cell(ug_panel, 1, 13, str.tostring(ug_gH, format.mintick) + " | " + f_macroDireccion(ug_gH, ug_gHprev) + " | " + f_macroPosicion(ug_cH, ug_gH), text_color=color.white) table.cell(ug_panel, 0, 14, "RENDIMIENTO TEÓRICO", bgcolor=color.navy, text_color=color.white) table.cell(ug_panel, 1, 14, str.tostring(ug_ventana) + " últimas velas", bgcolor=color.navy, text_color=color.white) table.cell(ug_panel, 0, 15, "Operaciones cerradas", text_color=color.white) table.cell(ug_panel, 1, 15, str.tostring(ug_nTrades) + " (" + str.tostring(ug_nWins) + " ganadoras)", text_color=color.white) table.cell(ug_panel, 0, 16, "Porcentaje de acierto", text_color=color.white) table.cell(ug_panel, 1, 16, ug_nTrades > 0 ? str.tostring(ug_pctAcierto, "#.##") + "%" : "Sin muestra", text_color=color.white) table.cell(ug_panel, 0, 17, "Retorno medio / operación", text_color=color.white) table.cell(ug_panel, 1, 17, ug_nTrades > 0 ? str.tostring(ug_mediaPct, "#.##") + "%" : "Sin muestra", text_color=ug_mediaPct > 0 ? color.lime : color.orange) table.cell(ug_panel, 0, 18, "Suma % / Factor beneficio", text_color=color.white) table.cell(ug_panel, 1, 18, ug_nTrades > 0 ? str.tostring(ug_sumaPct, "#.##") + "% / " + (na(ug_factor) ? "—" : str.tostring(ug_factor, "#.##")) : "Sin muestra", text_color=ug_sumaPct > 0 ? color.lime : color.orange) // ── FVG: huecos de valor justo de tres velas en temporalidad del gráfico ── // Alcista: low > high[2]. Bajista: high < low[2]. // Una caja permanece hasta una ruptura COMPLETA de su lado opuesto. ug_verFVG = input.bool(true, "Mostrar FVG activos", group="FVG") ug_fvgMinTicks = input.int(1, "Tamaño mínimo (ticks)", minval=1, group="FVG") ug_fvgMax = input.int(35, "Máximo de FVG simultáneos", minval=1, maxval=150, group="FVG") ug_fvgInvalidacion = input.string("Cierre", "Invalidar con", options=["Cierre", "Mecha"], group="FVG") ug_fvgOpacidad = input.int(83, "Transparencia", minval=0, maxval=100, group="FVG") var array ug_fvgCajas = array.new() var array ug_fvgLados = array.new() var array ug_fvgTop = array.new() var array ug_fvgBottom = array.new() bool ug_nuevoFVGalza = false bool ug_nuevoFVGbaja = false bool ug_rompioFVG = false if barstate.isconfirmed // Primero actualizamos y comprobamos los existentes; nunca invalidamos // un FVG recién creado por la misma vela que lo confirma. if array.size(ug_fvgCajas) > 0 for j = array.size(ug_fvgCajas) - 1 to 0 box caja = array.get(ug_fvgCajas, j) int lado = array.get(ug_fvgLados, j) float techo = array.get(ug_fvgTop, j) float suelo = array.get(ug_fvgBottom, j) bool roto = lado == 1 ? (ug_fvgInvalidacion == "Cierre" ? close < suelo : low < suelo) : (ug_fvgInvalidacion == "Cierre" ? close > techo : high > techo) if roto or not ug_verFVG box.delete(caja) array.remove(ug_fvgCajas, j) array.remove(ug_fvgLados, j) array.remove(ug_fvgTop, j) array.remove(ug_fvgBottom, j) ug_rompioFVG := ug_rompioFVG or roto else box.set_right(caja, bar_index + 1) if ug_verFVG and bar_index >= 2 ug_nuevoFVGalza := low > high[2] and (low - high[2]) >= ug_fvgMinTicks * syminfo.mintick ug_nuevoFVGbaja := high < low[2] and (low[2] - high) >= ug_fvgMinTicks * syminfo.mintick if ug_nuevoFVGalza or ug_nuevoFVGbaja int lado = ug_nuevoFVGalza ? 1 : -1 float techo = ug_nuevoFVGalza ? low : low[2] float suelo = ug_nuevoFVGalza ? high[2] : high color fondo = lado == 1 ? color.new(color.lime, ug_fvgOpacidad) : color.new(color.red, ug_fvgOpacidad) color borde = lado == 1 ? color.new(color.green, 45) : color.new(color.red, 45) box b = box.new(left=bar_index - 2, top=techo, right=bar_index + 1, bottom=suelo, xloc=xloc.bar_index, border_color=borde, bgcolor=fondo) array.push(ug_fvgCajas, b) array.push(ug_fvgLados, lado) array.push(ug_fvgTop, techo) array.push(ug_fvgBottom, suelo) if array.size(ug_fvgCajas) > ug_fvgMax box.delete(array.shift(ug_fvgCajas)) array.shift(ug_fvgLados) array.shift(ug_fvgTop) array.shift(ug_fvgBottom) alertcondition(ug_nuevoFVGalza, "FVG · Alcista nuevo", "FVG alcista confirmado en {{ticker}} {{interval}}.") alertcondition(ug_nuevoFVGbaja, "FVG · Bajista nuevo", "FVG bajista confirmado en {{ticker}} {{interval}}.") alertcondition(ug_rompioFVG, "FVG · Invalidado", "Un FVG ha quedado invalidado en {{ticker}} {{interval}}.") // ── Alertas ── alertcondition(ug_entraL, "GESTIÓN · Entrada larga", "Entrada larga orientativa por ruptura y zona en {{ticker}} {{interval}}.") alertcondition(ug_entraC, "GESTIÓN · Entrada corta", "Entrada corta orientativa por ruptura y zona en {{ticker}} {{interval}}.") alertcondition(ug_saleL, "GESTIÓN · Salida largo", "Salida orientativa de largo: stop o dos cierres en {{ticker}} {{interval}}.") alertcondition(ug_saleC, "GESTIÓN · Salida corto", "Salida orientativa de corto: stop o dos cierres en {{ticker}} {{interval}}.") alertcondition(ug_tocado, "GESTIÓN · Stop alcanzado", "La vela terminada alcanzó el stop previamente vigente en {{ticker}} {{interval}}. No implica ejecución real ni precio garantizado.") alertcondition(ug_ajuste, "GESTIÓN · Actualizar stop", "Nuevo stop confirmado para la próxima vela en {{ticker}} {{interval}}. Consulta el panel.") alertcondition(ug_avisoUno, "GESTIÓN · Primer cierre contrario", "Primer cierre contrario a la referencia seleccionada en {{ticker}} {{interval}}. Revisa el panel; todavía no hay dos cierres.") // FIN DEL CÓDIGO