StealthTrail SuperTrend [WillyAlgoTrader]

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #259519 quote
    Harley82
    Participant
    Average

    Buongiorno

    vorrei chiedere se possibile la conversione di questo codice pinescript (trading view) che rappresenta un indicatore da aggiungere al grafico del prezzo.Si tratta di un indicatore di trend following avanzato, progettato per migliorare il classico SuperTrend riducendo i falsi segnali (rumore) e adattandosi alla volatilità del mercato.

    Grazie

    //@version=6

    // ══════════════════════════════════════════════════════════

    // STEALTHTRAIL SUPERTREND [WillyAlgoTrader]

    // ══════════════════════════════════════════════════════════

    // Author: Willy | WillyAlgoTrader

    // Version: 1.1.0


    indicator(

      title      = “StealthTrail SuperTrend [WillyAlgoTrader]”,

      shorttitle    = “StealthTrail”,

      overlay     = true,

      max_labels_count = 500,

      max_lines_count = 500)


    // ══════════════════════════════════════

    // CONSTANTS

    // ══════════════════════════════════════

    GRP_MAIN  = “⚙️ Main Settings”

    GRP_FILTER = “🔍 Filters”

    GRP_VISUAL = “🎨 Visual Settings”

    GRP_DASH  = “📊 Dashboard”

    GRP_ALERT = “🔔 Alerts”

    GRP_COLORS = “🎨 Colors”

    GRP_ADV  = “🔧 Advanced”


    INDICATOR_VERSION = “v1.1.0”


    // ══════════════════════════════════════

    // INPUTS

    // ══════════════════════════════════════


    // ── Main Settings ───────────────────────────────────────

    atrLengthInput = input.int(13, “ATR Length”, minval = 1, maxval = 200, group = GRP_MAIN, tooltip = “Period for ATR calculation.n• Higher = smoother bands, fewer whipsawsn• Lower = faster response, more noisen• Recommended: 10–20”)

    baseMultInput = input.float(2.5, “Base Multiplier”, minval = 0.5, maxval = 8.0, step = 0.1, group = GRP_MAIN, tooltip = “Base multiplier for ATR bands.n• Higher = wider bands, fewer signalsn• Lower = tighter bands, more signalsn• Recommended: 2.0–3.5”)

    adaptiveInput = input.bool(true, “Adaptive Multiplier”, group = GRP_MAIN, tooltip = “Dynamically scale the multiplier based on current volatility relative to its average.n• ON: bands widen in high-vol, tighten in low-voln• OFF: fixed multiplier (classic SuperTrend)”)

    adaptSmoothInput = input.int(55, “Adaptation Smoothing”, minval = 10, maxval = 200, group = GRP_MAIN, tooltip = “Lookback for the volatility baseline (SMA of ATR).n• Higher = slower adaptationn• Lower = faster adaptationn• Recommended: 30–80”)


    // ── Filters ─────────────────────────────────────────────

    cushionInput = input.float(0.15, “Flip Cushion (×ATR)”, minval = 0.0, maxval = 1.0, step = 0.05, group = GRP_FILTER, tooltip = “Extra distance beyond the band required for a trend flip.n• Higher = fewer whipsaws, slightly later entriesn• 0.0 = classic behavior (flip exactly at band)n• Recommended: 0.1–0.3”)

    cooldownInput = input.int(3, “Signal Cooldown (bars)”, minval = 0, maxval = 20, group = GRP_FILTER, tooltip = “Minimum bars between trend flips.n• Prevents rapid back-and-forth signals in chopn• 0 = no cooldownn• Recommended: 2–5”)

    useMomentumInput = input.bool(true, “Momentum Filter (RSI)”, group = GRP_FILTER, tooltip = “Require RSI momentum confirmation for trend changes.n• Bullish flip requires RSI > thresholdn• Bearish flip requires RSI < (100 – threshold)n• Reduces false signals in ranging markets”)

    rsiLengthInput = input.int(13, “RSI Length”, minval = 2, maxval = 50, group = GRP_FILTER, tooltip = “Period for RSI calculation.n• Recommended: 14”)

    rsiThreshInput = input.float(45.0, “RSI Threshold”, minval = 30.0, maxval = 60.0, step = 1.0, group = GRP_FILTER, tooltip = “Minimum RSI for bullish confirmation.n• Bearish threshold = 100 – this valuen• Lower = more permissiven• Higher = stricter filtern• Recommended: 40–50”)

    useVolumeInput = input.bool(false, “Volume Filter”, group = GRP_FILTER, tooltip = “Require above-average volume for signal confirmation.n• Auto-disabled on instruments with no volume data (forex)n• Recommended for stocks and crypto”)

    volMultInput = input.float(1.2, “Volume Multiplier”, minval = 0.5, maxval = 3.0, step = 0.1, group = GRP_FILTER, tooltip = “Volume must exceed SMA(volume, 20) × this multiplier.n• Higher = stricter volume requirementn• Recommended: 1.0–1.5”)


    // ── Visual Settings ─────────────────────────────────────

    themeInput = input.string(“Auto”, “Theme”, options = [“Auto”, “Dark”, “Light”], group = GRP_VISUAL, tooltip = “Chart color theme.n• Auto: detects from chart backgroundn• Dark: optimized for dark backgroundsn• Light: optimized for light/white backgrounds”)

    showSignalsInput = input.bool(true, “Show Buy/Sell Signals”, group = GRP_VISUAL, tooltip = “Display confirmed BUY/SELL labels on chart”)

    showFilteredInput = input.bool(false, “Show Filtered Flips”, group = GRP_VISUAL, tooltip = “Show a muted dot when a trend flip was blocked by filters.n• Useful for understanding why a signal was skipped”)

    showBandInput = input.bool(true, “Show SuperTrend Band”, group = GRP_VISUAL, tooltip = “Display the adaptive SuperTrend band line”)

    showFillInput = input.bool(true, “Show Gradient Fill”, group = GRP_VISUAL, tooltip = “Display gradient fill between price and band”)

    showStrengthBgInput = input.bool(false, “Show Trend Background”, group = GRP_VISUAL, tooltip = “Tint chart background based on trend direction”)

    showWatermarkInput = input.bool(true, “Show Watermark”, group = GRP_VISUAL, tooltip = “Display ‘WillyAlgoTrader – by Willy’ watermark on chart”)


    // ── Dashboard ───────────────────────────────────────────

    showDashInput = input.bool(true, “Show Dashboard”, group = GRP_DASH, tooltip = “Display information panel with trend, signal, and strength data”)

    dashPosStr = input.string(“Top Right”, “Dashboard Position”, options = [“Top Left”, “Top Right”, “Bottom Left”, “Bottom Right”], group = GRP_DASH, tooltip = “Position of the dashboard on chart”)


    // ── Alerts ──────────────────────────────────────────────

    webhookInput = input.bool(false, “Webhook JSON Format”, group = GRP_ALERT, tooltip = “Send alerts in JSON format for webhook/bot integrations.n• OFF: human-readable text with emojisn• ON: machine-parseable JSON”)


    // ── Colors ──────────────────────────────────────────────

    bullColorInput = input.color(#00E676, “Bull”, inline = “colors”, group = GRP_COLORS, tooltip = “Color for bullish signals, bands, and fills”)

    bearColorInput = input.color(#FF5252, “Bear”, inline = “colors”, group = GRP_COLORS, tooltip = “Color for bearish signals, bands, and fills”)


    // ── Advanced ────────────────────────────────────────────

    minMultInput = input.float(1.0, “Min Adaptive Mult”, minval = 0.3, maxval = 5.0, step = 0.1, group = GRP_ADV, tooltip = “Floor for adaptive multiplier.n• Prevents bands from collapsing in ultra-low volatilityn• Recommended: 0.8–1.5”)

    maxMultInput = input.float(5.0, “Max Adaptive Mult”, minval = 2.0, maxval = 10.0, step = 0.5, group = GRP_ADV, tooltip = “Ceiling for adaptive multiplier.n• Prevents bands from becoming unreasonably widen• Recommended: 4.0–6.0”)


    // ══════════════════════════════════════

    // THEME DETECTION & COLORS

    // ══════════════════════════════════════

    isDark = switch themeInput

      “Dark” => true

      “Light” => false

      => color.r(chart.bg_color) < 128


    TEXT_COLOR  = isDark ? #E0E0E0 : #1A1A1A

    TEXT_MUTED  = isDark ? color.new(#9E9E9E, 0) : color.new(#757575, 0)

    TEXT_BRIGHT  = isDark ? #FFFFFF : #000000

    TABLE_BG   = isDark ? color.new(#131722, 5) : color.new(#FFFFFF, 5)

    TABLE_BORDER = isDark ? color.new(#2A2E39, 0) : color.new(#D0D0D0, 0)

    TABLE_ROW_ALT = isDark ? color.new(#1C2030, 0) : color.new(#F0F4F8, 0)

    HEADER_BG   = color.new(#2962FF, 0)

    HEADER_TEXT  = #FFFFFF

    LABEL_TEXT  = #FFFFFF

    LINE_SUBTLE  = isDark ? color.new(#555555, 0) : color.new(#AAAAAA, 0)

    WM_COLOR   = isDark ? color.new(#FFFFFF, 80) : color.new(#000000, 80)

    FILTERED_COLOR = isDark ? color.new(#888888, 30) : color.new(#999999, 30)


    // ══════════════════════════════════════

    // FUNCTIONS

    // ══════════════════════════════════════

    safeDiv(float num, float den, float fallback = 0.0) =>

      den != 0 and not na(num) and not na(den) ? num / den : fallback


    // Direction-aware trend strength: 0–100

    // distScore: how far price is from band (in ATR units) — max 50

    // momScore: RSI alignment with trend direction — max 50

    calcStrength(float price, float band, float atrV, float rsiV, int dir) =>

      float dist = safeDiv(math.abs(price – band), math.max(nz(atrV, 1.0), 1e-10)) * 20.0

      float distScore = math.min(dist, 50.0)

      float rsiSafe = nz(rsiV, 50.0)

      float momRaw = dir == 1 ? math.max(rsiSafe – 50.0, 0.0) : math.max(50.0 – rsiSafe, 0.0)

      float momScore = math.min(momRaw, 50.0)

      math.round(math.min(distScore + momScore, 100.0))


    // ══════════════════════════════════════

    // DASHBOARD POSITION

    // ══════════════════════════════════════

    dashPos = switch dashPosStr

      “Top Left”   => position.top_left

      “Top Right”  => position.top_right

      “Bottom Left” => position.bottom_left

      “Bottom Right” => position.bottom_right

      => position.top_right


    // ══════════════════════════════════════

    // CALCULATIONS

    // ══════════════════════════════════════


    // Warmup — no signals before indicator is primed

    int WARMUP_BARS = math.max(math.max(atrLengthInput, adaptSmoothInput), 50)

    bool isWarmedUp = bar_index >= WARMUP_BARS


    // ATR with safe early-bar fallback (use hl range when ATR is na)

    float atrRaw = ta.atr(atrLengthInput)

    float hlFallback = nz(high – low, 0.001)

    float atrVal = nz(atrRaw, hlFallback)


    // Adaptive multiplier: scale base mult by (currentATR / averageATR)

    float atrSma = nz(ta.sma(atrRaw, adaptSmoothInput), atrVal)

    float volRatio = atrSma > 0 ? atrVal / atrSma : 1.0

    float adaptiveMult = adaptiveInput ? math.max(minMultInput, math.min(maxMultInput, baseMultInput * volRatio)) : baseMultInput


    // SuperTrend core — bands always from hl2 for symmetry; close for flip detection

    float midPrice = hl2

    float upperBand = midPrice + adaptiveMult * atrVal

    float lowerBand = midPrice – adaptiveMult * atrVal


    // Trend state (var = persistent across bars)

    var int trendDir = 1

    var float stBand = na

    var int barsSinceFlip = 100


    barsSinceFlip := barsSinceFlip + 1


    // Previous band for ratcheting continuity

    float prevBand = nz(stBand[1], trendDir == 1 ? lowerBand : upperBand)


    // Flip cushion: require close beyond band by cushion × ATR

    float flipCushion = cushionInput * atrVal


    // Band ratcheting + trend flip logic with cushion and cooldown

    bool cooldownOk = barsSinceFlip >= cooldownInput


    if trendDir == 1

      stBand := math.max(lowerBand, prevBand)

      if close < (stBand – flipCushion) and cooldownOk

        trendDir  := -1

        stBand   := upperBand

        barsSinceFlip := 0

    else

      stBand := math.min(upperBand, prevBand)

      if close > (stBand + flipCushion) and cooldownOk

        trendDir  := 1

        stBand   := lowerBand

        barsSinceFlip := 0


    // Detect raw flip (before external filters)

    bool rawFlip = trendDir != nz(trendDir[1], trendDir)


    // ══════════════════════════════════════

    // MOMENTUM FILTER (RSI)

    // ══════════════════════════════════════

    float rsiVal = nz(ta.rsi(close, rsiLengthInput), 50.0)


    bool momentumOk = not useMomentumInput or (trendDir == 1 ? rsiVal >= rsiThreshInput : rsiVal <= (100.0 – rsiThreshInput))


    // ══════════════════════════════════════

    // VOLUME FILTER (only computed when enabled)

    // ══════════════════════════════════════

    bool hasVolume = nz(volume, 0) > 0

    float volSma = useVolumeInput and hasVolume ? nz(ta.sma(volume, 20), 0.0) : 0.0

    bool volumeOk = not useVolumeInput or not hasVolume or (volume > volSma * volMultInput)


    // ══════════════════════════════════════

    // SIGNAL LOGIC (confirmed + warmup + filters)

    // ══════════════════════════════════════


    // All external filters pass?

    bool filtersOk = momentumOk and volumeOk


    // Confirmed signal: raw flip + all filters + bar close confirmed + warmup

    bool confirmedBuy = rawFlip and trendDir == 1 and filtersOk and barstate.isconfirmed and isWarmedUp

    bool confirmedSell = rawFlip and trendDir == -1 and filtersOk and barstate.isconfirmed and isWarmedUp


    // Filtered flip: trend flipped but filters blocked the signal

    bool filteredFlip = rawFlip and not filtersOk and isWarmedUp


    // Track last signal for dashboard

    var string lastSignal = “—”

    var int barsSinceSignal = 0

    barsSinceSignal := barsSinceSignal + 1


    if confirmedBuy

      lastSignal   := “BUY”

      barsSinceSignal := 0

    if confirmedSell

      lastSignal   := “SELL”

      barsSinceSignal := 0


    // Trend strength (direction-aware)

    float strengthVal = calcStrength(close, nz(stBand, close), atrVal, rsiVal, trendDir)

    string strengthStr = strengthVal >= 70 ? “Strong” : strengthVal >= 40 ? “Medium” : “Weak”

    color strengthColor = strengthVal >= 70 ? bullColorInput : strengthVal >= 40 ? #FFEB3B : bearColorInput


    // ══════════════════════════════════════

    // PLOTS & VISUALS

    // ══════════════════════════════════════

    color bandColor = trendDir == 1 ? bullColorInput : bearColorInput


    // Band line

    plot(showBandInput ? stBand : na, “SuperTrend Band”, color = bandColor, linewidth = 2, style = plot.style_linebr)


    // Trend switch dot (confirmed signals only)

    plot(confirmedBuy or confirmedSell ? stBand : na, “Trend Switch”, color = bandColor, style = plot.style_circles, linewidth = 4, join = false)


    // Filtered flip dot (muted — shows where filter blocked)

    plot(showFilteredInput and filteredFlip and barstate.isconfirmed ? stBand : na, “Filtered Flip”, color = FILTERED_COLOR, style = plot.style_circles, linewidth = 3, join = false)


    // Gradient fill — anchor plots

    closePlot = plot(close, “Close”, color = na, display = display.none)

    bandPlot = plot(showFillInput ? stBand : na, “Band Fill”, color = na, display = display.none)


    float fillTop = math.max(close, nz(stBand, close))

    float fillBot = math.min(close, nz(stBand, close))

    color topFill = trendDir == 1 ? color.new(bullColorInput, 60) : color.new(bearColorInput, 100)

    color botFill = trendDir == 1 ? color.new(bullColorInput, 100) : color.new(bearColorInput, 60)


    fill(bandPlot, closePlot, fillTop, fillBot, topFill, botFill, title = “Trend Gradient”, display = showFillInput ? display.all : display.none)


    // Background tint

    bgcolor(showStrengthBgInput ? color.new(bandColor, 92) : na, title = “Trend Background”)


    // ══════════════════════════════════════

    // SIGNAL LABELS

    // ══════════════════════════════════════

    plotshape(showSignalsInput and confirmedBuy ? low : na, “Buy Signal”, style = shape.labelup, location = location.belowbar, color = bullColorInput, textcolor = LABEL_TEXT, text = “▲”, size = size.small)


    plotshape(showSignalsInput and confirmedSell ? high : na, “Sell Signal”, style = shape.labeldown, location = location.abovebar, color = bearColorInput, textcolor = LABEL_TEXT, text = “▼”, size = size.small)


    // ══════════════════════════════════════

    // DASHBOARD

    // ══════════════════════════════════════

    if showDashInput and barstate.islast

      var dashTable = table.new(dashPos, 2, 8, TABLE_BG, TABLE_BORDER, 1, TABLE_BORDER, 1)


      // Row 0: Header

      table.cell(dashTable, 0, 0, “WillyAlgoTrader”, text_color = HEADER_TEXT, bgcolor = HEADER_BG, text_size = size.small, text_halign = text.align_center)

      table.merge_cells(dashTable, 0, 0, 1, 0)


      // Row 1: Trend

      string trendStr = trendDir == 1 ? “Bullish” : “Bearish”

      color trendColor = trendDir == 1 ? bullColorInput : bearColorInput

      table.cell(dashTable, 0, 1, “Trend”, text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)

      table.cell(dashTable, 1, 1, trendStr, text_color = trendColor, text_size = size.small, bgcolor = TABLE_BG)


      // Row 2: Signal

      color sigColor = lastSignal == “BUY” ? bullColorInput : lastSignal == “SELL” ? bearColorInput : TEXT_MUTED

      string sigDisplay = lastSignal != “—” ? lastSignal + ” (” + str.tostring(barsSinceSignal) + ” bars ago)” : “—”

      table.cell(dashTable, 0, 2, “Signal”, text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_ROW_ALT)

      table.cell(dashTable, 1, 2, sigDisplay, text_color = sigColor, text_size = size.small, bgcolor = TABLE_ROW_ALT)


      // Row 3: Strength

      string strengthDisplay = na(strengthVal) ? “—” : str.tostring(strengthVal) + ” — ” + strengthStr

      table.cell(dashTable, 0, 3, “Strength”, text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)

      table.cell(dashTable, 1, 3, strengthDisplay, text_color = strengthColor, text_size = size.small, bgcolor = TABLE_BG)


      // Row 4: Adaptive Mult

      string multStr = na(adaptiveMult) ? “—” : str.tostring(adaptiveMult, “#.##”) + “x”

      table.cell(dashTable, 0, 4, “Multiplier”, text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_ROW_ALT)

      table.cell(dashTable, 1, 4, multStr, text_color = TEXT_COLOR, text_size = size.small, bgcolor = TABLE_ROW_ALT)


      // Row 5: RSI

      string rsiStr = na(rsiVal) ? “—” : str.tostring(rsiVal, “#.0”)

      color rsiColor = rsiVal >= 60 ? bullColorInput : rsiVal <= 40 ? bearColorInput : TEXT_COLOR

      table.cell(dashTable, 0, 5, “RSI”, text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)

      table.cell(dashTable, 1, 5, rsiStr, text_color = rsiColor, text_size = size.small, bgcolor = TABLE_BG)


      // Row 6: Timeframe

      table.cell(dashTable, 0, 6, “Timeframe”, text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_ROW_ALT)

      table.cell(dashTable, 1, 6, timeframe.period, text_color = TEXT_COLOR, text_size = size.small, bgcolor = TABLE_ROW_ALT)


      // Row 7: Version

      table.cell(dashTable, 0, 7, “Version”, text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)

      table.cell(dashTable, 1, 7, INDICATOR_VERSION, text_color = TEXT_MUTED, text_size = size.small, bgcolor = TABLE_BG)


    // ══════════════════════════════════════

    // WATERMARK — WillyAlgoTrader

    // ══════════════════════════════════════

    if barstate.islast and showWatermarkInput

      var wmTable = table.new(position = position.bottom_center, columns = 1, rows = 1, bgcolor = color.new(color.black, 100), border_color = color.new(color.black, 100), border_width = 0, frame_color = color.new(color.black, 100), frame_width = 0)

      table.cell(wmTable, 0, 0, “WillyAlgoTrader”, text_color = WM_COLOR, text_size = size.normal, text_halign = text.align_center, bgcolor = color.new(color.black, 100))


    // ══════════════════════════════════════

    // ALERTS

    // ══════════════════════════════════════

    string ticker = syminfo.tickerid

    string tf = timeframe.period

    string priceStr = str.tostring(close, format.mintick)

    string bandStr = na(stBand) ? “0” : str.tostring(stBand, format.mintick)

    string strStr = str.tostring(nz(strengthVal, 0))


    string buyJsonMsg = ‘{“action”:”buy”,”ticker”:”‘ + ticker + ‘”,”price”:’ + priceStr + ‘,”tf”:”‘ + tf + ‘”,”band”:’ + bandStr + ‘,”strength”:’ + strStr + ‘}’

    string buyTextMsg = “🟢 BUY | ” + ticker + ” | TF: ” + tf + ” | Price: ” + priceStr + ” | Band: ” + bandStr + ” | Strength: ” + strStr

    string buyMsg = webhookInput ? buyJsonMsg : buyTextMsg


    string sellJsonMsg = ‘{“action”:”sell”,”ticker”:”‘ + ticker + ‘”,”price”:’ + priceStr + ‘,”tf”:”‘ + tf + ‘”,”band”:’ + bandStr + ‘,”strength”:’ + strStr + ‘}’

    string sellTextMsg = “🔴 SELL | ” + ticker + ” | TF: ” + tf + ” | Price: ” + priceStr + ” | Band: ” + bandStr + ” | Strength: ” + strStr

    string sellMsg = webhookInput ? sellJsonMsg : sellTextMsg

    if confirmedBuy

    alert(buyMsg, alert.freq_once_per_bar_close)


    if confirmedSell

    alert(sellMsg, alert.freq_once_per_bar_close)



    #259560 quote
    Nicolas
    Keymaster
    Master

    Ciao, ecco qui sotto il codice tradotto. Per l’indicatore StealthTrail SuperTrend Aggiungi l’indicatore al grafico dei prezzi.

    // ============================================
    // StealthTrail SuperTrend — ProBuilder Port
    // Based on: WillyAlgoTrader 
    // www.prorealcode.com
    // Sharing ProRealTime Knowledge
    // ============================================
    
    
    // Parameters 
    atrLen = 13
    baseMult = 2.5
    adaptSmooth = 55
    cushion = 0.15
    cooldownBars = 3
    useRSI = 1       // 1 = RSI filter on, 0 = off
    rsiLen = 13
    rsiThresh = 45
    useVolume = 0    // 1 = volume filter on, 0 = off
    volMult = 1.2
    minMult = 1.0
    maxMult = 5.0
    
    
    if barindex>atrLen+rsiLen+adaptSmooth then 
    once stband=medianprice
    once upperband=high
    once lowerband=low
    
    
    // Warmup: no signals before indicators are primed
    warmup = MAX(MAX(atrLen, adaptSmooth), 50)
    
    
    // ATR and adaptive multiplier
    atrVal = AverageTrueRange[atrLen](close)
    atrSma = Average[adaptSmooth](atrVal)
    
    
    IF atrSma > 0 THEN
    volRatio = atrVal / atrSma
    ELSE
    volRatio = 1
    ENDIF
    
    
    adaptMult = MAX(minMult, MIN(maxMult, baseMult * volRatio))
    
    
    // Band calculation
    midPrice = (high + low) / 2
    upperBand = midPrice + adaptMult * atrVal
    lowerBand = midPrice - adaptMult * atrVal
    flipCushion = cushion * atrVal
    
    
    // Treat 0 (uninitialised) as bullish on the first bar
    IF trendDir[1] = 0 THEN
    prevDir = 1
    ELSE
    prevDir = trendDir[1]
    ENDIF
    
    
    // Cooldown counter: increments every bar, resets on a flip
    barsSinceFlip = barsSinceFlip[1] + 1
    
    
    // SuperTrend band ratcheting with flip cushion and cooldown
    IF prevDir = 1 THEN
    stBand = MAX(lowerBand, stBand[1])
    
    
    IF close < (stBand - flipCushion) AND barsSinceFlip >= cooldownBars THEN
    trendDir = -1
    stBand = upperBand
    barsSinceFlip = 0
    ELSE
    trendDir = 1
    ENDIF
    ELSE
    if stband[1]>0 then 
    stBand = MIN(upperBand, stBand[1])
    else
    stband = upperband
    endif 
    IF close > (stBand + flipCushion) AND barsSinceFlip >= cooldownBars THEN
    trendDir = 1
    stBand = lowerBand
    barsSinceFlip = 0
    ELSE
    trendDir = -1
    ENDIF
    ENDIF
    
    
    // RSI momentum filter
    rsiVal = RSI[rsiLen](close)
    IF useRSI = 1 THEN
    IF trendDir = 1 THEN
    momentumOk = (rsiVal >= rsiThresh)
    ELSE
    momentumOk = (rsiVal <= (100 - rsiThresh))
    ENDIF
    ELSE
    momentumOk = 1
    ENDIF
    
    
    // Volume filter
    volSma = Average[20](volume)
    IF useVolume = 1 AND volSma > 0 THEN
    volumeOk = (volume > volSma * volMult)
    ELSE
    volumeOk = 1
    ENDIF
    
    
    // Signal confirmation
    filtersOk = momentumOk AND volumeOk
    rawFlipUp   = (trendDir = 1  AND trendDir[1] = -1)
    rawFlipDown = (trendDir = -1 AND trendDir[1] = 1)
    
    
    confirmedBuy  = rawFlipUp   AND filtersOk AND (BarIndex >= warmup)
    confirmedSell = rawFlipDown AND filtersOk AND (BarIndex >= warmup)
    
    
    // Trend strength 0-100
    // Distance component: how far price is from band in ATR units (max 50)
    // Momentum component: RSI alignment with trend direction (max 50)
    IF atrVal > 0 THEN
    distScore = MIN(ABS(close - stBand) / atrVal * 20, 50)
    ELSE
    distScore = 0
    ENDIF
    
    
    IF trendDir = 1 THEN
    momRaw = MAX(rsiVal - 50, 0)
    ELSE
    momRaw = MAX(50 - rsiVal, 0)
    ENDIF
    momScore   = MIN(momRaw, 50)
    strengthVal = MIN(distScore + momScore, 100)-20
    
    
    // Buy/sell arrows
    IF confirmedBuy THEN
    DrawArrowUp(BarIndex, stband) COLOURED(0, 230, 118, 255)
    lastsignal=1
    ENDIF
    
    
    IF confirmedSell THEN
    DrawArrowDown(BarIndex, stband) COLOURED(255, 82, 82, 255)
    lastsignal=-1
    ENDIF
    
    
    // Band color by trend direction
    IF trendDir = 1 THEN
    r= 51
    g= 230 
    b= 111
    drawcandle(stband,close,stband,close) coloured(r,g,b,strengthval) bordercolor(0,0,0,0)
    ELSE
    r= 255
    g= 83
    b= 81
    drawcandle(stband,stband,close,close) coloured(r,g,b,strengthval) bordercolor(0,0,0,0)
    ENDIF
    endif 
    
    
    RETURN stBand COLOURED(r,g,b) AS "SuperTrend"
    
    Iván González thanked this post
    StealthTrail-SuperTrend.png StealthTrail-SuperTrend.png
    #259583 quote
    Harley82
    Participant
    Average

    Incredibile, dopo poco piu di tre ore già disponibile il nuovo codice, complimenti per l’eccellente servizio!

    Grazie.

    Iván González thanked this post
    #259591 quote
    Nicolas
    Keymaster
    Master

    A proposito, l’indicatore è ora disponibile anche nella libreria: scarica l’indicatore StealthTrail SuperTrend

    StealthTrail SuperTrend

    Iván González and robertogozzi thanked this post
Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.

TradingView to ProRealTime Translation Center

New Reply
Author
author-avatar
Harley82 @harley82 Participant
Summary

This topic contains 3 replies,
has 2 voices, and was last updated by Nicolas
1 week, 6 days ago.

Topic Details
Forum: TradingView to ProRealTime Translation Center Forum
Started: 03/27/2026
Status: Active
Attachments: 1 files
Logo Logo
Loading...