Heatmap Trailing Stop with Breakouts. Conversion from pinescript to prorealtime

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #252739 quote
    Pedro.lopez
    Participant
    Junior

    █Overview
    Heatmap Trailing Stop with Breakouts (Zeiierman) is a trend and breakout detection tool that combines dynamic trailing stop logic, Fibonacci-based levels, and a real-time market heatmap into a single, intuitive system.
    This indicator is designed to help traders visualize pressure zones, manage stop placement, and identify breakout opportunities supported by contextual price–derived heat. Whether you’re trailing trends, detecting reversals, or entering on explosive breakouts — this tool keeps you anchored in structure and sentiment.
    It projects adaptive trailing stop levels and calculates Fibonacci extensions from swing-based extremes. These levels are then colored by a market heatmap engine that tracks price interaction intensity — showing where the market is “hot” and likely to respond.
    On top of that, it includes breakout signals powered by HTF momentum conditions, trend direction, and heatmap validation — giving you signals only when the context is strong.
    █How It Works
    ⚪ Trailing Stop Engine
    At its core, the script uses an ATR-based trailing stop with trend detection:
    ATR Length – Defines volatility smoothing using EMA MA of true range.
    Multiplier – Expands/retracts the trailing offset depending on market aggression.
    Real-Time Extremum Tracking – Uses local highs/lows to define Fibonacci anchors.
    ⚪ Fibonacci Projection + Heatmap
    With each trend shift, Fibonacci levels are projected from the new swing to the current trailing stop. These include:

    Fib 61.8, 78.6, 88.6, and 100% (trailing stop) lines
    Heatmap Coloring – Each level’slevel’s color is determined by how frequently price has interacted with that level in the recent range (defined by ATR).
    Strength Score (1–10) – The number of touches per level is normalized and averaged to create a heatmap “”score”” displayed as a colored bar on the chart.
    ⚪ Breakout Signal System
    This engine detects high-confidence breakout signals using a higher timeframe candle structure:
    Bullish Breakout – Strong bullish candle + momentum + trend confirmation + heatmap score threshold.
    Bearish Breakout – Strong bearish candle + momentum + trend confirmation + heatmap score threshold.
    Cooldown Logic – Prevents signals from clustering too frequently during volatile periods.
    █How to Use
    ⚪ Trend Following & Trail Stops
    Use the Trailing Stop line to manage positions or time entries in line with trend direction. Trailing stop flips are highlighted with dot markers.
    25 077
    █ Overview
    Heatmap Trailing Stop with Breakouts (Zeiierman) is a trend and breakout detection tool that combines dynamic trailing stop logic, Fibonacci-based levels, and a real-time market heatmap into a single, intuitive system.
    This indicator is designed to help traders visualize pressure zones, manage stop placement, and identify breakout opportunities supported by contextual price–derived heat. Whether you’re trailing trends, detecting reversals, or entering on explosive breakouts — this tool keeps you anchored in structure and sentiment.
    snapshot
    It projects adaptive trailing stop levels and calculates Fibonacci extensions from swing-based extremes. These levels are then colored by a market heatmap engine that tracks price interaction intensity — showing where the market is “hot” and likely to respond.
    snapshot
    On top of that, it includes breakout signals powered by HTF momentum conditions, trend direction, and heatmap validation — giving you signals only when the context is strong.
    snapshot
    █ How It Works
    ⚪ Trailing Stop Engine
    At its core, the script uses an ATR-based trailing stop with trend detection:
    ATR Length – Defines volatility smoothing using EMA MA of true range.
    Multiplier – Expands/retracts the trailing offset depending on market aggression.
    Real-Time Extremum Tracking – Uses local highs/lows to define Fibonacci anchors.
    ⚪ Fibonacci Projection + Heatmap
    With each trend shift, Fibonacci levels are projected from the new swing to the current trailing stop. These include:
    Fib 61.8, 78.6, 88.6, and 100% (trailing stop) lines
    Heatmap Coloring – Each level’slevel’s color is determined by how frequently price has interacted with that level in the recent range (defined by ATR).
    Strength Score (1–10) – The number of touches per level is normalized and averaged to create a heatmap “”score”” displayed as a colored bar on the chart.
    ⚪ Breakout Signal System
    This engine detects high-confidence breakout signals using a higher timeframe candle structure:
    Bullish Breakout – Strong bullish candle + momentum + trend confirmation + heatmap score threshold.
    Bearish Breakout – Strong bearish candle + momentum + trend confirmation + heatmap score threshold.
    Cooldown Logic – Prevents signals from clustering too frequently during volatile periods.
    █ How to Use
    ⚪ Trend Following & Trail Stops
    Use the Trailing Stop line to manage positions or time entries in line with trend direction. Trailing stop flips are highlighted with dot markers.
    snapshot
    ⚪ Fibonacci Heat Zones
    The projected Fibonacci levels serve as price magnets or support/resistance zones. Watch how price reacts at Fib 61.8/78.6/88.6 levels — especially when they’re glowing with high heatmap scores (more glow = more historical touches = stronger significance).
    ⚪ Breakout Signals
    Enable breakout signals when you want to trade breakouts only under strong context. Use the “Heatmap Strength Threshold” to require a minimum score (1–10).
    █Settings
    Stop Distance ATR Length – ATR period for volatility smoothing
    Stop Distance Multiplier – Adjusts the trailing stop’sstop’s distance from price
    Heatmap Range ATR Length – Defines how far back the heatmap scans for touches
    Number of Heat Levels – Total levels used in the heatmap (more = finer resolution)
    Minimum Touches per Level – Defines what counts as a “”hot”” level
    Heatmap Strength Threshold – Minimum average heat score (1–10) required for breakouts
    Timeframe – HTF source used to evaluate breakout momentum structure

    #252741 quote
    Pedro.lopez
    Participant
    Junior

     

    // This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
    
    // © Zeiierman {
    //@version=6
    indicator('Heatmap Trailing Stop with Breakouts (Zeiierman)', overlay = true)
    //~~}
    
    // ~~ Tooltips {
    var string tStopLen = "Defines the length of the ATR used to calculate the trailing stop. A higher value results in smoother stop levels but slower responsiveness."
    var string tStopMult = "Multiplier applied to the ATR to determine how far the stop is placed from price. Increase to widen the stop and reduce sensitivity."
    var string tHeatATR = "Controls the range used for heat level calculation. A longer ATR period captures a broader high/low range for color zones."
    var string tHeatLvls = "Number of horizontal levels (bands) used in the heatmap. More levels give finer granularity but may introduce noise."
    var string tHeatThresh= "Defines how many bars must touch a level to consider it 'hot'. Lower values make the heatmap more reactive."
    var string tLineWidth = "Sets the thickness of the plotted Fibonacci and trailing stop lines. Adjust to improve visibility."
    var string tWeakBull = "Color for weak bullish zones. Typically used for cooler, less-active areas in an uptrend."
    var string tStrongBull= "Color for strong bullish zones. Applied when activity clusters near heat levels during uptrends."
    var string tWeakBear = "Color for weak bearish zones. Useful for identifying minor levels during downtrends."
    var string tStrongBear= "Color for strong bearish zones. Highlights heavy price activity in bearish pressure zones."
    var string tTF = "Higher-timeframe (HTF) used to detect breakout candles. Leave blank to use the chart timeframe."
    var string tScore = "Minimum heat-strength (1-10) the heatmap must show for a breakout signal to be valid. Raise it to filter weaker moves."
    var string tBreakUp = "Color of the marker plotted when a bullish breakout (price breaks up) is confirmed."
    var string tBreakDown = "Color of the marker plotted when a bearish breakout (price breaks down) is confirmed."
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
    
    // ~~ Inputs {
    stopATRlen = input.int(28, 'Stop Distance ATR Length', minval=2, group="Trailing Trend", tooltip = tStopLen)
    stopMult = input.float(5 , 'Stop Distance Multiplier', minval=0.1, step=0.1,group="Trailing Trend", tooltip = tStopMult)
    
    heatATR = input.int(50 , title='Heatmap Range ATR Length', group="Heat-map", tooltip = tHeatATR)
    levelsInp = input.int(3 , title='Number of Heat Levels', minval = 2, maxval = 100, group="Heat-map", tooltip = tHeatLvls)
    heatThresh = input.int(3 , title='Minimum Touches per Level', minval=1, group="Heat-map", tooltip = tHeatThresh)
    
    lineWidth = input.int(2 , title='Fibonacci Line Thickness', minval=1, group="Style", tooltip = tLineWidth)
    weakbullish = input.color(color.green, title="Weak Bullish Color", group="Style", inline="c", tooltip = tWeakBull)
    strongbullish = input.color(#09ff00, title="Strong Bullish Color", group="Style", inline="c", tooltip = tWeakBull + "\n\n" + tStrongBull)
    weakbearish = input.color(color.maroon, title="Weak Bearish Color", group="Style", inline="c1", tooltip = tWeakBear)
    strongbearish = input.color(color.rgb(255, 0, 0), title="Strong Bearish Color", group="Style", inline="c1", tooltip =tWeakBear + "\n\n" + tStrongBear)
    
    tf = input.timeframe('', title='Timeframe',group="Breakout Signals", inline='tf',tooltip=tTF)
    scoreVal = input.int(6, minval=1, maxval=10, title='Heatmap Strength Threshold', group="Breakout Signals", inline='s',tooltip=tScore)
    BreakUp = input.color(color.white, title='Break Up', group="Breakout Signals", inline='Break', tooltip=tBreakUp)
    BreakDn = input.color(color.white, title='Break Down',group="Breakout Signals", inline='Break', tooltip=tBreakUp+ "\n\n" +tBreakDown)
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
    
    // ~~ Var {
    var float trendUp = na
    var float trendDown = na
    var int trendDir = 1
    var float ex = na
    // ~~ Level arrays
    var levelVals = array.new_float(15, na)
    var levelColors = array.new_color(15, na)
    var levelCounts = array.new_int(15, na)
    a = ta.atr(100)
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
    
    // ~~ Trailing Stop {
    atrTrail = ta.ema(ta.tr, stopATRlen)
    stopOffset = stopMult * atrTrail
    bullStop = high - stopOffset
    bearStop = low + stopOffset
    
    trendUp := close[1] > trendUp ? math.max(bullStop, trendUp ) : bullStop
    trendDown := close[1] < trendDown ? math.min(bearStop, trendDown) : bearStop trendDir := close > trendDown[1] ? 1 : close < trendUp[1] ? -1 : nz(trendDir[1], 1)
    bullFlip = trendDir == 1 and trendDir[1] == -1
    bearFlip = trendDir == -1 and trendDir[1] == 1
    trail = trendDir == 1 ? trendUp : trendDown
    ex := trendDir != trendDir[1] ? (trendDir == 1 ? high : low)
    : trendDir == 1 ? math.max(nz(ex[1]), high)
    : math.min(nz(ex[1]), low)
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
    
    // ~~ Fibonacci levels from trailing-stop {
    fib1 = ex + (trail - ex) * 0.618
    fib2 = ex + (trail - ex) * 0.786
    fib3 = ex + (trail - ex) * 0.886
    l100 = trail
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
    
    // ~~ Heatmap {
    hi = ta.highest(high, heatATR)
    lo = ta.lowest (low , heatATR)
    rng = hi - lo
    step = rng / (levelsInp)
    
    // ~~ Dynamic trend-based colors
    coldTrendCol = trendDir == 1 ? weakbullish : weakbearish
    hotTrendCol = trendDir == 1 ? strongbullish : strongbearish
    noColorOnFlip = trendDir != trendDir[1]
    
    // ~~ Populate arrays {
    for i = 0 to 14
    if i <= levelsInp - 1 lvl = lo + step * i cnt = 0 for j = 0 to heatATR cnt += (high[j] >= lvl and low[j] <= lvl) ? 1 : 0 col = color.from_gradient( cnt, heatThresh, heatThresh + 10, color.new(coldTrendCol , 80 - cnt), hotTrendCol ) array.set(levelVals , i, lvl) array.set(levelColors , i, col) array.set(levelCounts , i, cnt) else array.set(levelVals , i, na) array.set(levelColors , i, na) array.set(levelCounts , i, na) getClosestHeatColor(val) =>
    minD = 1e10
    color best = na
    for k = 0 to 14
    lvl = array.get(levelVals , k)
    col = array.get(levelColors, k)
    if not na(lvl)
    d = math.abs(val - lvl)
    if d < minD minD := d best := col best countToScore(cnt) =>
    raw = (float(cnt) - heatThresh) / 10.0
    norm = math.min(math.max(raw, 0.0), 1.0)
    math.round(1 + norm * 9) // 1-10
    
    Score(val) =>
    minD = 1e10
    best = 1
    for k = 0 to 14
    lvl = array.get(levelVals , k)
    cnt = array.get(levelCounts, k)
    if not na(lvl)
    d = math.abs(val - lvl)
    if d < minD minD := d best := countToScore(cnt) best //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} score = math.avg(Score(trail),Score(fib1),Score(fib2),Score(fib3),Score(l100)) // ~~ Plots { heat_fib1 = noColorOnFlip ? na : getClosestHeatColor(fib1) heat_fib2 = noColorOnFlip ? na : getClosestHeatColor(fib2) heat_fib3 = noColorOnFlip ? na : getClosestHeatColor(fib3) heat_trail = noColorOnFlip ? na : getClosestHeatColor(trail) FIB61 = plot(fib1 , 'Fib 61.8',heat_fib1 , linewidth = lineWidth) FIB78 = plot(fib2 , 'Fib 78.6',heat_fib2 , linewidth = lineWidth) FIB88 = plot(fib3 , 'Fib 88.6',heat_fib3 , linewidth = lineWidth) TRAIL = plot(trail, 'Trailing Stop', heat_trail, linewidth = 2) fill(FIB61, TRAIL, fib1, trail, color.new(heat_trail, 50),na) plotshape(bullFlip?trail:na, title = 'Bull Flip', location = location.absolute,style = shape.circle, color = color.lime, size = size.tiny) plotshape(bullFlip?trail:na, title = 'Bull Flip', location = location.absolute,style = shape.circle, color = color.new(color.lime,50), size = size.small) plotshape(bearFlip?trail:na, title = 'Bear Flip', location = location.absolute, style = shape.circle, color = color.red, size = size.tiny) plotshape(bearFlip?trail:na, title = 'Bear Flip', location = location.absolute, style = shape.circle, color = color.new(color.red,50), size = size.small) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} // ~~ Breakout Signals { // ~~ HTF Prices { o = request.security(syminfo.tickerid, tf, open , lookahead = barmerge.lookahead_off) h = request.security(syminfo.tickerid, tf, high , lookahead = barmerge.lookahead_off) l = request.security(syminfo.tickerid, tf, low , lookahead = barmerge.lookahead_off) c = request.security(syminfo.tickerid, tf, close, lookahead = barmerge.lookahead_off) //~~} // ~~ Intrabar Index Sim { var int lastL = na var int lastS = na barNow = bar_index //~~} // ~~ Price Action { bull = c > o and c - o > (h - l) * 0.5
    bear = c < o and o - c > (h - l) * 0.5
    momUp = c > h[1] and c > h[2]
    momDn = c < l[1] and c < l[2] //~~} // ~~ Entry Triggers { rawL = bull and momUp and trendDir == 1 rawS = bear and momDn and trendDir == -1 //~~} // ~~ Cooldown Logic { cdL = na(lastL) or barNow - lastL > 20 or nz(lastS) > nz(lastL)
    cdS = na(lastS) or barNow - lastS > 20 or nz(lastL) > nz(lastS)
    //~~}
    
    // ~~ Final Entry Signals {
    sigL = rawL and cdL and score > scoreVal
    sigS = rawS and cdS and score > scoreVal
    //~~}
    
    // ~~ Cooldown State Update {
    if sigL
    lastL := barNow
    if sigS
    lastS := barNow
    //~~}
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
    
    // ~~ Plots {
    plotshape(sigL?low-a:na, title = 'Break Up Signal', location = location.absolute, style = shape.triangleup, size = size.tiny, color = BreakUp)
    plotshape(sigS?high+a:na, title = 'Break Down Signal', location = location.absolute, style = shape.triangledown, size = size.tiny, color = BreakDn)
    plotshape(sigL?low-a:na, title = 'Break Up Signal', location = location.absolute, style = shape.triangleup, size = size.small, color = color.new(BreakUp,50))
    plotshape(sigS?high+a:na, title = 'Break Down Signal', location = location.absolute, style = shape.triangledown, size = size.small, color = color.new(BreakDn,50))
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
    
    // ~~ Table {
    var table heatTable = table.new(position.top_right, 11, 1, border_width = 0)
    blueGradient = array.from(
    color.rgb(173, 216, 230),
    color.rgb(135, 206, 250),
    color.rgb(100, 149, 237),
    color.rgb(70 , 130, 180),
    color.rgb(65 , 105, 225),
    color.rgb(30 , 144, 255),
    color.rgb(0 , 120, 255),
    color.rgb(0 , 90 , 200),
    color.rgb(0 , 60 , 150),
    color.rgb(0 , 40 , 100)
    )
    
    if barstate.islast
    table.cell(heatTable, 0, 0, "Heatmap Strength: " + str.tostring(score), text_color=chart.fg_color)
    blkChar = "█"
    for i = 0 to 9
    show = i < score
    col = array.get(blueGradient, i)
    table.cell(heatTable, i + 1, 0, show ? blkChar : "", text_color=col)
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
    #252759 quote
    robertogozzi
    Moderator
    Master

    Por favor, no incluyas imágenes dentro del texto; de lo contrario, la página cargará más despacio.
    Las eliminé del texto y las adjunté.
    Gracias 🙂

    #252773 quote
    Iván González
    Moderator
    Master

    aquí va:

    //-------------------------------------------
    //PRC_Heatmap Trailing Stop with Breakouts
    //version = 0
    //21.10.2025
    //Iván González @ www.prorealcode.com
    //Sharing ProRealTime knowledge
    //-------------------------------------------
    // --- Inputs ---
    //-------------------------------------------
    // Trailing Trend
    stopATRlen = 28     // Stop Distance ATR Length (minval=2)
    stopMult = 5.0      // Stop Distance Multiplier (minval=0.1)
    // Heat-map
    heatATR = 50        // Heatmap Range ATR Length
    levelsInp = 3 // Number of Heat Levels (minval=2, maxval=14)
    heatThresh = 3      // Minimum Touches per Level (minval=1)
    // Weak Bullish Color
    weakbullishR = 0
    weakbullishG = 128
    weakbullishB = 0
    // Strong Bullish Color
    strongbullishR = 9
    strongbullishG = 255
    strongbullishB = 0
    // Weak Bearish Color
    weakbearishR = 128
    weakbearishG = 0
    weakbearishB = 0
    // Strong Bearish Color
    strongbearishR = 255
    strongbearishG = 0
    strongbearishB = 0
    // Breakout Signals
    scoreVal = 6        // Heatmap Strength Threshold (1-10)
    // Break Up Color
    BreakUpR = 100
    BreakUpG = 255
    BreakUpB = 100
    // Break Down Color
    BreakDnR = 255
    BreakDnG = 100
    BreakDnB = 100
    //-------------------------------------------
    // --- HTF Selection ---
    //-------------------------------------------
    //TIMEFRAME(1 hour,updateonclose)
    openTFhigher = open
    highTFhigher = high
    lowTFhigher = low
    closeTFhigher = close
    //TIMEFRAME(default)
    //-------------------------------------------
    // --- Variable Initialization ---
    //-------------------------------------------
    ONCE trendUp = 0.0
    ONCE trendDown = 0.0
    ONCE trendDir = 1
    ONCE ex = 0.0
    ONCE lastL = -1 // Use -1 as 'na' for bar index
    ONCE lastS = -1
    //-------------------------------------------
    // --- Trailing Stop Calculation ---
    //-------------------------------------------
    atrTrail = ExponentialAverage[stopATRlen](tr)
    stopOffset = stopMult * atrTrail
    bullStop = high - stopOffset
    bearStop = low + stopOffset
    
    IF close[1] > TrendUp THEN
       trendUp = MAX(bullStop, TrendUp)
    ELSE
       trendUp = bullStop
    ENDIF
    
    IF close[1] < TrendDown THEN
       trendDown = MIN(bearStop, TrendDown)
    ELSE
       trendDown = bearStop
    ENDIF
    
    IF close > TrendDown[1] THEN
       trendDir = 1
    ELSIF close < TrendUp[1] THEN
       trendDir = -1
    ENDIF
    
    bullFlip = (trendDir = 1 AND TrendDir[1] = -1)
    bearFlip = (trendDir = -1 AND TrendDir[1] = 1)
    
    trail = 0.0 // Initialize trail for the current bar
    IF trendDir = 1 THEN
       trail = trendUp
    ELSE
       trail = trendDown
    ENDIF
    
    IF trendDir <> TrendDir[1] THEN
       IF trendDir = 1 THEN
          ex = high
       ELSE
          ex = low
       ENDIF
    ELSIF trendDir = 1 THEN
       IF Ex = 0 THEN // Handle initial case
          ex = high
       ELSE
          ex = MAX(Ex, high)
       ENDIF
    ELSE // trendDir = -1
       IF Ex = 0 THEN // Handle initial case
          ex = low
       ELSE
          ex = MIN(Ex, low)
       ENDIF
    ENDIF
    //-------------------------------------------
    // --- Fibonacci levels from trailing-stop
    //-------------------------------------------
    fib1 = ex + (trail - ex) * 0.618
    fib2 = ex + (trail - ex) * 0.786
    fib3 = ex + (trail - ex) * 0.886
    l100 = trail // Same as trail
    //-------------------------------------------
    // --- Heatmap Calculation ---
    //-------------------------------------------
    hi = Highest[heatATR](high)
    lo = Lowest[heatATR](low)
    rng = hi - lo
    step = 0.0
    IF levelsInp > 0 THEN
       step = rng / levelsInp
    ENDIF
    //-------------------------------------------
    // Dynamic trend-based colors
    //-------------------------------------------
    coldTrendR = 0
    coldTrendG = 0
    coldTrendB = 0
    hotTrendR = 0
    hotTrendG = 0
    hotTrendB = 0
    
    IF trendDir = 1 THEN
       coldTrendR = weakbullishR
       coldTrendG = weakbullishG
       coldTrendB = weakbullishB
       hotTrendR = strongbullishR
       hotTrendG = strongbullishG
       hotTrendB = strongbullishB
    ELSE
       coldTrendR = weakbearishR
       coldTrendG = weakbearishG
       coldTrendB = weakbearishB
       hotTrendR = strongbearishR
       hotTrendG = strongbearishG
       hotTrendB = strongbearishB
    ENDIF
    
    noColorOnFlip = (trendDir <> TrendDir[1])
    //-------------------------------------------
    // Populate arrays & Calculate Heatmap Colors
    //-------------------------------------------
    FOR i = 0 TO 14 DO
       IF i < levelsInp AND step > 0 THEN
          lvl = lo + step * i
          cnt = 0
          FOR j = 0 TO heatATR - 1 DO
             IF high[j] >= lvl AND low[j] <= lvl THEN
                cnt = cnt + 1
             ENDIF
          NEXT
          
          levelR = coldTrendR
          levelG = coldTrendG
          levelB = coldTrendB
          levelA = MAX(0, 80 - cnt)
          
          IF cnt > heatThresh THEN
             IF cnt > heatThresh + 5 THEN
                levelR = hotTrendR
                levelG = hotTrendG
                levelB = hotTrendB
                levelA = 255
             ELSE
                levelR = (coldTrendR + hotTrendR) / 2
                levelG = (coldTrendG + hotTrendG) / 2
                levelB = (coldTrendB + hotTrendB) / 2
                levelA = 180
             ENDIF
          ENDIF
          
          $levelVals[i] = lvl
          $levelColorsR[i] = levelR
          $levelColorsG[i] = levelG
          $levelColorsB[i] = levelB
          $levelColorsA[i] = levelA
          $levelCounts[i] = cnt
       ELSE
          $levelVals[i] = Undefined
          $levelColorsR[i] = Undefined
          $levelColorsG[i] = Undefined
          $levelColorsB[i] = Undefined
          $levelColorsA[i] = Undefined
          $levelCounts[i] = -1
       ENDIF
    NEXT
    //-------------------------------------------
    // --- Find Closest Color & Score in ONE loop
    //-------------------------------------------
    // Initialize minimum distances
    minDfib1 = exp(10)
    minDfib2 = exp(10)
    minDfib3 = exp(10)
    minDtrail = exp(10)
    // Initialize best colors
    bestRfib1=0
    bestGfib1=0
    bestBfib1=0
    bestAfib1=0
    bestRfib2=0
    bestGfib2=0
    bestBfib2=0
    bestAfib2=0
    bestRfib3=0
    bestGfib3=0
    bestBfib3=0
    bestAfib3=0
    bestRtrail=0
    bestGtrail=0
    bestBtrail=0
    bestAtrail=0
    // Initialize best scores
    bestScoreFib1 = 1
    bestScoreFib2 = 1
    bestScoreFib3 = 1
    bestScoreTrail = 1
    // Single loop to find closest level for all prices and calculate their score
    FOR k = 0 TO 14 DO
       lvl = $levelVals[k]
       IF lvl <> Undefined THEN
          cnt = $levelCounts[k] // Get count for score calculation
          
          // --- Check Fib1 ---
          d = ABS(fib1 - lvl)
          IF d < minDfib1 THEN
             minDfib1 = d
             bestRfib1 = $levelColorsR[k]
             bestGfib1 = $levelColorsG[k]
             bestBfib1 = $levelColorsB[k]
             bestAfib1 = $levelColorsA[k]
             // Calculate score for this level if it's the closest
             IF cnt >= 0 THEN
                raw = MAX(0.0, MIN(1.0, (cnt - heatThresh) / 10.0))
                bestScoreFib1 = ROUND(1 + raw * 9)
             ENDIF
          ENDIF
          
          // --- Check Fib2 ---
          d = ABS(fib2 - lvl)
          IF d < minDfib2 THEN
             minDfib2 = d
             bestRfib2 = $levelColorsR[k]
             bestGfib2 = $levelColorsG[k]
             bestBfib2 = $levelColorsB[k]
             bestAfib2 = $levelColorsA[k]
             IF cnt >= 0 THEN
                raw = MAX(0.0, MIN(1.0, (cnt - heatThresh) / 10.0))
                bestScoreFib2 = ROUND(1 + raw * 9)
             ENDIF
          ENDIF
          
          // --- Check Fib3 ---
          d = ABS(fib3 - lvl)
          IF d < minDfib3 THEN
             minDfib3 = d
             bestRfib3 = $levelColorsR[k]
             bestGfib3 = $levelColorsG[k]
             bestBfib3 = $levelColorsB[k]
             bestAfib3 = $levelColorsA[k]
             IF cnt >= 0 THEN
                raw = MAX(0.0, MIN(1.0, (cnt - heatThresh) / 10.0))
                bestScoreFib3 = ROUND(1 + raw * 9)
             ENDIF
          ENDIF
          
          // --- Check Trail ---
          d = ABS(trail - lvl)
          IF d < minDtrail THEN
             minDtrail = d
             bestRtrail = $levelColorsR[k]
             bestGtrail = $levelColorsG[k]
             bestBtrail = $levelColorsB[k]
             bestAtrail = $levelColorsA[k]
             IF cnt >= 0 THEN
                raw = MAX(0.0, MIN(1.0, (cnt - heatThresh) / 10.0))
                bestScoreTrail = ROUND(1 + raw * 9)
             ENDIF
          ENDIF
       ENDIF
    NEXT
    //-------------------------------------------
    // --- Final Score Calculation ---
    //-------------------------------------------
    scoreSum = 0.0
    validScores = 0
    
    IF bestRfib1 <> Undefined THEN
       scoreSum = scoreSum + bestScoreFib1
       validScores = validScores + 1
    ENDIF
    IF bestRfib2 <> Undefined THEN
       scoreSum = scoreSum + bestScoreFib2
       validScores = validScores + 1
    ENDIF
    IF bestRfib3 <> Undefined THEN
       scoreSum = scoreSum + bestScoreFib3
       validScores = validScores + 1
    ENDIF
    IF bestRtrail <> Undefined THEN
       scoreSum = scoreSum + bestScoreTrail
       validScores = validScores + 1
    ENDIF
    
    score = 1 // Default score
    IF validScores > 0 THEN
       score = ROUND(scoreSum / validScores)
    ENDIF
    //-------------------------------------------
    // --- Assign Final Plot Colors (Handle Flip)
    //-------------------------------------------
    IF NOT noColorOnFlip THEN
       plotRfib1 = bestRfib1
       plotGfib1 = bestGfib1
       plotBfib1 = bestBfib1
       plotAfib1 = bestAfib1
       
       plotRfib2 = bestRfib2
       plotGfib2 = bestGfib2
       plotBfib2 = bestBfib2
       plotAfib2 = bestAfib2
       
       plotRfib3 = bestRfib3
       plotGfib3 = bestGfib3
       plotBfib3 = bestBfib3
       plotAfib3 = bestAfib3
       
       plotRtrail = bestRtrail
       plotGtrail = bestGtrail
       plotBtrail = bestBtrail
       plotAtrail = bestAtrail
    ENDIF
    //-------------------------------------------
    // --- Trend Flip Plots ---
    //-------------------------------------------
    transpFlip = 150
    
    IF bullFlip THEN
       DRAWPOINT(barindex, trail, 2) COLOURED(0, 255, 0, 255)
       DRAWPOINT(barindex, trail, 4) COLOURED(0, 255, 0, transpFlip)
    ENDIF
    
    IF bearFlip THEN
       DRAWPOINT(barindex, trail, 2) COLOURED(255, 0, 0, 255)
       DRAWPOINT(barindex, trail, 4) COLOURED(255, 0, 0, transpFlip)
    ENDIF
    //-------------------------------------------
    // --- Breakout Signals ---
    //-------------------------------------------
    bull = (closeTFhigher > openTFhigher AND closeTFhigher - openTFhigher > (highTFhigher - lowTFhigher) * 0.5)
    bear = (closeTFhigher < openTFhigher AND openTFhigher - closeTFhigher > (highTFhigher - lowTFhigher) * 0.5)
    momUp = (closeTFhigher > highTFhigher[1] AND closeTFhigher > highTFhigher[2])
    momDn = (closeTFhigher < lowTFhigher[1] AND closeTFhigher < lowTFhigher[2])
    
    rawL = bull AND momUp AND trendDir = 1
    rawS = bear AND momDn AND trendDir = -1
    
    barNow = barindex
    cdL = (lastL = -1 OR barNow - lastL > 20 OR (lastS <> -1 AND lastS > lastL))
    cdS = (lastS = -1 OR barNow - lastS > 20 OR (lastL <> -1 AND lastL > lastS))
    
    sigL = rawL AND cdL AND score > scoreVal
    sigS = rawS AND cdS AND score > scoreVal
    
    IF sigL THEN
       lastL = barNow
    ENDIF
    IF sigS THEN
       lastS = barNow
    ENDIF
    //-------------------------------------------
    // Plot Breakout Signals
    //-------------------------------------------
    a = AverageTrueRange[100]
    arrowOffset = a * 0.5
    
    IF sigL THEN
       DRAWARROWUP(barindex, low - arrowOffset) COLOURED(BreakUpR, BreakUpG, BreakUpB)
    ENDIF
    
    IF sigS THEN
       DRAWARROWDOWN(barindex, high + arrowOffset) COLOURED(BreakDnR, BreakDnG, BreakDnB)
    ENDIF
    
    //-------------------------------------------
    RETURN Fib1 COLOURED(plotRfib1, plotGfib1, plotBfib1, plotAfib1) AS "Fib 61.8" STYLE(line, 1), Fib2 COLOURED(plotRfib2, plotGfib2, plotBfib2, plotAfib2) AS "Fib 78.6" STYLE(line, 1),Fib3 COLOURED(plotRfib3, plotGfib3, plotBfib3, plotAfib3) AS "Fib 88.6" STYLE(line, 1),Trail COLOURED(plotRtrail, plotGtrail, plotBtrail, plotAtrail) AS "Trailing Stop" STYLE(line, 3)
    
    #252787 quote
    Pedro.lopez
    Participant
    Junior

    Disculpa, Roberto. Tomo nota.
    Muchas gracias.
    Pedro Lopez

    #252788 quote
    Pedro.lopez
    Participant
    Junior

    Hola, Ivan.
    Muchisimas gracias por tu tan rapida respuesta y por el codigo!!! Ole, ole y ole!!!!
    Me atasque en la parte de los array y entre en bucle, llevaba unos cuantos dias sin avanzar en la “traduccion”.
    Pedro Lopez

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.

Heatmap Trailing Stop with Breakouts. Conversion from pinescript to prorealtime


ProBuilder: Indicadores y Herramientas

New Reply
Author
Summary

This topic contains 5 replies,
has 3 voices, and was last updated by Pedro.lopez
3 months, 2 weeks ago.

Topic Details
Forum: ProBuilder: Indicadores y Herramientas
Language: Spanish
Started: 10/19/2025
Status: Active
Attachments: 7 files
Logo Logo
Loading...