script("Adaptive Swingtrading pro", kind="indicator") input atrLength = 10 input baseMultiplier = 2.5 input adaptiveMultiplier = 1 input volatilityLookback = 50 input adaptationStrength = 0.4 input recoveryAlphaPercent = 8 input recoveryThreshold = 1 input acceleratedRecovery = 1 input showReentry = 1 input reentryDistance = 0.5 input useHTF = 1 input higherFrame = 604800 input htfOffset = 345600 input baseFrameSeconds = 0 input showHTFBand = 1 input momentumGate = 0 input rsiLength = 14 input bandSmoothness = 3 input showGradient = 1 input showSignals = 1 input showZoneLabels = 1 input colorCandles = 0 input showDashboard = 1 input showLegend = 1 input bullColor = "#2997FF" input bearColor = "#EF5350" input guardColor = "#FFA726" atrPeriod = math.clamp(math.floor(atrLength), 1, 200) rankPeriod = math.clamp(math.floor(volatilityLookback), 2, 200) rsiPeriod = math.clamp(math.floor(rsiLength), 1, 200) strength = math.clamp(adaptationStrength, 0, 1) baseMult = math.max(0.5, baseMultiplier) threshold = math.max(0, recoveryThreshold) baseAlpha = math.clamp(recoveryAlphaPercent / 100, 0.001, 1) nearDistance = math.max(0, reentryDistance) trueRange = ta.tr() atrSeed = ta.sma(trueRange, atrPeriod) atrValue = na(atrValue[1]) ? atrSeed : (atrValue[1] * (atrPeriod - 1) + trueRange) / atrPeriod // Mid-rank of the current ATR in a full window: ties give a neutral rank on flat data. var below = 0 var equal = 0 var samples = 0 for rankStep in 0..rankPeriod - 1 { if rankStep <= barIndex and not na(atrValue[rankStep]) { samples = samples + 1 below = below + (atrValue[rankStep] < atrValue ? 1 : 0) equal = equal + (atrValue[rankStep] == atrValue ? 1 : 0) } } atrRank = samples == rankPeriod ? (below + equal * 0.5) / samples : na multiplier = adaptiveMultiplier == 1 and not na(atrRank) ? math.max(0.5, baseMult - strength * (atrRank - 0.5) * 2) : baseMult ready = not na(atrValue) and (adaptiveMultiplier == 0 or not na(atrRank)) midPrice = (high + low) / 2 lowerCandidate = midPrice - multiplier * atrValue upperCandidate = midPrice + multiplier * atrValue rsi = ta.rsi(close, rsiPeriod) allowBull = momentumGate == 0 or (not na(rsi) and rsi > 50) allowBear = momentumGate == 0 or (not na(rsi) and rsi < 50) trend = nz(trend[1], 0) band = nz(band[1], na) flipPrice = nz(flipPrice[1], na) guard = nz(guard[1], 0) barsInTrend = nz(barsInTrend[1], 0) longSignal = 0 shortSignal = 0 guardStarted = 0 loss = na effectiveAlpha = baseAlpha if ready and isClosed { if trend == 0 { trend = close >= midPrice ? 1 : -1 flipPrice = close band = trend == 1 ? lowerCandidate : upperCandidate guard = 0 barsInTrend = 1 } else { reverse = trend == 1 ? close < band and allowBear : close > band and allowBull if reverse { trend = -trend flipPrice = close band = trend == 1 ? lowerCandidate : upperCandidate guard = 0 barsInTrend = 1 longSignal = trend == 1 ? 1 : 0 shortSignal = trend == -1 ? 1 : 0 } else { barsInTrend = barsInTrend + 1 loss = trend == 1 ? flipPrice - close : close - flipPrice guard = loss > threshold * atrValue ? 1 : 0 excess = math.max(0, loss - threshold * atrValue) effectiveAlpha = acceleratedRecovery == 1 and atrValue > 0 ? math.min(1, baseAlpha * (1 + excess / atrValue)) : baseAlpha if guard == 1 { band = effectiveAlpha * close + (1 - effectiveAlpha) * band } else { band = trend == 1 ? math.max(band, lowerCandidate) : math.min(band, upperCandidate) } guardStarted = guard == 1 and nz(guard[1], 0) == 0 ? 1 : 0 } } } reentry = isClosed and ready and guard == 1 and math.abs(close - band) <= nearDistance * atrValue reentrySignal = reentry and not nz(reentry[1], 0) // Replay an independent adaptive SuperTrend on completed higher-timeframe OHLC buckets. // Partial first buckets and buckets containing missing base bars are discarded. frame = math.clamp(math.floor(higherFrame), 60, 604800) observedFrame = barIndex > 0 ? time - time[1] : 0 baseFrame = baseFrameSeconds > 0 ? math.floor(baseFrameSeconds) : nz(baseFrame[1], 0) if baseFrame == 0 and observedFrame > 0 { baseFrame = observedFrame } frameValid = baseFrame > 0 and frame > baseFrame and math.floor(frame / baseFrame) * baseFrame == frame bucket = math.floor((time - htfOffset) / frame) * frame + htfOffset bucketFirst = nz(bucketFirst[1], time) bucketLast = nz(bucketLast[1], time) bucketCount = nz(bucketCount[1], 0) bucketClean = nz(bucketClean[1], 1) bucketHigh = nz(bucketHigh[1], high) bucketLow = nz(bucketLow[1], low) bucketClose = nz(bucketClose[1], close) htfBars = nz(htfBars[1], 0) htfAtrSum = nz(htfAtrSum[1], 0) htfAtr = nz(htfAtr[1], na) htfPreviousClose = nz(htfPreviousClose[1], na) htfTrend = nz(htfTrend[1], 0) htfBand = nz(htfBand[1], na) htfFlipPrice = nz(htfFlipPrice[1], na) htfRank = nz(htfRank[1], na) if useHTF == 1 { if barIndex > 0 and bucket != bucket[1] { completeBucket = frameValid and bucketFirst == bucket[1] and bucketLast + baseFrame == bucket[1] + frame and bucketCount * baseFrame == frame and bucketClean == 1 if completeBucket { htfRange = na(htfPreviousClose) ? bucketHigh - bucketLow : math.max(bucketHigh - bucketLow, math.max(math.abs(bucketHigh - htfPreviousClose), math.abs(bucketLow - htfPreviousClose))) htfBars = htfBars + 1 htfAtrSum = htfBars <= atrPeriod ? htfAtrSum + htfRange : htfAtrSum htfAtr = htfBars < atrPeriod ? na : htfBars == atrPeriod ? htfAtrSum / atrPeriod : (htfAtr * (atrPeriod - 1) + htfRange) / atrPeriod if not na(htfAtr) { if array.size("htfAtrHistory") >= rankPeriod { array.remove("htfAtrHistory", 0) } array.push("htfAtrHistory", htfAtr) var htfBelow = 0 var htfEqual = 0 for htfStep in 0..array.size("htfAtrHistory") - 1 { var oldAtr = array.get("htfAtrHistory", htfStep) htfBelow = htfBelow + (oldAtr < htfAtr ? 1 : 0) htfEqual = htfEqual + (oldAtr == htfAtr ? 1 : 0) } htfRank = array.size("htfAtrHistory") == rankPeriod ? (htfBelow + htfEqual * 0.5) / rankPeriod : na if adaptiveMultiplier == 0 or not na(htfRank) { var htfMult = adaptiveMultiplier == 1 ? math.max(0.5, baseMult - strength * (htfRank - 0.5) * 2) : baseMult var htfLower = (bucketHigh + bucketLow) / 2 - htfMult * htfAtr var htfUpper = (bucketHigh + bucketLow) / 2 + htfMult * htfAtr if htfTrend == 0 { htfTrend = bucketClose >= (bucketHigh + bucketLow) / 2 ? 1 : -1 htfBand = htfTrend == 1 ? htfLower : htfUpper htfFlipPrice = bucketClose } else { if (htfTrend == 1 and bucketClose < htfBand) or (htfTrend == -1 and bucketClose > htfBand) { htfTrend = -htfTrend htfBand = htfTrend == 1 ? htfLower : htfUpper htfFlipPrice = bucketClose } else { var htfLoss = htfTrend == 1 ? htfFlipPrice - bucketClose : bucketClose - htfFlipPrice if htfLoss > threshold * htfAtr { var htfExcess = math.max(0, htfLoss - threshold * htfAtr) var htfAlpha = acceleratedRecovery == 1 and htfAtr > 0 ? math.min(1, baseAlpha * (1 + htfExcess / htfAtr)) : baseAlpha htfBand = htfAlpha * bucketClose + (1 - htfAlpha) * htfBand } else { htfBand = htfTrend == 1 ? math.max(htfBand, htfLower) : math.min(htfBand, htfUpper) } } } } } htfPreviousClose = bucketClose } bucketFirst = time bucketCount = 0 bucketClean = 1 bucketHigh = high bucketLow = low } if bucketCount > 0 and time != bucketLast + baseFrame { bucketClean = 0 } bucketHigh = bucketCount == 0 ? high : math.max(bucketHigh, high) bucketLow = bucketCount == 0 ? low : math.min(bucketLow, low) bucketClose = close bucketLast = time bucketCount = bucketCount + 1 } htfAvailable = useHTF == 1 and frameValid and htfTrend != 0 and not na(htfBand) conflict = htfAvailable and htfTrend != trend aligned = htfAvailable and htfTrend == trend smoothed = ta.ema(band, math.clamp(math.floor(bandSmoothness), 1, 50)) bullBand = trend == 1 ? smoothed : na bearBand = trend == -1 ? smoothed : na bullAligned = trend == 1 and not conflict ? bullBand : na bearAligned = trend == -1 and not conflict ? bearBand : na bullConflict = trend == 1 and conflict ? bullBand : na bearConflict = trend == -1 and conflict ? bearBand : na fillPrice = showGradient == 1 ? close : na fillBull = showGradient == 1 ? bullAligned : na fillBear = showGradient == 1 ? bearAligned : na fillBullConflict = showGradient == 1 ? bullConflict : na fillBearConflict = showGradient == 1 ? bearConflict : na plot(bullAligned, title="Bullish band", color=bullColor, width=2) plot(bearAligned, title="Bearish band", color=bearColor, width=2) plot(bullConflict, title="Bullish HTF conflict", color=bullColor, width=2, opacity=0.35) plot(bearConflict, title="Bearish HTF conflict", color=bearColor, width=2, opacity=0.35) htfVisible = showHTFBand == 1 and htfAvailable ? htfBand : na plot(htfVisible, title="Closed HTF band", color="#9C88CE", width=1, style="step") fill(fillPrice, fillBull, color=bullColor, opacity=0.22, gradient=1) fill(fillPrice, fillBear, color=bearColor, opacity=0.22, gradient=1) fill(fillPrice, fillBullConflict, color=bullColor, opacity=0.07, gradient=1) fill(fillPrice, fillBearConflict, color=bearColor, opacity=0.07, gradient=1) guardBackground = showReentry == 1 and guard == 1 bgcolor(guardBackground, color=guardColor, opacity=0.10) plotShape(low, when=showSignals == 1 and longSignal == 1, shape="triangleUp", position="below", color=bullColor, size=6) plotShape(high, when=showSignals == 1 and shortSignal == 1, shape="triangleDown", position="above", color=bearColor, size=6) plotShape(low, when=showReentry == 1 and reentrySignal and trend == 1, shape="triangleUp", position="below", color=guardColor, size=5) plotShape(high, when=showReentry == 1 and reentrySignal and trend == -1, shape="triangleDown", position="above", color=guardColor, size=5) plotText(midPrice, when=showZoneLabels == 1 and longSignal == 1, text="BULL", color=bullColor, position="center") plotText(midPrice, when=showZoneLabels == 1 and shortSignal == 1, text="BEAR", color=bearColor, position="center") barcolor(colorCandles == 1 and trend == 1, color=bullColor) barcolor(colorCandles == 1 and trend == -1, color=bearColor) if showDashboard == 1 { table.cell("excavoInspired", 0, 0, "Adaptive ST ยท custom", position="top_right") table.cell("excavoInspired", 0, 1, trend == 1 ? "BULL" : trend == -1 ? "BEAR" : "Warming up", position="top_right") table.cell("excavoInspired", 1, 1, "Bars: " + barsInTrend, position="top_right") table.cell("excavoInspired", 0, 2, htfAvailable ? (htfTrend == 1 ? "HTF BULL" : "HTF BEAR") : "HTF unavailable / warming up", position="top_right") table.cell("excavoInspired", 1, 2, conflict ? "CONFLICT" : aligned ? "ALIGNED" : "NO HTF", position="top_right", color=conflict ? guardColor : "#D6D9E0") table.cell("excavoInspired", 0, 3, guard == 1 ? (reentry ? "Guard: Active / Re-entry" : "Guard: Active") : "Guard: Off", position="top_right", color=guard == 1 ? guardColor : "#D6D9E0") table.cell("excavoInspired", 0, 4, na(atrRank) ? "ATR rank: warming up" : "ATR rank: " + math.round(atrRank * 100) + "%", position="top_right") table.cell("excavoInspired", 1, 4, "Multiplier: " + math.round(multiplier * 100) / 100, position="top_right") } if showLegend == 1 { table.cell("excavoLegend", 0, 0, "Blue: BULL / Red: BEAR", position="bottom_left") table.cell("excavoLegend", 0, 1, "Orange: guard / re-entry", position="bottom_left") table.cell("excavoLegend", 0, 2, "Faded band: HTF conflict", position="bottom_left") } alertcondition(longSignal, title="Bullish trend", message="Independent adaptive SuperTrend: bullish flip") alertcondition(shortSignal, title="Bearish trend", message="Independent adaptive SuperTrend: bearish flip") alertcondition(longSignal == 1 or shortSignal == 1, title="Any trend change", message="Independent adaptive SuperTrend: trend changed") alertcondition(guardStarted, title="Guard activated", message="Independent adaptive SuperTrend: guard activated") alertcondition(reentrySignal, title="Re-entry zone", message="Independent adaptive SuperTrend: re-entry zone") alertcondition(longSignal == 1 and aligned, title="Bullish + HTF aligned", message="Independent adaptive SuperTrend: bullish aligned") alertcondition(shortSignal == 1 and aligned, title="Bearish + HTF aligned", message="Independent adaptive SuperTrend: bearish aligned")