CRT 5m - Candle Range Theory

andresrosales1989 · study · 221 行 · 点赞 1,331 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
indicator("CRT 5m - Candle Range Theory", shorttitle = "CRT 5m", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500)
 
// =====================================================================
// INPUTS
// =====================================================================
string GRP_DET = "Detección del CRT"
float  minRangeATR = input.float(0.0, "Tamaño mínimo de la vela de rango (x ATR)", minval = 0.0, step = 0.1, tooltip = "Ignora velas de rango muy pequeñas. 0 = sin filtro.", group = GRP_DET)
bool   reqColor    = input.bool(false, "La vela de barrido debe ser del color de la dirección", tooltip = "CRT bajista: vela de barrido roja. CRT alcista: vela de barrido verde.", group = GRP_DET)
float  tpFibLevel  = input.float(2.0, "Nivel Fibonacci del T.P.", minval = 1.0, step = 0.5, tooltip = "Fibonacci sobre la vela de barrido: nivel 0 = su extremo (S.L.: mínimo si es alcista, máximo si es bajista), nivel 1 = su otro extremo, nivel 2 = T.P.", group = GRP_DET)
float  slFibExt    = input.float(0.25, "Nivel Fibonacci del S.L. (distancia más allá del nivel 0)", minval = 0.0, step = 0.05, tooltip = "0.25 = el S.L. queda en el nivel Fibonacci -0.25: 0.25 veces la altura de la vela de barrido más allá de su extremo (debajo del mínimo si es alcista, arriba del máximo si es bajista). 0 = justo en el extremo.", group = GRP_DET)
float  slBuffer    = input.float(0.0, "Margen extra del S.L. (en ticks)", minval = 0.0, step = 1.0, group = GRP_DET)
bool   showPreview = input.bool(true, "Señal inmediata (sin esperar el cierre de la vela de 5m)", tooltip = "Activado: la señal se marca en cuanto la vela barre el extremo y está dentro del rango, también en el modo Replay y en tiempo real. La señal se mantiene aunque el precio retroceda antes del cierre; los niveles siguen a la vela y quedan fijos al cerrar. Desactivado: la señal solo se marca al cierre de la vela.", group = GRP_DET)
bool   waitTrade   = input.bool(true, "No buscar un CRT nuevo hasta que el actual toque el S.L. o el T.P.", tooltip = "Mientras el CRT actual no haya tocado el S.L. ni el T.P., no se dibuja ninguno nuevo y el actual no se borra. Los CRT que aparezcan en ese tiempo se ignoran.", group = GRP_DET)
int    maxSignals  = input.int(1, "Máximo de CRT visibles en el gráfico", minval = 1, maxval = 100, tooltip = "1 = solo se ve el último CRT; al salir uno nuevo se borra completo el anterior.", group = GRP_DET)
 
