本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This script is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
// https://creativecommons.org/licenses/by-nc-sa/4.0/
// © QuantAlgo
//@version=6
indicator("Bilateral Filter Trend [QuantAlgo]", overlay = true, max_bars_back = 500)
// ╔════════════════════════════════╗ //
// ║ USER-DEFINED SETTINGS ║ //
// ╚════════════════════════════════╝ //
var string filter_settings = "════════ Bilateral Filter Settings ════════"
var string visual_settings = "════════ Visualization Settings ════════"
tooltip_preset = "Select a predefined configuration for different trading styles and timeframes. Fast Response and Smooth Trend set the Window Length, Time Sigma, Range Sigma, and Reversal Threshold, overriding those inputs below. Spike Rejection, Source, and all visualization inputs keep their manual values."
tooltip_preset_det = "Default: Uses the manual settings below, with the Window Length, Time Sigma, Range Sigma, and Reversal Threshold adjustable directly. Suited to swing trading on 1H to daily charts.\n\nFast Response (Window 25, Time Sigma 6.0, Range Sigma 1.0, Reversal 1.0): Shortens the window and narrows both kernels, and the narrower range kernel also shortens the retrace needed to confirm a reversal, so the filter tracks price closely and trend changes confirm sooner. Suited to intraday trading on 5min to 1H charts.\n\nSmooth Trend (Window 60, Time Sigma 12.0, Range Sigma 1.5, Reversal 1.75): Lengthens the window, widens the time kernel, and raises the reversal threshold, so trends hold through deeper pullbacks and trend changes confirm less often. Suited to position trading on daily and weekly charts."
tooltip_window = "Number of bars the filter weighs on every bar, which sets how much history it can draw on. Each bar inside the window contributes according to both kernels. Longer windows give the time kernel more history and allow a smoother path when Time Sigma is raised with them. Shorter windows keep the filter focused on recent price and reduce lag. Bars more than about three Time Sigma widths back receive almost no weight, so extending the window beyond that point adds little."
tooltip_time_sigma = "Width, in bars, of the time kernel. Each bar's weight decays with its distance from the current bar along a Gaussian curve of this width, so recent bars count the most. Higher values (12-20) spread weight across more history and smooth the path. Lower values (4-8) concentrate weight on the most recent bars and respond faster. Keep Window Length at roughly three times this value or more so the curve is not cut short."
tooltip_range_sigma = "Width of the range kernel, as a multiple of the 14-bar Average True Range. Each bar's weight also decays with its price distance from the current reference level, so bars that traded far from that level contribute little. Lower values (0.5-1.0) treat smaller price gaps as a separate level, so the filter reaches a new level sooner after a breakout but also follows swings inside a range more closely. Higher values (2.0-3.0) let the filter average across wider price gaps, smoothing over swings inside a range but reaching a new level more slowly, closer to the behavior of a conventional moving average. The same width sets the similarity band and the size of the reversal distance, so lower values also confirm trend changes on smaller retraces."
tooltip_reversal = "How far the filter must retrace from the extreme of the current trend to confirm a reversal, measured in range kernel widths, so this reversal distance scales with volatility. A bullish trend turns bearish on the closed bar where the filter has fallen the reversal distance below its highest level since the trend began, and a bearish trend turns bullish on the closed bar where it has risen the reversal distance above its lowest level since that trend began. The first trend is set the same way, from the highest and lowest levels the filter has reached since its first value. Higher values (1.5-2.5) ride through deeper pullbacks and produce fewer trend changes. Lower values (0.5-0.75) confirm reversals sooner and produce more trend changes."
tooltip_spike = "Enable/disable measuring price distance against the median of the last three source values rather than the current value alone. When enabled, a single isolated spike sits far from the reference and receives little weight, while a move that holds for two bars shifts the reference and is followed promptly. When disabled, the current value is always the reference, so the filter responds to every bar at once, including one-bar spikes."
tooltip_source = "The price series the filter smooths, with every value in the window weighted by both kernels. Close follows settled bar values, while averaged sources such as HL2 or HLC3 soften individual closing prints before they reach the filter. The range kernel width and the reversal distance are always scaled by the Average True Range of the chart's own bars, whichever source is selected."
tooltip_color_preset = "Pre-configured color schemes for different chart themes and visual preferences. Classic uses traditional green and red. Aqua provides ocean-inspired blue and orange. Cosmic offers futuristic cyan and purple. Cyber features cool cyan and warm orange contrast. Neon delivers high-contrast yellow and magenta for maximum visibility. Custom uses the Bullish and Bearish colors set below. Before the first trend is confirmed, the filter line, glow, and band use a neutral color that contrasts with the chart background."
tooltip_bullish = "Color applied to the filter line, filter glow, similarity band, price bars, and background while the trend is bullish, which is confirmed on the closed bar where the filter has risen the reversal distance above its lowest level. Use a vibrant color to highlight uptrend phases and potential long opportunities. Only used when Color Preset is set to Custom."
tooltip_bearish = "Color applied to the filter line, filter glow, similarity band, price bars, and background while the trend is bearish, which is confirmed on the closed bar where the filter has fallen the reversal distance below its highest level. Use a warning color to highlight downtrend phases and potential short opportunities or exits. Only used when Color Preset is set to Custom."
tooltip_glow = "Enable/disable the soft glow around the filter line. The glow brightens as the range kernel sets aside more of the window's history, which happens as price moves away from the levels it traded at earlier in the window, so a breakout in either direction stands out as it develops. Disable for a thinner line that keeps the focus on price action."
tooltip_band = "Enable/disable the similarity band, shaded one range kernel width above and below the filter and fading outward from the line. It shows the scale of the range kernel on the chart: bars whose prices sit within about this distance of the current reference level keep most of their weight, while bars farther away lose weight quickly. Its width follows Range Sigma and current volatility."
tooltip_barcolor = "Enable/disable bar coloring based on the current trend. When enabled, price bars are tinted with the bullish or bearish color, providing instant visual confirmation of the trend without reading the filter line directly. Disable if you prefer default bar colors or use another bar coloring indicator."
tooltip_bartrans = "Transparency of the bar coloring overlay. Lower values (0-30) produce vivid, fully saturated bars that make the trend immediately obvious. Higher values (70-90) apply a subtle tint that shows the trend without overwhelming price action. Only applies when Enable Bar Coloring is turned on."
tooltip_bgcolor = "Enable/disable background coloring based on the current trend. When enabled, the chart background is shaded with the bullish or bearish color, highlighting each trend across the full height of the chart. Disable if you prefer a clean chart background or use another background coloring indicator."
tooltip_bgtrans = "Transparency of the background coloring. Lower values (50-70) produce strong shading that makes each trend stand out immediately. Higher values (85-95) apply a subtle tint that keeps price action and other chart elements easy to read. Only applies when Enable Background Coloring is turned on."
presetMode = input.string("Default", "Preset Configuration", group = filter_settings, options = ["Default", "Fast Response", "Smooth Trend"], tooltip = tooltip_preset + "\n\n" + tooltip_preset_det)
windowIn = input.int(40, "Window Length", group = filter_settings, minval = 5, maxval = 300, tooltip = tooltip_window)
timeSigmaIn = input.float(10.0, "Time Sigma", group = filter_settings, minval = 1.0, step = 0.5, tooltip = tooltip_time_sigma)
rangeSigmaIn = input.float(1.5, "Range Sigma", group = filter_settings, minval = 0.1, step = 0.1, tooltip = tooltip_range_sigma)
reversalIn = input.float(1.0, "Reversal Threshold", group = filter_settings, minval = 0.1, step = 0.05, tooltip = tooltip_reversal)
spikeReject = input.bool(true, "Spike Rejection", group = filter_settings, tooltip = tooltip_spike)
src = input.source(close, "Source", group = filter_settings, tooltip = tooltip_source)
colorPreset = input.string("Custom", "Color Preset", group = visual_settings, options = ["Custom", "Classic", "Aqua", "Cosmic", "Cyber", "Neon"], tooltip = tooltip_color_preset)
bullCustom = input.color(#00ffaa, "Bullish Color", group = visual_settings, tooltip = tooltip_bullish)
bearCustom = input.color(#ff0000, "Bearish Color", group = visual_settings, tooltip = tooltip_bearish)
showGlow = input.bool(true, "Show Filter Glow", group = visual_settings, tooltip = tooltip_glow)
showBand = input.bool(true, "Show Similarity Band", group = visual_settings, tooltip = tooltip_band)
colorBars = input.bool(false, "Enable Bar Coloring", group = visual_settings, tooltip = tooltip_barcolor)
barTrans = input.int(0, "Bar Color Transparency", group = visual_settings, minval = 0, maxval = 100, tooltip = tooltip_bartrans)
colorBg = input.bool(false, "Enable Background Coloring", group = visual_settings, tooltip = tooltip_bgcolor)
bgTrans = input.int(90, "Background Color Transparency", group = visual_settings, minval = 0, maxval = 100, tooltip = tooltip_bgtrans)
// ╔════════════════════════════════╗ //
// ║ PRESET CONFIGURATION ║ //
// ╚════════════════════════════════╝ //
int windowLen = switch presetMode
"Fast Response" => 25
"Smooth Trend" => 60
=> windowIn
float timeSigma = switch presetMode
"Fast Response" => 6.0
"Smooth Trend" => 12.0
=> timeSigmaIn
float rangeSigmaMult = switch presetMode
"Fast Response" => 1.0
"Smooth Trend" => 1.5
=> rangeSigmaIn
float reversalMult = switch presetMode
"Fast Response" => 1.0
"Smooth Trend" => 1.75
=> reversalIn
// ╔════════════════════════════════╗ //
// ║ BILATERAL FILTER ENGINE ║ //
// ╚════════════════════════════════╝ //
float atrValue = ta.atr(14)
float rangeSigma = rangeSigmaMult * atrValue
float priorOne = nz(src[1], src)
float priorTwo = nz(src[2], priorOne)
float medianRef = math.max(math.min(src, priorOne), math.min(math.max(src, priorOne), priorTwo))
float reference = spikeReject ? medianRef : src
float weightSum = 0.0
float valueSum = 0.0
float timeSum = 0.0
int span = math.min(windowLen, bar_index + 1)
if rangeSigma > 0
for i = 0 to span - 1
float sample = src[i]
if not na(sample)
float timeWeight = math.exp(-0.5 * i * i / (timeSigma * timeSigma))
float distance = (sample - reference) / rangeSigma
float weight = timeWeight * math.exp(-0.5 * distance * distance)
weightSum += weight
valueSum += weight * sample
timeSum += timeWeight
float filtered = weightSum > 0 ? valueSum / weightSum : na
float edgeStrength = timeSum > 0 ? 1.0 - weightSum / timeSum : 0.0
// ╔════════════════════════════════╗ //
// ║ TREND STATE ENGINE ║ //
// ╚════════════════════════════════╝ //
var int signalState = 0
var float peakLevel = na
var float troughLevel = na
float reversalDistance = reversalMult * rangeSigma
if barstate.isconfirmed and not na(filtered)
if signalState == 0
peakLevel := na(peakLevel) ? filtered : math.max(peakLevel, filtered)
troughLevel := na(troughLevel) ? filtered : math.min(troughLevel, filtered)
if filtered >= troughLevel + reversalDistance
signalState := 1
peakLevel := filtered
else if filtered <= peakLevel - reversalDistance
signalState := -1
troughLevel := filtered
else if signalState == 1
peakLevel := math.max(peakLevel, filtered)
if filtered <= peakLevel - reversalDistance
signalState := -1
troughLevel := filtered
else
troughLevel := math.min(troughLevel, filtered)
if filtered >= troughLevel + reversalDistance
signalState := 1
peakLevel := filtered
// ╔════════════════════════════════╗ //
// ║ SIGNAL ENGINE ║ //
// ╚════════════════════════════════╝ //
int prevState = nz(signalState[1])
bool turnedBull = signalState == 1 and prevState != 1
bool turnedBear = signalState == -1 and prevState != -1
bool signalChanged = turnedBull or turnedBear
// ╔════════════════════════════════╗ //
// ║ VISUALIZATION ║ //
// ╚════════════════════════════════╝ //
[bullCol, bearCol] = switch colorPreset
"Classic" => [#00ff00, #ff0000]
"Aqua" => [#00d4ff, #ff8c00]
"Cosmic" => [#49ffce, #9932cc]
"Cyber" => [#00cccc, #ff6600]
"Neon" => [#ffff00, #ff00ff]
=> [bullCustom, bearCustom]
color signalColor = signalState == 1 ? bullCol : signalState == -1 ? bearCol : chart.fg_color
float bandUpper = showBand ? filtered + rangeSigma : na
float bandLower = showBand ? filtered - rangeSigma : na
plot(showGlow ? filtered : na, "Filter Halo", color.new(signalColor, 88 - 30 * edgeStrength), 8, editable = false, display = display.pane)
plot(showGlow ? filtered : na, "Filter Glow", color.new(signalColor, 72 - 30 * edgeStrength), 4, editable = false, display = display.pane)
filterPlot = plot(filtered, "Bilateral Filter", signalColor, 2)
upperPlot = plot(bandUpper, "Similarity Upper", display = display.none, editable = false)
lowerPlot = plot(bandLower, "Similarity Lower", display = display.none, editable = false)
fill(upperPlot, filterPlot, top_value = bandUpper, bottom_value = filtered, top_color = color.new(signalColor, 100), bottom_color = color.new(signalColor, 80), title = "Similarity Band Upper")
fill(filterPlot, lowerPlot, top_value = filtered, bottom_value = bandLower, top_color = color.new(signalColor, 80), bottom_color = color.new(signalColor, 100), title = "Similarity Band Lower")
barcolor(colorBars and signalState != 0 ? color.new(signalColor, barTrans) : na, title = "Trend Bar Color")
bgcolor(colorBg and signalState != 0 ? color.new(signalColor, bgTrans) : na, title = "Trend Background Color")
// ╔════════════════════════════════╗ //
// ║ ALERTS ║ //
// ╚════════════════════════════════╝ //
alertcondition(turnedBull, title = "Bullish Trend Signal", message = "Bilateral Filter Trend: BULLISH trend confirmed on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(turnedBear, title = "Bearish Trend Signal", message = "Bilateral Filter Trend: BEARISH trend confirmed on {{exchange}}:{{ticker}} - {{interval}}")
alertcondition(signalChanged, title = "Any Trend Change", message = "Bilateral Filter Trend: Trend signal changed on {{exchange}}:{{ticker}} - {{interval}}")
// ╔════════════════════════════════╗ //
// ║ CREATED BY ║ //
// ╚════════════════════════════════╝ //
// ██████╗ ██╗ ██╗ █████╗ ███╗ ██╗████████╗ █████╗ ██╗ ██████╗ ██████╗
//██╔═══██╗██║ ██║██╔══██╗████╗ ██║╚══██╔══╝ ██╔══██╗██║ ██╔════╝ ██╔═══██╗
//██║ ██║██║ ██║███████║██╔██╗ ██║ ██║ ███████║██║ ██║ ███╗██║ ██║
//██║▄▄ ██║██║ ██║██╔══██║██║╚██╗██║ ██║ ██╔══██║██║ ██║ ██║██║ ██║
//╚██████╔╝╚██████╔╝██║ ██║██║ ╚████║ ██║ ██║ ██║███████╗╚██████╔╝╚██████╔╝
// ╚══▀▀═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