string GRP_RNG = "Vela de rango (alto / bajo)"
bool   showRange   = input.bool(true, "Mostrar alto y bajo de la vela de rango", group = GRP_RNG)
color  rngHiColor  = input.color(#000000, "Color línea del alto", group = GRP_RNG)
color  rngLoColor  = input.color(#000000, "Color línea del bajo", group = GRP_RNG)
int    rngWidth    = input.int(2, "Grosor", minval = 1, maxval = 10, group = GRP_RNG)
string rngStyleIn  = input.string("Sólida", "Tipo de línea", options = ["Sólida", "Discontinua", "Punteada"], group = GRP_RNG)
int    rngLen      = input.int(40, "Largo (barras después de la señal)", minval = 1, maxval = 500, group = GRP_RNG)
bool   showMid     = input.bool(true, "Mostrar el 50% del rango (equilibrio / TP parcial)", group = GRP_RNG)
color  midColor    = input.color(#000000, "Color línea del 50%", group = GRP_RNG)
int    midWidth    = input.int(1, "Grosor del 50%", minval = 1, maxval = 10, group = GRP_RNG)
string midStyleIn  = input.string("Punteada", "Tipo de línea del 50%", options = ["Sólida", "Discontinua", "Punteada"], group = GRP_RNG)
 
string GRP_LVL = "Entrada / S.L. / T.P."
bool   showLevels  = input.bool(true, "Mostrar entrada, S.L. y T.P.", group = GRP_LVL)
color  entryColor  = input.color(#000000, "Color línea de entrada", group = GRP_LVL)
color  slColor     = input.color(#000000, "Color línea del S.L.", group = GRP_LVL)
color  tpColor     = input.color(#000000, "Color línea del T.P. (nivel Fibonacci 2)", group = GRP_LVL)
int    lvlWidth    = input.int(1, "Grosor de las líneas", minval = 1, maxval = 10, group = GRP_LVL)
string lvlStyleIn  = input.string("Sólida", "Tipo de línea", options = ["Sólida", "Discontinua", "Punteada"], group = GRP_LVL)
color  invalidColor = input.color(#ff0000, "Color de todo el CRT si toca el S.L. primero", group = GRP_LVL)
bool   showPrice   = input.bool(false, "Mostrar precio en las etiquetas", group = GRP_LVL)
string lblSizeIn   = input.string("Normal", "Tamaño de las etiquetas", options = ["Diminuto", "Pequeño", "Normal", "Grande", "Enorme"], group = GRP_LVL)
bool   boldTxt     = input.bool(true, "Etiquetas en negrita", group = GRP_LVL)
 
string GRP_MRK = "Marcador de señal"
bool   showMarker  = input.bool(true, "Mostrar marcador", group = GRP_MRK)
string markerShape = input.string("Triángulo", "Forma", options = ["Triángulo", "Flecha", "Diamante", "Círculo", "Cuadrado"], group = GRP_MRK)
string markerSize  = input.string("Normal", "Tamaño", options = ["Diminuto", "Pequeño", "Normal", "Grande"], group = GRP_MRK)
color  bullColor   = input.color(#089981, "Color CRT alcista (compra)", group = GRP_MRK)
color  bearColor   = input.color(#f23645, "Color CRT bajista (venta)", group = GRP_MRK)
 
// =====================================================================
// FUNCIONES AUXILIARES
// =====================================================================
f_style(string s) =>
    s == "Sólida" ? line.style_solid : s == "Discontinua" ? line.style_dashed : line.style_dotted
 
f_size(string s) =>
    switch s
        "Diminuto" => size.tiny
        "Pequeño"  => size.small
        "Grande"   => size.large
        "Enorme"   => size.huge
        =>            size.normal
 
f_marker(string s, bool bull) =>
    switch s
        "Flecha"   => bull ? label.style_arrowup : label.style_arrowdown
        "Diamante" => label.style_diamond
        "Círculo"  => label.style_circle
        "Cuadrado" => label.style_square
        =>            bull ? label.style_triangleup : label.style_triangledown
 
mkLine(bool vis, int x1, int x2, float p, color c, int w, string st) =>
    vis ? line.new(x1, p, x2, p, color = c, width = w, style = f_style(st)) : line.new(na, na, na, na)
 
mkLbl(bool vis, int x, float p, string nm, color tc) =>
    string t = nm + (showPrice ? " (" + str.tostring(p, format.mintick) + ")" : "")
    vis ? label.new(x, p, t, color = color.new(color.white, 100), style = label.style_label_left, textcolor = tc, size = f_size(lblSizeIn), text_formatting = boldTxt ? text.format_bold : text.format_none) : label.new(na, na, "")
 
// =====================================================================
// TIPO
// =====================================================================
type Crt
    line  rHi
    line  rLo
    line  lMid
    line  lEn
    line  lSL
    line  lTP
    label bMid
    label bEn
    label bSL
    label bTP
    label mk
    bool  bull
    float sl
    float tp
    int   bar
    bool  done = false
 
var array<Crt> crts = array.new<Crt>()
 
drawCrt(bool bull, float rH, float rL, float entry, float sl, float tp) =>
    int   x0   = bar_index
    int   x1   = bar_index + 1
    float mid  = (rH + rL) / 2
    line  rHi  = mkLine(showRange, bar_index - 1, bar_index + rngLen, rH, rngHiColor, rngWidth, rngStyleIn)
    line  rLo  = mkLine(showRange, bar_index - 1, bar_index + rngLen, rL, rngLoColor, rngWidth, rngStyleIn)
    line  lMid = mkLine(showRange and showMid, bar_index - 1, bar_index + rngLen, mid, midColor, midWidth, midStyleIn)
    line  lEn  = mkLine(showLevels, x0, x1, entry, entryColor, lvlWidth, lvlStyleIn)
    line  lSL  = mkLine(showLevels, x0, x1, sl, slColor, lvlWidth, lvlStyleIn)
    line  lTP  = mkLine(showLevels, x0, x1, tp, tpColor, lvlWidth, lvlStyleIn)
    label bMid = mkLbl(showRange and showMid, bar_index + rngLen, mid, "50%", midColor)
    label bEn  = mkLbl(showLevels, x1, entry, "Entrada", entryColor)
    label bSL  = mkLbl(showLevels, x1, sl, "S.L.", slColor)
    label bTP  = mkLbl(showLevels, x1, tp, "T.P.", tpColor)
    label mk   = showMarker ? label.new(bar_index, bull ? low : high, "", yloc = bull ? yloc.belowbar : yloc.abovebar, color = bull ? bullColor : bearColor, style = f_marker(markerShape, bull), size = f_size(markerSize)) : label.new(na, na, "")
    Crt.new(rHi = rHi, rLo = rLo, lMid = lMid, lEn = lEn, lSL = lSL, lTP = lTP, bMid = bMid, bEn = bEn, bSL = bSL, bTP = bTP, mk = mk, bull = bull, sl = sl, tp = tp, bar = bar_index)
 
delCrt(Crt c) =>
    c.rHi.delete()
    c.rLo.delete()
    c.lMid.delete()
    c.lEn.delete()
    c.lSL.delete()
    c.lTP.delete()
    c.bMid.delete()
    c.bEn.delete()
    c.bSL.delete()
    c.bTP.delete()
    c.mk.delete()
    true
 
// =====================================================================
// LÓGICA CRT
// Vela 1 = vela de rango. Vela 2 = barre un extremo del rango pero cierra DENTRO.
// CRT bajista: barre el alto y cierra dentro -> objetivo = bajo de la vela de rango.
// CRT alcista: barre el bajo y cierra dentro -> objetivo = alto de la vela de rango.
// =====================================================================
float atrVal = ta.atr(14)
float rH     = high[1]
float rL     = low[1]
 
bool sizeOk  = (rH - rL) >= minRangeATR * nz(atrVal[1])
bool outside = high > rH and low < rL
 
bool bearCrt = bar_index > 1 and high > rH and close < rH and close >= rL and not outside and sizeOk and (not reqColor or close < open)
bool bullCrt = bar_index > 1 and low < rL and close > rL and close <= rH and not outside and sizeOk and (not reqColor or close > open)
 
// --- Seguimiento de CRT activos (S.L. / T.P.) ---
if crts.size() > 0
    for i = 0 to crts.size() - 1
        Crt f = crts.get(i)
        if not f.done and f.bar < bar_index
            bool slHit = f.bull ? low <= f.sl : high >= f.sl
            bool tpHit = f.bull ? high >= f.tp : low <= f.tp
            if showLevels
                line.set_x2(f.lEn, bar_index)
                line.set_x2(f.lSL, bar_index)
                line.set_x2(f.lTP, bar_index)
                label.set_x(f.bEn, bar_index)
                label.set_x(f.bSL, bar_index)
                label.set_x(f.bTP, bar_index)
            if barstate.isconfirmed
                if slHit
                    line.set_color(f.rHi, invalidColor)
                    line.set_color(f.rLo, invalidColor)
                    line.set_color(f.lMid, invalidColor)
                    label.set_textcolor(f.bMid, invalidColor)
                    line.set_color(f.lEn, invalidColor)
                    line.set_color(f.lSL, invalidColor)
                    line.set_color(f.lTP, invalidColor)
                    label.set_textcolor(f.bEn, invalidColor)
                    label.set_textcolor(f.bSL, invalidColor)
                    label.set_textcolor(f.bTP, invalidColor)
                    label.set_color(f.mk, invalidColor)
                    f.done := true
                else if tpHit
                    f.done := true
 
// --- ¿Hay un CRT activo (aún no toca S.L. ni T.P.)? ---
// Se ignora el CRT dibujado en la vela actual, porque se redibuja con cada tick.
bool tradeActive = false
if waitTrade and crts.size() > 0
    for i = 0 to crts.size() - 1
        Crt fa = crts.get(i)
        if not fa.done and fa.bar < bar_index
            tradeActive := true
 
// --- Señal (inmediata o al cierre) ---
// latchBar guarda la vela en la que ya se cumplió el CRT, así la señal se mantiene aunque el precio retroceda.
varip int  latchBar  = -1
varip bool latchBull = false
 
bool liveOk = showPreview or barstate.isconfirmed
if liveOk and bar_index > 1 and (bearCrt or bullCrt) and not tradeActive and latchBar != bar_index
    latchBar  := bar_index
    latchBull := bullCrt
 
if liveOk and latchBar == bar_index and not tradeActive
    // quitar la señal dibujada en un tick anterior de esta misma vela
    if crts.size() > 0
        Crt lastC = crts.get(crts.size() - 1)
        if lastC.bar == bar_index
            delCrt(lastC)
            crts.pop()
 
    bool  isBull = latchBull
    float entry  = close
    float buf    = slBuffer * syminfo.mintick
    float rng    = math.max(high - low, syminfo.mintick)
    float fib0   = isBull ? low : high
    float sl     = isBull ? fib0 - slFibExt * rng - buf : fib0 + slFibExt * rng + buf
    float tp     = isBull ? fib0 + tpFibLevel * rng : fib0 - tpFibLevel * rng
    if (isBull ? tp > entry : tp < entry)
        crts.push(drawCrt(isBull, rH, rL, entry, sl, tp))
 
    while crts.size() > maxSignals
        Crt oldC = crts.shift()
        delCrt(oldC)
 
// --- Alertas ---
alertcondition(bullCrt and not tradeActive, "CRT alcista (compra)", "CRT alcista en {{ticker}}: barrió el bajo del rango y cerró dentro. T.P. en el nivel Fibonacci 2.")
alertcondition(bearCrt and not tradeActive, "CRT bajista (venta)", "CRT bajista en {{ticker}}: barrió el alto del rango y cerró dentro. T.P. en el nivel Fibonacci 2.")

← 返回列表