Indicador

Nadaraya-Watson Trend [QuantAlgo]🟢 Overview
The Nadaraya-Watson Trend indicator estimates a smooth, adaptive trend path by applying non-parametric kernel regression directly to price. For each bar it weights historical values inside a configurable lookback window with a chosen kernel function, normalizes those weights, and returns a single endpoint estimate that forms the plotted trend line. Bandwidth and kernel type control how aggressively recent bars dominate the estimate, optional residual bands express how far price is dispersed around that path, and slope based coloring with reversal markers make direction and turning points readable at a glance across any timeframe or instrument.
🟢 How It Works
The indicator is built around a one sided Nadaraya-Watson (NW) estimator: only the current bar and past bars enter the calculation, so the path behaves as a causal smoother rather than a centered, repainting fit. The pipeline has three stages: kernel weighting over the lookback window, normalized regression into a single trend value, and optional residual band construction from the same estimate.
First, effective bandwidth is formed from the configured bandwidth and multiplier. Each lag distance is then mapped to a kernel weight. Gaussian and Rational Quadratic keep infinite support with different decay shapes. Compact kernels (Epanechnikov, Triangular, Quartic, Cosine) only assign weight while the normalized lag stays inside the unit interval:
kernel_weight(float dist, float h, string ktype, float rq) =>
float w = 0.0
if h > 0.0
float u = dist / h
if ktype == 'Gaussian'
w := math.exp(-(dist * dist) / (2.0 * h * h))
else if ktype == 'Rational Quadratic'
w := math.pow(1.0 + (dist * dist) / (2.0 * rq * h * h), -rq)
else if math.abs(u) <= 1.0
if ktype == 'Epanechnikov'
w := 0.75 * (1.0 - u * u)
else if ktype == 'Triangular'
w := 1.0 - math.abs(u)
else if ktype == 'Quartic'
w := (15.0 / 16.0) * math.pow(1.0 - u * u, 2.0)
else if ktype == 'Cosine'
w := (math.pi / 4.0) * math.cos(math.pi * u / 2.0)
w
float h = bandwidth * h_mult
Next, the Nadaraya-Watson path is computed as the normalized weighted average of the selected source across the lookback window. Nearer bars dominate when bandwidth is low. Weight spreads more evenly when bandwidth is high, producing a smoother path:
float sum_w = 0.0
float sum_p = 0.0
for i = 0 to lookback
float w = kernel_weight(i, h, kernel_type, rel_weight)
sum_w += w
sum_p += src * w
float nw_trend = sum_w != 0.0 ? sum_p / sum_w : na
Finally, residual bands can be drawn from a kernel weighted mean absolute residual of the source versus the current NW estimate, scaled by the band multiplier. When price is tightly clustered around the path the envelope contracts. When price is dispersed the envelope expands, framing extension and compression relative to the same estimator that defines the trend:
float sum_abs = 0.0
float sum_res_w = 0.0
for i = 0 to lookback
float w = kernel_weight(i, h, kernel_type, rel_weight)
if w > 0.0 and not na(src ) and not na(nw_trend)
sum_abs += w * math.abs(src - nw_trend)
sum_res_w += w
float residual = sum_res_w != 0.0 ? sum_abs / sum_res_w : na
float upper = not na(nw_trend) and not na(residual) ? nw_trend + residual * band_mult : na
float lower = not na(nw_trend) and not na(residual) ? nw_trend - residual * band_mult : na
🟢 Signal Interpretation
▶ Bullish Path (Rising NW Line with Bullish Color): When the Nadaraya-Watson estimate is increasing bar to bar, the path and optional gradient fill plot in the bullish color, reading as an uptrend in the kernel smoothed series. Treat this as a long bias: strongest on the reversal marker with price holding above the path, or on pullbacks that respect the path while slope stays up. Bias weakens if price loses the path and the slope flattens or flips down.
▶ Bearish Path (Falling NW Line with Bearish Color): When the estimate is decreasing bar to bar, the path and fill plot in the bearish color, reading as a downtrend in the kernel smoothed series. Treat this as a short bias: strongest on the reversal marker with price holding below the path, or on bounces that fail at the path while slope stays down. Bias weakens if price reclaims the path and the slope flattens or flips up.
▶ Residual Bands (Optional Envelope Around the Path): With residual bands enabled, the upper and lower lines track a scaled kernel weighted residual around the NW path. Touches or closes beyond the outer band highlight price stretched away from the estimate. Returns toward the path after an extension often mark mean reversion relative to the kernel trend rather than a full regime change. Band width is derived from how widely the source has been scattered around the current NW estimate inside the lookback window
🟢 Features
▶ Preconfigured Presets: Three parameter sets tuned for different trading styles and timeframes. "Default" delivers balanced trend estimation for swing trading on 1H to daily charts, smoothing short lived noise while still responding to genuine directional turns. "Fast Response" is built for intraday work on 5 minute to 1H charts, keeping the path tighter to recent structure so turns register earlier at the cost of more frequent reversals in chop. "Smooth Trend" is aimed at position style reading on daily and weekly charts, forming a more stable baseline that flips only when the kernel path itself shifts with more conviction. Kernel type, residual bands, and visual options stay independently configurable under every preset.
▶ Kernel Library: Six kernel functions expand how the same endpoint Nadaraya-Watson framework assigns weight across the window. Gaussian is the classic smooth default with infinite support. Epanechnikov, Triangular, Quartic, and Cosine are compact kernels that fully exclude bars beyond the bandwidth scale. Rational Quadratic keeps infinite support with heavier tails, and its Relative Weighting input controls how much influence farther bars retain versus a Gaussian like decay. Switching kernels changes the shape of the single plotted path without adding a second model or external oscillator.
▶ Residual Bands: Optional envelope around the NW path built from kernel weighted mean absolute residuals of the source versus the estimate, scaled by Band Multiplier. Enable when you want extension and compression context around the same trend line. Disable when you want only the path, gradient, and markers.
▶ Built-in Alerts: Five alert conditions support hands off monitoring. "Bullish Kernel Reversal" fires on the bar the path slope flips from down to up. "Bearish Kernel Reversal" fires on the bar the path slope flips from up to down. "Any Kernel Reversal" fires on either directional flip. "Source Cross Above Upper Band" and "Source Cross Below Lower Band" fire when the selected source crosses the residual envelope extremes. Alert messages include exchange, ticker, and timeframe for immediate context.
▶ Visual Customisation: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) apply coordinated bullish and bearish colors to the path, gradient fill, residual bands, markers, optional bar coloring, and optional background coloring. Custom unlocks independent bullish and bearish color pickers. Gradient fill, residual bands, reversal markers, bar coloring, and background coloring can each be toggled so the chart stays as clean or as expressive as the workflow requires.
Indicador

Price Action Breakout Trend [QuantAlgo]🟢 Overview
Price Action Breakout Trend is a trend-following indicator built on structural range breakouts rather than moving average crossovers or oscillator thresholds. It tracks the highest high and lowest low of a defined lookback window to establish the levels price must decisively clear to confirm a directional shift, anchoring a trailing stop that ratchets in the trend's direction and reverses only when price breaks through it, helping traders distinguish genuine trend continuation from the shallow pullbacks that punctuate every sustained move across all timeframes and markets.
🟢 How It Works
The foundation of the indicator is the range defined by recent price extremes. On each bar it references the highest high and lowest low of the prior lookback window, excluding the current bar so the reference range is locked in before price interacts with it:
prior_high = ta.highest(high, lookback)
prior_low = ta.lowest(low, lookback)
These two levels frame the breakout boundaries. Rather than reacting to every marginal touch, the indicator lets you define what qualifies as a genuine break through the confirmation setting, which determines whether the closing price or the full bar extreme is tested against the trailing stop:
test_down = confirmation == 'Close' ? close : low
test_up = confirmation == 'Close' ? close : high
From these, a single trailing stop is maintained on the active side of the trend. While the trend holds bullish the stop ratchets upward, advancing to track the rising lookback low and never loosening, and the trend reverses the moment the tested price breaks below it:
if trend == 1
trail := math.max(trail, prior_low)
if test_down < trail
trend := -1
trail := prior_high
On that reversal the stop immediately re-anchors to the opposite extreme, flipping above price to begin trailing the new downtrend, where the mirror of this same logic ratchets the stop lower and flips the trend back to bullish once price breaks above it. Because the reversal is triggered by the same stop price has been trailing, the line is not a passive overlay but the actual decision boundary, with no separate signal calculation sitting behind it. This makes the indicator a continuous stop-and-reverse system that always holds a committed direction, retaining its bullish or bearish reading through every pullback contained within the range until price clears the trailing level.
🟢 Signal Interpretation
▶ Bullish Trend (Green): When price breaks above the trailing stop and the trend flips up, the indicator enters bullish mode with green coloring applied across the stop, gradient fill, and breakout levels. The stop sits below price and ratchets higher as the trend develops, and the reading holds through pullbacks that stay above it. The flip into green, marked by an up triangle beneath the bar, identifies a potential long/buy opportunity, with subsequent pullbacks toward the rising stop offering potential continuation entries while the trend remains intact.
▶ Bearish Trend (Red): When price breaks below the trailing stop and the trend flips down, the indicator enters bearish mode with red coloring across all visual elements. The stop sits above price and ratchets lower as the decline extends, holding bearish through rallies that fail to reclaim it. The flip into red, marked by a down triangle above the bar, identifies a potential short/sell opportunity, with rallies back toward the falling stop offering potential continuation entries on the downside.
🟢 Features
▶ Preconfigured Presets: Three parameter sets cover different trading approaches. "Default" targets swing trading on 4-hour and daily charts with a 10-bar lookback and close-based confirmation, filtering marginal breaks while staying responsive to genuine shifts. "Fast Response" shortens the lookback to 5 bars and switches to wick-based confirmation for intraday charts, where the trend needs to flip as soon as price trades beyond a recent extreme. "Smooth Trend" extends the lookback to 25 bars with close confirmation for position trading on daily and weekly timeframes, where the cost of a false flip exceeds the cost of a delayed one. Selecting a preset overrides the individual lookback and confirmation inputs.
▶ Built-in Alerts: Three alert conditions cover all directional states. "Bullish Breakout Signal" fires on the bar where the trend confirms bullish. "Bearish Breakout Signal" fires on the bar where it confirms bearish. "Any Breakout Signal" combines both into a single condition for traders who want a unified notification regardless of direction.
▶ Visual Customization: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) apply coordinated bullish and bearish schemes across the trailing stop, gradient fill, breakout levels, markers, and optional bar and background coloring. Independent toggles control each visual layer, so the trailing stop line, the gradient fill that ramps from the stop toward price, the triangle markers printed on each flip, and the underlying breakout levels that frame the active range can each be shown or hidden without affecting the others. Bar coloring tints price candles with the active trend color at a configurable transparency, and background coloring extends the directional tint across the full chart pane. Both are disabled by default and controlled independently.
*Tips: Layer the Price Action Breakout Trend with complementary analysis rather than treating it as a standalone trading tool. Breakouts hold most reliably when backed by participation, so combine each flip with volume context, since a break on expanding volume is far more likely to sustain than one on thin flow, and read the level being cleared against market structure, as a breakout through a well-established swing high or low carries more significance than one in open space. Pairing this script with volume, open interest, CVD, market structure, and mean reversion indicators from our QuantAlgo toolkit can further validate a breakout before entry. Indicador

Monotonic Trend Consensus [QuantAlgo]🟢 Overview
Monotonic Trend Consensus is a trend-following oscillator built on rank correlation between price and time rather than moving averages or crossovers. It scores how consistently price is ordered across multiple lookback windows and combines them into a single bounded reading on a -1 to +1 scale, holding the same meaning on any symbol or timeframe so traders can separate a broadly aligned trend from directionless noise and read when a move has stretched to saturation.
🟢 How It Works
The foundation is Spearman rank correlation between price and time, computed over each active window. Closes inside the window are ranked against one another, time forms its own rising sequence of ranks, and the difference between the two collapses to a single coefficient (rho):
float price_rank = less + (eq + 1.0) / 2.0
float time_rank = float(len - i)
float rho = 1.0 - 6.0 * sumd2 / denom
The coefficient reads +1 when each bar closes above the last in unbroken order, 0 when there is no consistent order, and -1 when each bar steps lower. Because it scores ordering rather than smoothing price into a line, it reflects the current window directly rather than trailing behind it, though it still needs a full window of bars to form. Ranking also limits the pull of any single outlier bar, and the bounded output is what lets one threshold hold across markets without rescaling.
A single window describes direction; the tool runs several and averages them into a consensus spanning fast, medium, and slow horizons:
consensus := array.avg(rhos)
Agreement is then measured as the share of windows leaning the same way as the consensus, and this conviction figure must clear a floor before a direction prints, working alongside the strength threshold:
conviction := 100.0 * agree / active
raw_bull = consensus > threshold and conviction >= min_conviction
raw_bear = consensus < -threshold and conviction >= min_conviction
A reading registers only when both clear at once: consensus past the threshold and windows aligned enough to meet the conviction floor. Fail either and the line stays flat. With Show Neutral on, those flat stretches reset to neutral; with it off, the line holds its last direction until the next qualifying move.
🟢 Signal Interpretation
▶ Bullish Consensus (Green): Consensus sits above the upper threshold with enough windows aligned, meaning recent bars are ordered upward across horizons. Trend traders read the turn into green as a possible long or continuation as the score presses toward +1. Mean-reversion traders treat a reading pinned near +1 as a stretched, broadly-agreed advance rather than a buy, and look to fade only once the line rolls back off the extreme, since the score can hold high through a sustained trend.
▶ Bearish Consensus (Red): Consensus sits below the lower threshold with conviction met, with bars ordered downward across horizons. Trend traders read the turn into red as a possible short or continuation as the score presses toward -1. Mean-reversion traders treat a reading pinned near -1 as a saturated decline where a bounce becomes more plausible, and look to fade on the turn back up rather than at the low itself.
▶ Neutral (Gray): With Show Neutral on, the line goes gray whenever no direction qualifies, either because consensus sits inside the threshold or conviction falls short. The zero line acts as the balance point and behaves like support or resistance for the reading itself: a score rejected at zero from above points to bullish order reasserting, a score capped at zero from below points to bearish order holding, and a clean break through leans toward a regime change. Reading this midline behavior against price is where market structure tools pair well, separating a base building above a structural level from a coil forming under overhead supply. Trend traders stand aside until the line commits; mean-reversion traders find less to work with here than at the edges.
▶ Reading the Extremes: The axis caps at +1 and -1, marking maximum agreement across every active window. Trend traders take an extreme as a sign a move is still in force; mean-reversion traders take it as a stretched zone and watch for the score to turn back toward zero as agreement breaks. An extreme that aligns with a known structural level gives a fade a cleaner reference than one in open space, and neither read holds on the extreme alone, since a strong trend can stay saturated before it cools.
🟢 Features
▶ Preconfigured Presets: Three setups map to different holding styles. "Default" suits swing work on 4-hour and daily charts, pairing a mid-range window spread of 8, 13, 21, and 34 with a 0.35 threshold and a 60% conviction floor, so a direction needs both strength and agreement before it flags. "Fast Response" pulls the windows in to 5, 8, 13, and 21 and eases the threshold and conviction floor so the reading keeps pace with quicker intraday swings. "Smooth Trend" stretches the windows out to 21, 34, 55, and 89 and raises both gates for daily and weekly position trading, where a premature flip costs more than a late one. Choosing a preset takes over the manual window, threshold, and conviction fields.
▶ Built-in Alerts: Four conditions track every change in state. "Bullish Trend Signal" triggers when the consensus confirms to the upside. "Bearish Trend Signal" triggers when it confirms to the downside. "Trend Lost / Neutral" triggers when an active direction fades back to flat, which is also the event a mean-reversion trader watches for after an extreme. "Any Trend Change" rolls the two directional events into a single notification for anyone who wants one alert covering both ways.
▶ Visual Customization: Six color schemes (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) carry a matched pair of bullish and bearish colors through the consensus line, its tiered gradient fill down to the zero baseline, and the optional bar and background tints. Marker lines sit at the positive and negative trigger levels to show the zone the consensus has to cross, and each window's own score can be switched on as a faint backing line so you can see which horizons are driving or dragging the combined figure. Bar coloring paints the price candles in the active trend color at an adjustable transparency, while background coloring spreads that tint across the pane.
Indicador

Dynamic Volatility Filter [QuantAlgo]🟢 Overview
Dynamic Volatility Filter is a trend-following indicator built on an adaptive volatility threshold rather than fixed bands or moving average crossovers. It quantifies the realized volatility of recent price movement to establish a dynamic noise floor that price must overcome before the line responds, anchoring a filtered trend line that only shifts when a directional move exceeds the prevailing volatility regime, helping traders separate statistically significant trend change from noise-driven fluctuation across every timeframe and market.
🟢 How It Works
The foundation of the indicator is a rolling volatility estimate derived from the Average True Range over a configurable lookback window, scaled by a noise multiplier to produce the threshold used in all line logic:
threshold = ta.atr(lookback) * noise_mult
This threshold functions as a deviation barrier the line will not cross until price movement breaches it. On each bar the filter measures the displacement between price and the current line position, and only when that displacement exceeds the volatility threshold does the line update:
float diff = src - dvf_line
if math.abs(diff) > threshold
dvf_line := dvf_line + diff * snap_speed
The line remains stationary through movement that falls within the volatility envelope and only commits once displacement clears the threshold. Rather than converging directly onto price, the line advances by a fraction of the residual distance governed by the catch-up coefficient, producing a damped response instead of an instantaneous one. Lower catch-up values introduce deliberate lag that requires a move to persist before the line follows, while higher values tighten the track to price.
Direction state is derived from the line's own first difference, comparing its current position against the prior bar:
if dvf_line > dvf_line
trend_dir := 1
else if dvf_line < dvf_line
trend_dir := -1
Because the line holds flat whenever displacement stays inside the threshold, those periods register no direction change. With Show Neutral enabled the state resets to neutral during these pauses, and with it disabled the line retains its last directional reading until the next threshold breach.
🟢 Signal Interpretation
▶ Bullish Trend (Green): When the filter line registers positive displacement against its prior position, the indicator enters bullish mode with green coloring applied across the line, gradient fill, and volatility bands. This state persists through pullbacks contained within the threshold, since direction only updates when the line moves. The transition into green marks a potential long/buy opportunity, with pullbacks toward the line during an established bullish reading offering potential continuation entries.
▶ Bearish Trend (Red): When the filter line registers negative displacement against its prior position, the indicator enters bearish mode with red coloring across all visual elements. The reading holds bearish until price clears the volatility threshold in the opposite direction. The transition into red marks a potential short/sell opportunity, with rallies back toward the line during an established bearish reading offering potential continuation entries on the downside.
▶ Neutral (Gray): When Show Neutral is enabled, the line and fills turn gray during flat stretches where price stays inside the threshold and the line holds still. This state signals an absence of confirmed direction and is best treated as a stand-aside condition, where waiting for the line to commit back to green or red avoids entering during indecisive, range-bound conditions.
🟢 Features
▶ Preconfigured Presets: Three parameter sets cover different trading approaches. "Default" targets swing trading on 4-hour and daily charts with a balanced threshold that filters moderate noise while staying responsive to genuine regime shifts. "Fast Response" lowers the volatility barrier and shortens the lookback for intraday charts where the line needs to adapt to shorter-duration moves. "Smooth Trend" raises the threshold and slows the catch-up for position trading on daily and weekly timeframes, where the cost of a false flip exceeds the cost of a delayed one. Selecting a preset overrides the individual noise, period, and catch-up inputs.
▶ Built-in Alerts: Three alert conditions cover all directional states. "Bullish Trend Signal" fires on the bar where the trend confirms bullish. "Bearish Trend Signal" fires on the bar where it confirms bearish. "Any Trend Change" combines both into a single condition for traders who want a unified notification regardless of direction.
▶ Visual Customization: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) apply coordinated bullish and bearish color schemes across the line, gradient fill, volatility bands, and optional bar and background coloring. The volatility bands plot one threshold above and below the line to frame the deviation envelope price must breach, and can be hidden for a clean line-only view. Bar coloring tints price candles with the active trend color at a configurable transparency level, and background coloring extends the directional tint across the full chart pane. Both are disabled by default and controlled independently.
*Recommendation: Layer the Dynamic Volatility Filter with complementary analysis rather than treating it as a standalone decision tool. Combine direction changes with volume context, since expanding volume on a flip bar suggests the move has broader participation behind it, and read transitions against key structural levels, as a flip occurring near major support or resistance carries more weight than one in open space. Pairing this script with volume, open interest, CVD, market structure, and mean reversion indicators from our QuantAlgo toolkit can further validate directional bias before entry. Indicador

Trend Structure Scale-In👋 What's up traders,
Decided to finally share this one after a lot of testing, tweaking, and more chart staring than I'd like to admit.
Trend Mitigation Scale-In Pro is built around a simple idea: trade with the trend, wait for quality pullbacks, and let probabilities do the heavy lifting.
The strategy combines:
• EMA200 trend filtering
• Pivot structure detection
• Engulfing candle confirmation
• Mitigation-based entries
• Controlled scale-ins on pullbacks
• Fixed basket take-profit management
The goal isn't to catch every move. It's to stay aligned with the bigger trend and focus on higher-quality setups while keeping execution simple.
Like every strategy, it's not perfect and should always be tested thoroughly before being used on a live account.
I'm constantly building, testing, and improving new ideas, so feedback is always appreciated.
If you find it useful, a ⭐ Favorite, 👍 Like, or 🚀 Boost helps more than you think and motivates me to keep sharing.
Wishing everyone green charts and disciplined trading. 🏆
Good luck out there.
— Tomukasss
Estrategia

Indicador

Adaptive Volatility Envelope [QuantAlgo]🟢 Overview
The Adaptive Volatility Envelope wraps price in a dynamic field of volatility bands centred on a self-adjusting baseline. Rather than tracking price at a fixed speed, the centerline measures how efficiently price is moving and accelerates when movement is more directional while slowing down in choppy conditions, so the baseline follows sustained moves more closely and reacts less to sideways noise. Around this adaptive centerline, layered ATR-scaled bands form a heat map that brightens toward the side price is moving into, giving traders a visual read on both trend state and momentum strength across any instrument or timeframe.
🟢 How It Works
The indicator's core methodology combines two mechanisms: an efficiency-driven centerline that adapts its tracking speed to market conditions, and a volatility-scaled band field that visualises momentum through colour and brightness.
First, market efficiency is measured by comparing net directional movement against total movement over the adaptation window. This ratio approaches one when movement is more directional and falls toward zero in choppy conditions, and it is used to blend between a slow choppy speed and a fast trending speed. The result is a smoothing factor that automatically tightens the centerline's tracking in directional moves and loosens it in noise, without manual recalibration:
efficiencyRatio = totalMovement != 0 ? priceChange / totalMovement : 0.0
smoothingFactor = choppySpeed + (trendSpeed - choppySpeed) * efficiencyRatio
Next, the centerline advances toward price by the smoothing factor on each bar, producing an adaptive baseline that closes the gap quickly when efficiency is high and slowly when it is low:
centerline := na(centerline ) ? src : centerline + smoothingFactor * (src - centerline )
Band width is then derived from Average True Range scaled by the band spacing, with a safety cap that measures total envelope height against the recent fifty bar price range. If the raw width would exceed this cap, every band is scaled down proportionally, preventing the field from blowing out and distorting the chart scale during volatility spikes:
widthScale = rawWidth > maxWidth and rawWidth != 0 and maxWidth > 0 ? maxWidth / rawWidth : 1.0
bandUnit = atr * bandSpacing * widthScale
Momentum is resolved from the centerline's slope normalised by ATR and scaled by the colour sensitivity, then clamped to a range of minus one to one. This drives a gradient that runs from the neutral colour at flat momentum toward the bullish or bearish colour as the move strengthens, while a directional brightness offset lights up the leading side of the envelope more than the trailing side:
momentumRaw = not na(atr) and atr != 0 ? slope / atr * colorSens : 0.0
momentum = math.max(-1.0, math.min(1.0, momentumRaw))
Finally, a confirmed-bars toggle governs what the script computes. In Live mode the centerline, momentum, bands and signals update intrabar on the developing bar for the fastest response, with the current bar able to change until it closes. In Confirmed mode everything is locked to closed bars only, so signals do not repaint and print on the bar that closes the move.
🟢 Signal Interpretation
▶ Bullish Momentum (Centerline and Bands Brightening Toward the Bullish Colour): When the centerline slopes upward relative to volatility, momentum turns positive and the envelope gradient shifts toward the bullish colour. The leading upper side of the field brightens through the directional brightness offset, making the direction of the move easier to read. The bullish state persists as long as the centerline continues rising, and a "Momentum Turned Bullish" alert fires on the bar where momentum crosses above zero.
▶ Bearish Momentum (Centerline and Bands Brightening Toward the Bearish Colour): When the centerline slopes downward relative to volatility, momentum turns negative and the gradient shifts toward the bearish colour, with the leading lower side of the field brightening to flag the downturn. As with the bullish state, the colour saturates as the move strengthens and fades toward neutral as momentum flattens. A "Momentum Turned Bearish" alert fires on the bar where momentum crosses below zero, flagging a potential short or exit condition.
▶ Neutral Momentum (Centerline and Bands at the Neutral Colour): When the centerline is flat or moving slowly relative to volatility, momentum sits near zero and the gradient settles at the neutral colour at the middle of its range. This indicates low conviction or sideways drift rather than a directional move, and the envelope brightens away from neutral only as the slope steepens enough to register on either side. Reading the neutral state helps separate genuine momentum from chop, since the field stays muted until price generates a meaningful directional slope.
🟢 Features
▶ Preconfigured Presets: Three parameter sets cover a range of trading styles and timeframes. "Default" delivers a balanced engine for swing trading on 4-hour and daily charts. "Fast Response" shortens the adaptation window and quickens both market speeds for tighter, more reactive bands on 5-minute to 1-hour charts, suiting intraday and scalping use. "Smooth Trend" lengthens the adaptation window and slows the speeds for wider, steadier bands on daily and weekly charts, suiting position trading. The presets deliberately leave Volatility Length untouched, so band width stays under independent manual control.
▶ Built-in Alerts: Three alert conditions support automated monitoring of momentum transitions. "Momentum Turned Bullish" fires on the bar momentum crosses above zero. "Momentum Turned Bearish" fires on the bar momentum crosses below zero. "Any Momentum Change" triggers on either transition for traders who want a single unified alert regardless of direction. All alerts include the exchange, ticker, and timeframe in the message for immediate context, and the confirmed-bars toggle determines whether they evaluate on live or closed-bar data.
▶ Visual Customisation: Six colour presets, Classic, Aqua, Cosmic, Cyber, Neon, and Custom, provide coordinated bullish and bearish colour pairings suited to different chart themes and personal preferences. Selecting Custom exposes independent colour pickers for full manual control over both states, alongside an adjustable neutral colour for the midpoint of the gradient. The number of band layers is configurable from one for a clean minimal look up to eight for a rich gradient field, and the bands can be hidden entirely to display only the centerline. Optional bar colouring tints price candles with the active trend colour at a configurable transparency level, reflecting the current momentum state without reading the centerline directly.
Indicador

Market Breadth Trend StrategyOverview
Many traders focus on major indexes such as the S&P 500 or Nasdaq when evaluating market conditions. While indexes show overall price movement, they do not always reflect how broadly that movement is supported across the market.
Market breadth is a way of studying participation. It can help traders understand whether strength or weakness is concentrated in a small group of stocks or spread across a wider portion of the market.
A market move supported by broad participation may provide different context than a move driven by only a few heavily weighted stocks.
Understanding Market Participation
Market breadth generally refers to the number of securities contributing to a market move.
Examples of breadth-related observations include:
The balance between advancing and declining stocks
The number of stocks reaching new highs or lows
The percentage of stocks trading above key moving averages
These measurements can provide additional perspective alongside price action and trend analysis.
Why Traders Monitor Breadth
Participation Matters
Strong participation may indicate that market activity is occurring across a wider group of stocks rather than being concentrated in a few names.
Additional Context
Breadth can be used as a supplementary tool when evaluating trends, momentum, and overall market conditions.
Market Observation
Some traders monitor breadth metrics to better understand changes in participation over time and how those changes compare with index performance.
Strategy Concept
This script uses a simplified breadth-style proxy derived from the chart's relationship to a long-term moving average.
It is important to note that this script does not use actual exchange-wide market breadth data. Instead, it creates a participation-style filter using price behavior on the current chart.
The strategy combines:
Trend identification using moving averages
A breadth-style participation filter
ATR-based risk management
The objective is to demonstrate how participation concepts can be incorporated into a trend-following framework for research and testing purposes.
Important Notes
This script uses a simplified participation-style filter and is not a substitute for exchange-wide breadth indicators.
Results will vary across symbols, timeframes, and market conditions.
The script is intended for educational, research, and testing purposes.
Disclaimer
This script is provided for educational and research purposes only. It demonstrates one way to combine trend analysis with a breadth-style participation filter. It is not financial advice and should be tested across different symbols, market conditions, and timeframes before being used in any trading workflow.
This version avoids performance claims, avoids implying predictive ability, and clearly explains the limitations of the breadth proxy. Estrategia

Fractal Exhaustion Band [QuantAlgo]🟢 Overview
The Fractal Exhaustion Band is a trend-following indicator that replaces the fixed ATR multiplier common to most adaptive bands with the Fractal Dimension Index, scaling the buffer width in real time based on how efficiently price is consuming its recent range. Additionally, an extremum tracker accumulates swing highs and lows since the last confirmed flip to form an outer Band Edge, giving traders a structured range to position within the trend, identify exhaustion near its boundaries, and treat extensions beyond the edge as potential deviation signals ahead of a directional flip across any instrument or timeframe.
🟢 How It Works
The core methodology is built around three sequential stages: a fractal dimension calculation that quantifies the structural quality of recent price movement, a dynamic buffer derived from that measurement, and a ratcheting trend line that advances only when market conditions justify it.
First, the Fractal Dimension Index (FDI) is calculated by comparing the total path length price has travelled over the lookback window against the straight-line distance between its highest and lowest point. A value near 1 indicates clean, efficient trending. A value near 2 indicates erratic, space-filling movement. The ratio is log-normalised by the window size to keep it comparable across different FDI Period settings:
fdi = high_ - low_ > 0 ? (math.log(len) - math.log(high_ - low_)) / math.log(power) : 0
Next, the FDI is fed directly into the buffer calculation as a scaling factor on top of the Band Width Multiplier and a 10-period ATR. This means the buffer is never fixed; it inflates when price behaviour is erratic and compresses when price is trending with conviction:
dynamic_mult = sensitivity * (1 + fdi)
buffer = atr * dynamic_mult
The trend line then ratchets in the direction of the current trend, but only on bars where the FDI is below 1.5. This gate prevents the line from being dragged by price during high-fractal-dimension conditions, even if price has not yet breached the buffer threshold. A trend flip is only registered when price closes beyond the buffer on the opposite side:
if fdi < 1.5
trend_line := math.max(trend_line, close - buffer)
Finally, an extremum tracker accumulates the running high or low since the last confirmed flip, forming the outer Band Edge. A midline is derived as the average between this extremum and the trend line, creating a three-layer structure that encodes both the structural anchor of recent price extremes and the adaptive trend line beneath it:
ex := trend_dir != trend_dir ? (trend_dir == 1 ? high : low)
: trend_dir == 1 ? math.max(nz(ex , high), high)
: math.min(nz(ex , low), low)
mid = math.avg(ex, trend_line)
🟢 Signal Interpretation
▶ Bullish Trend (Band Rising with Bullish Colour): When price moves upward with sufficient efficiency to produce a low FDI reading and close above the trend line's buffer threshold, the trend direction flips to bullish and the entire band shifts to the bullish colour. From that point, the Fractal Line ratchets upward on each bar where the FDI remains below 1.5, while the extremum tracker accumulates successive highs to form the outer Band Edge above. The flat segments visible in the band reflect bars where the FDI gate suppressed movement, while upward steps reflect bars where trending conditions were confirmed.
Within the bullish band, the Fractal Line and Band Edge define a structured trading range. Price oscillating between the two represents normal trend continuation behaviour, and pullbacks toward the Fractal Line can be treated as higher-probability long entries with the trend, using the Fractal Line itself as the logical invalidation level. The Band Mid serves as a directional gauge within that range; price holding above it reflects stronger momentum, while price drifting below it signals weakening conviction worth monitoring. When price pushes into the Band Edge zone and begins interacting with the accumulated swing highs, treat that as an exhaustion area rather than a continuation signal. Longs initiated near the Band Edge carry elevated risk of a short-term mean reversion back toward the Fractal Line. If price then extends meaningfully beyond the Band Edge, treat the extension as a deviation from the established structure. A deviation of this kind, particularly when accompanied by a rising FDI indicating deteriorating trend quality, is a preparatory signal to begin tightening long exposure and watching for the Fractal Line to be breached on the downside, which would confirm the bias flip to bearish.
▶ Bearish Trend (Band Declining with Bearish Colour): When price moves downward with sufficient efficiency to produce a low FDI reading and close below the trend line's buffer threshold, the trend direction flips to bearish and the band shifts to the bearish colour. The Fractal Line ratchets lower on each bar where the FDI gate permits, while the extremum tracker accumulates successive lows to form the outer Band Edge below. As with the bullish state, the filter holds its last value on bars where fractal dimension is elevated, and the direction state remains unchanged on those bars.
Within the bearish band, the same structural logic applies in reverse. Price oscillating between the Fractal Line above and the Band Edge below represents normal bearish continuation, and bounces toward the Fractal Line can be treated as higher-probability short entries with the trend, using the Fractal Line as the invalidation level. The Band Mid again acts as a momentum gauge; price holding below it indicates sustained selling pressure, while recovery above it suggests the downtrend is losing conviction. When price pushes into the Band Edge zone and interacts with the accumulated swing lows, treat that region as exhaustion rather than confirmation of further downside. Shorts initiated near the Band Edge carry elevated mean-reversion risk back toward the Fractal Line. If price extends beyond the Band Edge to the downside, treat that extension as a structural deviation. A deviation paired with a rising FDI is a signal to begin reducing short exposure and watching for an upward breach of the Fractal Line, which would confirm the directional flip back to bullish.
🟢 Features
▶ Preconfigured Presets: Three parameter sets cover a range of trading styles and timeframes. "Default" delivers balanced noise filtering suited to swing trading on 4-hour and daily charts. "Fast Response" tightens the buffer and shortens the fractal measurement window for intraday and scalping use on 1-minute to 1-hour charts, producing earlier trend flips in response to smaller directional moves. "Smooth Trend" widens the buffer and extends the measurement window for position trading on daily and weekly charts, requiring a more sustained and efficient directional move before a trend flip is registered.
▶ Built-in Alerts: Three alert conditions support automated monitoring of trend transitions. Bullish Trend fires on the first bar where trend direction flips from bearish to bullish. Bearish Trend fires on the first bar where trend direction flips from bullish to bearish. Any Signal Change triggers on either transition for traders who want a single unified alert regardless of direction. All alerts include the exchange, ticker, and timeframe in the message for immediate context.
▶ Visual Customisation: Six colour presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) provide coordinated bullish and bearish colour pairings suited to different chart themes and personal preferences. Selecting Custom exposes independent colour pickers for full manual control over both states. The three-layer band fill uses graduated transparency across the outer edge, midline, and trend line zones to clearly distinguish structural from adaptive components at a glance. Optional bar colouring tints price candles with the active trend colour using a configurable transparency level, and optional background colouring extends the trend state tint across the full chart pane at a separately configurable transparency.
Indicador

Open Interest Suite [QuantAlgo]🟢 Overview
The Open Interest (OI) Suite is a comprehensive OI visualization and analysis tool built specifically for crypto perpetual futures traders. It reads open interest data directly from TradingView-supported exchanges, giving you a way to monitor how many active contracts are currently open in the market. Whether you are tracking a single exchange or aggregating OI across venues like Binance, Bybit, Bitget, Coinbase, Kraken, HTX, BitMEX, and OKX, this indicator is one of the most powerful contextual tools available, allowing traders to quickly gauge overall perpetual futures market positioning.
🟢 What is Open Interest?
Open interest (OI) is the total number of live contracts between buyers and sellers at any given moment. Every long is matched to a short at a 1:1 ratio, so OI gives you a strong sense of how much capital and how many positions are currently committed to the market. Rising OI suggests new money and new positions are entering. Falling OI suggests positions are being closed or liquidated. When combined with price action, OI becomes one of the most valuable lenses available for understanding what is likely happening beneath the surface of price movement in perpetual markets.
🟢 How It Works
The indicator operates in two distinct modes. In Single (Chart) mode, it automatically reads open interest from whichever supported exchange and perpetual contract you are currently viewing, requiring no manual configuration. In Aggregated mode, it fetches OI from some of the highest-volume exchanges in crypto, for example, Binance, Bybit, Bitget, Coinbase, Kraken, HTX, BitMEX, and OKX, combines them into a single composite total, and gives you a cross-market view of positioning that no individual exchange feed can provide on its own. For each exchange in Aggregated mode, OI is fetched across both USDT and USDC perpetual pairs where applicable, then converted to a unified measure before summing. More exchanges will be added as their data becomes available on TradingView.
The Measure setting controls how OI values are expressed. In Coins mode, values are kept in their native unit, which may be more useful when you want to observe raw contract volume independent of price fluctuations. In Dollars mode, coin quantities are multiplied by the current bar price to convert values into USD, which is the standard way most traders and data providers report OI and tends to make cross-asset comparisons more intuitive. For exchanges that report natively in USD, the conversion is handled in reverse when Coins mode is active.
🟢 Key Features
▶ View Modes
The indicator offers four ways to visualize OI, each suited to a different analytical purpose.
1. Candles: Renders OI as full OHLC candlesticks, displaying open, high, low, and close OI for every bar. This is the richest view for studying OI structure, trends, compression, and expansion over time. You can watch OI build or unwind bar by bar similarly to how you read price action, which may help with spotting periods of aggressive position-building or rapid deleverage.
2. Lines: Renders OI as a single continuous line using the close value of each bar. Cleaner and less visually demanding than candles, this mode works well for maintaining OI context alongside other indicators without crowding the chart.
3. Change: Displays the bar-over-bar absolute difference in OI as a histogram. Positive bars indicate net new positions were likely opened. Negative bars suggest net positions were closed or liquidated. This mode can help identify the bars where positioning shifted most dramatically, which often corresponds to high-conviction entries, forced liquidations, or possible trend exhaustion.
4. Change (%): The same histogram expressed as a percentage of the prior bar OI value. This normalises the signal across different asset sizes and OI magnitudes, which could make it easier to compare positioning dynamics between a large-cap asset and a smaller altcoin.
▶ Aggregated Mode and Exchange Selection
In Aggregated mode, each of the eight supported exchanges can be toggled on or off independently. This flexibility allows several useful configurations beyond a simple total. You can enable only one exchange to track that specific venue regardless of which chart you are currently viewing. You can also add the indicator to your layout multiple times with a different single exchange selected each time, letting you compare individual exchange OI side by side on the same chart.
▶ Color Presets
Five built-in color presets (Classic, Aqua, Cosmic, Cyber, Neon) allow you to match the indicator's appearance to your chart setup with a single click. A Custom preset exposes individual color pickers for bull, bear, and line colors, giving full control over every visual element including candle bodies, wicks, borders, histogram columns, and the line overlay.
▶ Unsupported Exchange Warning
When Single (Chart) mode is active and the current exchange does not provide open interest data on TradingView, the indicator displays a warning label on the chart identifying the unsupported exchange and listing supported alternatives.
🟢 Price + OI Interpretation
Reading OI in isolation is only part of the picture. More meaningful analysis tends to come from combining OI direction with price action and, where available, volume data, along with other trend-following or mean-reversion indicators.
Examples:
1. Price Up + OI Up: New capital is likely entering on the long side. This could indicate bullish trend continuation, with fresh positioning supporting the move rather than just short covering. The stronger the OI growth relative to price movement, the higher the probability that the trend has genuine participation behind it.
2. Price Down + OI Up: New shorts are probably being added aggressively. Bearish momentum may be building through fresh positioning, which tends to be a more sustained signal than a move driven purely by long liquidations.
3. Price Down + OI Down: Longs are likely closing or being liquidated. The selling pressure in this scenario is coming from position unwinds rather than new short entries, which could sometimes suggest exhaustion near a local low rather than fresh trend initiation.
4. Price Up + OI Down: Shorts are probably closing or being squeezed out. This is the likely mechanics of a short squeeze: buyers overwhelm sellers, underwater shorts cover, and the resulting buy pressure may accelerate the move higher. This pattern tends to produce some of the fastest and sharpest price moves seen in crypto perpetual markets.
It is worth noting that for every short there is a long. When OI increases during a downtrend, it does not necessarily mean only shorts are entering. Longs are participating too, often more passively through limit orders. Cumulative Volume Delta (CVD) can help distinguish which side is more likely driving the flow, since it measures aggressive buying versus aggressive selling pressure within each bar.
🟢 Important Notes
1. This indicator is designed exclusively for crypto perpetual futures and will not produce output on spot tickers, equity symbols, or any instrument without a corresponding OI feed on TradingView. In Single (Chart) mode, if the exchange you are viewing is not among the currently supported venues (Binance, Bybit, Bitget, Coinbase, Kraken, HTX, BitMEX, and OKX), the indicator will display a warning and produce no data. Switching to a supported exchange will restore functionality. More exchanges will be added as their data becomes available on TradingView.
2. OI is most useful as a context layer rather than a standalone signal. Using it alongside price structure, volume, and order flow analysis may help you assess whether a move is likely backed by new positioning or driven by position unwinds. That distinction could have meaningful implications for how far a move extends and how quickly it might reverse. Indicador

Asymmetric Volatility Trend Line [QuantAlgo]🟢 Overview
Asymmetric Volatility Trend Line is a trend-following indicator built on adaptive standard deviation thresholds rather than fixed bands or moving average crossovers. It quantifies the statistical volatility of recent price movement to determine asymmetric conditions for trend continuation versus trend reversal, then uses those conditions to anchor a dynamic trend line that adjusts position in response to confirmed directional moves, helping traders distinguish between genuine breakouts and noise-driven fluctuations across every timeframe and market.
🟢 How It Works
The foundation of the indicator is a rolling standard deviation applied to the selected price source over a configurable lookback window, scaled by a threshold multiplier to produce the volatility boundary used in all trend logic:
vol_threshold = ta.stdev(src, lookback) * threshold_mult
This threshold is intentionally asymmetric in application. When the trend line is in a bullish state, a smaller fraction of the threshold (0.5x) is required for price to confirm continuation, while a full threshold breach in the opposite direction is needed to trigger a reversal. The same asymmetry applies in reverse during bearish states:
if trend_dir >= 0
if src > trend_line + vol_threshold * 0.5
trend_line := math.max(trend_line, src - vol_threshold * 0.25)
trend_dir := 1
else if src < trend_line - vol_threshold
trend_line := src + vol_threshold * 0.25
trend_dir := -1
This design means continuation requires less evidence than reversal. A directional move only needs to exceed half the volatility threshold to sustain the current trend, but must overcome the full threshold to flip it. The 0.25x offset applied when repositioning the trend line keeps it anchored within the volatility envelope rather than jumping directly to price, producing a smoother line that does not overreact to a single bar.
When a reversal is confirmed, the trend line is placed on the opposite side of price at a quarter-threshold distance, giving it room to develop without immediately triggering another flip:
trend_line := src + vol_threshold * 0.25 // repositioned on bearish flip
trend_dir := -1
Direction state is tracked through two integer variables, with reversal conditions derived from comparing the current and prior bar states:
turned_bullish = trend_dir == 1 and trend_dir == -1
turned_bearish = trend_dir == -1 and trend_dir == 1
is_reversal = trend_dir != prev_dir and bar_index > 0
🟢 Signal Interpretation
▶ Bullish Trend (Green): When price closes above the trend line by more than half the volatility threshold, the indicator enters bullish mode with green colouring applied across the trend line, gradient fill, and reversal marker (⦿). This state persists until price closes below the trend line by the full volatility threshold, allowing normal pullbacks to occur without triggering a direction change.
▶ Bearish Trend (Red): When price closes below the trend line by more than half the volatility threshold, the indicator enters bearish mode with red colouring across all visual elements. A full threshold breach to the upside is required to exit this bearish state.
🟢 Features
▶ Preconfigured Presets: Three parameter sets cover different trading approaches. "Default" targets swing trading on 4-hour and daily charts with moderate threshold sensitivity. "Fast Response" reduces the volatility barrier and shortens the lookback for intraday charts where the indicator needs to adapt to shorter-duration moves. "Smooth Trend" raises the reversal threshold substantially for position trading on daily and weekly timeframes, where the cost of a false flip is higher than the cost of a delayed one. Selecting a preset overrides the individual multiplier and lookback inputs.
▶ Built-in Alerts: Three alert conditions cover all directional states. "Bullish Trend Signal" fires on the bar where the trend direction flips from bearish to bullish. "Bearish Trend Signal" fires on the bar where it flips from bullish to bearish. "Any Trend Change" combines both into a single condition for traders who want a unified notification regardless of direction.
▶ Visual Customisation: Six colour presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) apply coordinated bullish and bearish colour schemes across the trend line, gradient fill, reversal markers, and optional bar and background colouring. Bar colouring tints price candles with the active trend colour at a configurable transparency level, and background colouring extends the directional tint across the full chart pane. Both are disabled by default and controlled independently.
Indicador

Adaptive Friction Filter (AFF) [QuantAlgo]🟢 Overview
The Adaptive Friction Filter (AFF) identifies trending market conditions by applying a physics-inspired friction model to price movement. Rather than smoothing price through fixed averaging, it introduces a dynamic noise threshold derived from recent market volatility, which means price must generate enough force to overcome this threshold before the filter moves at all. Once breached, the filter closes the gap at a configurable rate, producing a step-like trend line that holds steady through noise and responds decisively to genuine directional moves. This allows traders to distinguish between meaningful trend continuation and low-conviction chop across any instrument or timeframe.
🟢 How It Works
The AFF's core methodology is built around a two-stage mechanism: a volatility-derived friction threshold that gates filter movement, and a catch-up scalar that governs how much of the gap the filter closes on each bar once that threshold is exceeded.
First, the friction threshold is computed as the simple moving average of absolute bar-to-bar price changes over the configured lookback window, scaled by the friction coefficient. This makes the threshold inherently self-adjusting; it widens during volatile conditions and contracts during quiet ones, without requiring any manual recalibration:
friction = ta.sma(math.abs(src - src ), lookback) * friction_mult
Next, the raw displacement between current price and the filter's last position is evaluated as force. The filter only advances if this force exceeds the friction threshold. When it does, the filter moves toward price by a fraction of the gap governed by the catch-up scalar, rather than closing the full distance immediately, producing a controlled and progressive response:
force = src - aff_line
aff_line := math.abs(force) > friction ? aff_line + force * catchup_scalar : aff_line
Trend direction is then resolved by comparing the current filter value to its prior bar value. The direction state persists when the filter is flat, so no transition is registered on bars where the filter does not move:
trend_dir := aff_line > aff_line ? 1 : aff_line < aff_line ? -1 : trend_dir
Finally, the filter is rendered as two overlapping plots at the same value: a step-line that traces the filter's path and a circle overlay positioned at each bar's filter value. The circles serve a visual purpose, reinforcing the current filter level at each step and making it easier to read the filter's position at a glance, particularly during flat periods where the step-line alone can be harder to track. Together they produce a dotted step appearance that improves legibility across different chart zoom levels and timeframes.
🟢 Signal Interpretation
▶ Bullish Trend (AFF Line Rising with Bullish Colour): When price generates enough upward force to exceed the friction threshold, the filter begins stepping higher and the line shifts to the bullish colour. The step-line rendering makes the transition visually clear; flat segments indicate bars where force was insufficient to move the filter, while upward steps reflect bars where it was. The bullish trend state persists until force in the downward direction is large enough to push the filter lower, at which point trend direction flips and the line shifts to the bearish colour.
▶ Bearish Trend (AFF Line Declining with Bearish Colour): When price generates enough downward force to exceed the friction threshold, the filter begins stepping lower and shifts to the bearish colour. As with the bullish state, the filter holds its last value on bars where force is insufficient to breach the threshold, and the direction state remains unchanged on those bars. A full reversal back to bullish requires upward force to exceed the friction threshold and push the filter higher, at which point trend direction flips and the colour transitions accordingly.
🟢 Features
▶ Preconfigured Presets: Three parameter sets cover a range of trading styles and timeframes. "Default" delivers balanced noise filtering for swing trading on 4-hour and daily charts. "Fast Response" lowers the friction threshold and accelerates the catch-up rate for intraday and scalping use on 5-minute to 1-hour charts, producing earlier filter movement in response to smaller price displacements. "Smooth Trend" raises the threshold and slows the catch-up rate for position trading on daily and weekly charts, requiring larger price displacements relative to the average noise level before the filter advances.
▶ Built-in Alerts: Three alert conditions support automated monitoring of trend transitions. "Bullish Trend Signal" fires on the first bar trend direction flips from bearish to bullish. "Bearish Trend Signal" fires on the first bar trend direction flips from bullish to bearish. "Any Trend Change" triggers on either transition for traders who want a single unified alert regardless of direction. All alerts include the exchange, ticker, and timeframe in the message for immediate context.
▶ Visual Customisation: Six colour presets, Classic, Aqua, Cosmic, Cyber, Neon, and Custom, provide coordinated bullish and bearish colour pairings suited to different chart themes and personal preferences. Selecting Custom exposes independent colour pickers for full manual control over both states. Optional bar colouring tints price candles with the active trend colour using a configurable transparency level, and optional background colouring extends the trend state tint across the full chart pane at a separately configurable transparency.
Indicador

Adaptive Fourier Transform CCI [QuantAlgo]🟢 Overview
The Adaptive Fourier Transform CCI reimagines the classic Commodity Channel Index by replacing its fixed lookback period with one that continuously adjusts to the market's own rhythm. Rather than measuring price deviation against an arbitrary static length, it first isolates the cyclical component of price action through a Discrete Fourier Transform, identifies which cycle period currently holds the most spectral energy, and then tunes the CCI calculation to that dominant period. The result is a momentum oscillator calibrated to the frequency structure of the instrument being traded, naturally tightening during fast, high-frequency regimes and widening during slower, drawn-out cycles without requiring manual timeframe adjustments.
🟢 How It Works
Before any cycle detection occurs, raw price is conditioned through two sequential filters. A high-pass filter strips the slow-moving trend component from the close, leaving only the oscillating portion of price action:
hp := 0.5 * (1 + a1) * (close - close ) + a1 * hp
That residual is then passed through a Super Smoother filter, which removes short-term noise from the cycle signal without introducing the lag that standard moving averages add at this stage:
filt := c1 * (hp + hp ) / 2 + c2 * filt + c3 * filt
This cleaned signal is what the Discrete Fourier Transform (DFT) operates on. The DFT scans across a range of candidate cycle periods and measures how much price energy is concentrated at each one. The period where that energy is strongest is selected as the dominant cycle. An EMA smooths the period output to prevent erratic length switching between bars, and the result is scaled by the Length Multiplier to derive the final adaptive CCI lookback:
adaptiveLen = clamp(round(dominantPeriod × lengthMult), 5, 60)
The CCI is then calculated using the standard Lambert formula over that adaptive length, measuring how far typical price has deviated from its mean relative to its average absolute deviation. An optional output smoothing MA reduces bar-to-bar noise before the final value is plotted.
🟢 Signal Interpretation
▶ Overbought (Above Upper Level, Red): When the Adaptive Fourier Transform CCI (AFT-CCI) rises above the upper threshold, price has deviated significantly above its cycle-adaptive mean. The reading reflects momentum extended relative to the market's current detected rhythm rather than a fixed arbitrary baseline. The signal carries more weight when the dominant cycle is stable and the DFT is locked onto a consistent frequency rather than switching between periods.
▶ Oversold (Below Lower Level, Green): When the AFT-CCI falls below the lower threshold, price has moved an equivalent distance below its cycle-adaptive mean. In strongly trending conditions the AFT-CCI can remain in either zone for extended periods, so the threshold levels should be read as zones of extension rather than automatic reversal points.
▶ Neutral Zone (Between Levels, Grey): When the AFT-CCI sits between the upper and lower thresholds, price deviation relative to the detected cycle is within normal range. Zero-line crosses within this zone indicate the adaptive mean is being reclaimed, which can serve as early directional context before a full threshold break develops.
▶ Zero Line: The zero line represents the adaptive mean itself. A cross above zero indicates typical price has moved above the cycle-adaptive mean; a cross below indicates the opposite. These crosses are lower-conviction reads on their own but become more meaningful when followed by a threshold break in the same direction.
🟢 Features
▶ Preconfigured Presets: Two parameter sets sit alongside the default configuration. "Fast Response" compresses the DFT window and cycle search range while raising the length multiplier, producing faster adaptation suited to intraday charts from 5-minute to 1-hour. "Smooth Trend" expands the window and search range while lowering the multiplier, establishing a more stable cycle read suited to daily and weekly position trading.
▶ Built-in Alerts: Six alert conditions cover the full range of meaningful oscillator events. Separate alerts fire on entering and exiting both overbought and oversold territory, capturing threshold breaks in both directions. Two additional alerts trigger on bullish and bearish zero-line crosses, enabling directional monitoring without requiring constant chart observation.
▶ Visual Customisation: Six colour presets, Classic, Aqua, Cosmic, Cyber, Neon, and Custom, apply consistently across the signal line, glow layers, and threshold level lines so the overbought and oversold colours remain coherent regardless of which preset is active. The optional neon glow effect uses three layered plots at increasing transparency to give the signal line visual depth and make threshold breaks immediately readable at a glance.
Indicador

Hyperbolic Hull Moving Average (HHMA) [QuantAlgo]🟢 Overview
Hyperbolic Hull Moving Average is a trend-following indicator that replaces the linear weighting kernel inside a Hull Moving Average with a hyperbolic sine function, producing a moving average that concentrates weight on recent bars in a non-linear, exponentially accelerating curve rather than a straight ramp. Where a standard WMA assigns weight proportionally across the lookback, the sinh kernel creates a steep recency gradient that responds meaningfully to genuine momentum shifts while remaining more resistant to brief noise spikes, because distant bars lose influence at a compounding rate rather than a constant one. The result is a Hull-style construction with faster directional detection and smoother curvature than its conventional counterpart.
🟢 How It Works
The indicator is built across three passes of the same sinh weighting function. The core kernel computes a weighted average where each bar's weight is determined by the hyperbolic sine of its normalized position within the lookback, scaled by a tension parameter:
float _x = (_len - i) / _len * _t
float _w = (math.exp(_x) - math.exp(-_x)) / 2
Higher tension values push more of the total weight toward the most recent bars. At the default tension of 2.0 across a 24-period window, the most recent bar carries roughly 44 times the weight of the oldest bar. A standard WMA across the same window would assign the newest bar only 24 times the weight of the oldest, so the sinh kernel naturally produces a steeper bias toward recent price action at any equivalent length setting.
The Hull construction then runs two sinh-weighted averages at different periods, a fast pass at half the length and a slow pass at the full length, before combining them in the same denoising formula Alan Hull originally described:
fastSinh = f_sinh_weight(src, halfLen, tension)
slowSinh = f_sinh_weight(src, length, tension)
rawHull = 2 * fastSinh - slowSinh
hhma = f_sinh_weight(rawHull, sqrtLen, tension)
The raw Hull output is then passed through a final sinh-weighted smoothing pass at the square root of the full length, which removes the lagging noise the doubling step introduces.
Trend direction is determined by a simple slope check on the final output. This keeps state detection clean and unambiguous, with direction changes triggering alerts and visual updates the bar they occur.
🟢 Signal Interpretation
▶ Bullish Trend (Rising HHMA, Green): When the HHMA turns upward, all visual elements switch to the bullish colour, indicating a confirmed uptrend. Because the sinh kernel front-loads weight on recent bars, the line responds quickly to genuine upside momentum without needing price to sustain a move for many bars before registering a directional shift. Trend state remains bullish on each subsequent bar the HHMA continues to rise, allowing traders to hold positions through normal intra-trend oscillation without being shaken out by minor hesitations in the line.
▶ Bearish Trend (Falling HHMA, Red): When the HHMA turns downward, all visual elements switch to the bearish colour, confirming a downtrend or a breakdown from a prior uptrend. The same recency weighting that accelerates bullish detection also means the line will respond relatively quickly to sustained selling pressure, reducing the lag that causes conventional Hull variants to stay bullish well into a reversal. The trend remains bearish on each bar the HHMA continues to fall.
🟢 Features
▶ Preconfigured Presets: Three optimised parameter sets cover different trading approaches. "Default" is calibrated for swing trading on 4-hour and daily charts, balancing responsiveness with noise rejection. "Fast Response" shortens the lookback and increases recency bias for intraday and scalping use on 5-minute to 1-hour charts. "Smooth Trend" extends the period and flattens the weighting curve for position trading on daily and weekly charts where fewer, higher-conviction direction changes are preferred.
▶ Built-in Alerts: Three alert conditions support automated monitoring without requiring constant chart supervision. "Bullish Trend Signal" fires on the bar the HHMA slope turns upward. "Bearish Trend Signal" fires on the bar it turns downward. "Trend Direction Changed" covers both transitions with a single alert for traders who want a unified notification regardless of direction.
▶ Visual Customization: Six colour presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) provide coordinated bullish and bearish colour pairs suited to different chart themes and backgrounds. Optional bar colouring tints price bars with the active trend colour at an adjustable transparency level, offering immediate visual confirmation of trend state across all open chart timeframes without requiring the indicator line itself to be in view.
Indicador

Liquidity Sweep Detector [QuantAlgo]🟢 Overview
The Liquidity Sweep Detector is a swing-based liquidity tracking tool that identifies moments when price wicks beyond a confirmed swing high or low and closes back inside, then tracks the remaining unswept levels as forward-projecting lines and zones on your chart. It classifies each event by direction (Bullish or Bearish) and maintains a running registry of swing levels that have not yet been visited by price, giving you a live map of where resting stop clusters may still be sitting across any timeframe and market.
🟢 How It Works
The indicator identifies swing highs and lows using a pivot detection window that requires a configurable number of bars to the left and right to confirm a valid structural point. The active pivot length and minimum wick penetration are resolved from the selected preset before any detection runs:
active_len = preset_config == 'Scalp' ? 5 : preset_config == 'Swing' ? 20 : pivot_len
active_min_pct = preset_config == 'Scalp' ? 0.0 : preset_config == 'Swing' ? 0.05 : min_wick_pct
A bearish sweep is confirmed when price wicks above the most recent swing high by at least the minimum penetration percentage and closes back below it. A bullish sweep mirrors this on the downside:
bearSweep = not na(lastSwingHigh) and high > lastSwingHigh * (1 + active_min_pct / 100) and close < lastSwingHigh
bullSweep = not na(lastSwingLow) and low < lastSwingLow * (1 - active_min_pct / 100) and close > lastSwingLow
Every confirmed swing point is simultaneously stored in an unswept level registry. Levels are removed when the full candle closes beyond them, or immediately when a sweep is confirmed on that level, so the chart only shows levels price has not yet visited:
if bearSweep and array.size(unsweptHighs) > 0
for i = array.size(unsweptHighs) - 1 to 0
if array.get(unsweptHighs, i) == lastSwingHigh
array.remove(unsweptHighs, i)
array.remove(unsweptHighBars, i)
break
The indicator also detects when price enters the zone around an unswept level without yet confirming a full sweep. Edge detection ensures the alert fires once on entry rather than on every bar price remains inside the zone:
buySideEntry = enteredBuySide and not enteredBuySide
sellSideEntry = enteredSellSide and not enteredSellSide
🟢 Key Features
▶ Three Preset Configurations: The indicator includes three presets that override the manual pivot length and minimum wick penetration settings.
1. Default/Custom: A general-purpose configuration suited to swing trading on 4H and daily charts. Confirms swing points that require a reasonable structural context before a sweep is flagged.
2. Scalp: A faster configuration for intraday charts from 1 minute to 15 minutes. Shorter pivot windows capture local swing points that form and get swept within a single session.
3. Swing: A more conservative configuration for daily and weekly charts that requires a more deliberate wick extension before confirming a sweep, filtering out shallow tags at swing levels.
▶ Built-in Alert System: Pre-configured alert conditions cover bearish sweeps, bullish sweeps, any sweep, price entering a buy-side zone, price entering a sell-side zone, and price entering any unswept zone.
▶ Visual Customisation: Choose from five colour presets (Classic, Aqua, Cosmic, Cyber, Neon) or set your own custom colours. Optional candle background highlighting marks sweep bars directly on the chart, and label text size is configurable across four options to suit different chart layouts.
🟢 Important Considerations
▶ Sweep detection references only the most recently confirmed swing high or low at the time each bar closes. On lower timeframes with frequent swing formation, raising the pivot length focuses detection on more structurally significant levels and reduces signal frequency on choppy charts.
▶ The indicator works best as a contextual layer within an existing trading framework. Sweep signals indicate that price has moved beyond a swing level and closed back inside, which is a useful data point, but should be read alongside your system and market context rather than used as a standalone trigger. Indicador

Backtest Template [Backtest Terminal]Overview — What Is This Script?
Backtest Template (BTT) is an open-source strategy framework designed to let traders test their own indicator logic without building the backtest infrastructure from scratch. Instead of writing stop loss management, session filters, alert systems, and trailing stops yourself, BTT handles all of that automatically. You bring your signal idea — BTT handles the rest.
The template is designed for all markets: stocks, Forex, gold (XAUUSD), crypto spot, and crypto futures. It ships with a pre-built Moving Average Cross trigger and Moving Average Trend filter as working examples that you replace with your own logic.
What Makes It Original
Most backtest templates on TradingView are fixed strategies that test one specific indicator. BTT introduces a User Zone architecture: a single clearly marked section near the top of the script where the user replaces one pre-built trigger and one pre-built filter with their own Pine Script code. The engine below reads four fixed variable names and runs automatically — the user never needs to touch strategy orders, stop management, session logic, or the alert system.
This design means a complete beginner can run their first backtest by changing fewer than ten lines of code, while an advanced user can plug in arrays, multi-timeframe calculations, or complex signal logic and the engine handles it identically.
What The Engine Handles Automatically
Once your signal is connected through the User Zone, the following run without any additional code:
Stop Loss and Take Profit — three unit modes: percentage of price, fixed points (Forex / CFD), or fixed dollar amount (crypto / stocks)
Stop Mode — Fixed (original level), Trailing (follows price), or Breakeven (moves to entry price)
Trailing Stop — configurable distance and activation offset, each with matching %, point, and dollar unit inputs consistent with your Stop/Target Mode selection
Breakeven Stop — configurable activation offset in the same unit system
Disable Take Profit — when using Trailing mode, an optional toggle removes the fixed TP so the trailing stop becomes the sole exit
Trade Direction — Long only, Short only, or Both
Backtest Date Range — start and end date inputs
Trading Day Filter — enable or disable any day of the week
Trade Session Hours — exchange server time filter (HHMM-HHMM format)
Trade Windows — four configurable local-time windows each independently set to Off, Blackout, or Trade Only mode with full timezone support
Entry Signal Markers — green and red triangles that only appear when all conditions pass, so chart visuals exactly match what the strategy trades
App Alerts — pre-formatted alert messages with ticker, direction, stop and target prices
Custom JSON Alerts — four separate input fields for webhook bot integration, one per order event
How To Use It — Quick Start
Open the script in Pine Editor
Find the User Zone near the top — it is clearly marked with a visual border and is the only section you need to edit
Replace the pre-built Moving Average Cross trigger block with your own indicator signal, assigning your long condition to userLong and your short condition to userShort — always add and confirmed to both
Replace the pre-built Moving Average Trend filter block with your own market condition, assigning to userFilterLong and userFilterShort
Add to chart and open Strategy Tester
User Zone Contract
The engine connects to your signal through exactly four variables. Do not rename them:
userLong → true on the bar you want to enter Long
userShort → true on the bar you want to enter Short
userFilterLong → true when Long entries are allowed
userFilterShort → true when Short entries are allowed
Always add and confirmed (barstate.isconfirmed) to userLong and userShort. This ensures the signal locks in only when the bar closes, preventing signals from changing value mid-bar.
Setting userFilterLong = true disables the Long filter entirely. Setting it to a condition like close > ta.ema(close, 200) means Long entries are only allowed when price is above that EMA. Long and Short filters are independent — you can filter one direction while leaving the other open.
Stop Loss and Take Profit — Three Unit Modes
The Stop/Target Mode setting controls how SL and TP distances are measured:
% (Percentage) — distance as a percentage of price. Suitable for stocks and crypto. Stop source can be the close price or the candle High/Low. Take profit is derived from stop distance × Risk:Reward ratio.
Point - Forex / CFD — distance in instrument ticks (syminfo.mintick). Suitable for XAUUSD, EURUSD, and other Forex/CFD instruments. Example: 100 points on EURUSD (mintick = 0.00001) = 1 pip.
Dollar - Crypto / Stock — fixed dollar distance from entry. Suitable for BTCUSD and US stocks.
All trailing and breakeven offset inputs follow the same three-unit system. Use the , , or input that matches your selected Stop/Target Mode. Using the wrong unit input will result in a mismatch between your intended stop distance and the actual calculation.
Stop Mode — Fixed, Trailing, Breakeven
Fixed — stop loss stays at the original level from entry until hit or TP is reached
Trailing — stop follows price at a configurable distance, locking in profit as price moves. The trailing activation offset controls how far price must move before trailing begins (shown as a yellow line on chart). Enable "Disable Take Profit" to let the trailing stop manage the entire exit without a fixed TP ceiling
Breakeven — stop moves to the exact entry price once price moves a configurable distance in your favour (shown as a white line on chart)
Trade Windows — Off, Blackout, Trade Only
Each of the four time windows (Tokyo, London, New York, Custom) has an independent mode selector:
Off — this window has no effect on entries (default for all four)
Blackout — block all new entries while the current time is inside this window. Useful for avoiding high-volatility opens or news events
Trade Only — only allow new entries while the current time is inside this window. Useful for targeting specific sessions or news event windows such as NFP or Fed announcements
All times are entered in your local timezone selected from the My Timezone dropdown. The engine converts to UTC internally.
Logic rules:
Multiple Blackout windows use AND NOT logic — entries are blocked if the current time is inside any Blackout window
Multiple Trade Only windows use OR logic — entries are allowed when the current time is inside any one Trade Only window
If no windows are set to Trade Only, there is no time restriction on entries (same as all Off)
Blackout and Trade Only can be combined: for example, set London to Trade Only and New York to Blackout to only trade the London session while avoiding NY volatility
Trading Day and Session
Trading Days — enable or disable any individual day of the week. Disabling a day prevents new entries — open positions are still managed on disabled days.
Trade Session — set allowed hours in exchange server time (HHMM-HHMM format). Default 0000-0000 means 24 hours with no restriction. This uses exchange server time, not your local time.
Alert System — App Alert and Custom JSON
How to activate alerts:
Set the alert mode to App Alert or Custom in the settings panel
Create a TradingView alert on the chart (right-click → Add Alert)
In the alert message box, paste exactly: {{strategy.order.alert_message}}
This placeholder delivers the correct message for each order event automatically
App Alert mode sends a pre-formatted text message for each event:
ENTRY LONG : {price}
STOP LOSS : {stop level}
TARGET PRICE : {target level}
Exit alerts include a PNL percentage. No additional setup is required.
Custom mode — JSON webhook for bot integration:
Four separate input fields accept a single-line JSON string — one per order event:
Long Entry — fires when a Long position opens
Long Exit — fires when a Long position closes (TP, SL, or trailing stop)
Short Entry — fires when a Short position opens
Short Entry — fires when a Short position opens
Short Exit — fires when a Short position closes (TP, SL, or trailing stop)
Paste your JSON as a single line into each field. TradingView's input.string stores the content as a single line regardless of how it was formatted, making it safe for all webhook receivers.
Settings Guide — Commission, Slippage, Margin
Default values are conservative starting points. Edit the strategy() declaration at the top of the script to match your broker and market. Detailed inline comments in the script explain every parameter.
Commission defaults (0.1% per side, 2 ticks slippage):
Stocks zero-commission broker → 0.0%
Stocks SET Thailand → 0.16%
Crypto spot (Binance) → 0.1%
Crypto futures (Binance taker) → 0.04%
XAUUSD $7 per standard lot → change commission_type to strategy.commission.cash_per_contract and commission_value to 0.07 ($7 ÷ 100 oz)
Position sizing (default 2% of equity):
For lot-based markets (Forex, XAUUSD) change default_qty_type to strategy.fixed and default_qty_value to the number of units. On XAUUSD: 1 unit = 1 oz, so 0.01 lot = value of 1, 0.10 lot = value of 10, 1.00 lot = value of 100.
Margin/leverage simulation:
Both margin_long and margin_short are 0 by default (no margin simulation). Formula: margin value = 100 / leverage ratio. Example: 1:500 leverage → margin_long = 0.2. These values cannot be set from the input panel — edit them directly in the strategy() call.
Repainting Warning
Before connecting any indicator to the User Zone, verify it does not repaint. A repainting indicator places signal arrows on past bars using data from future bars that did not exist at the time — backtest results will look excellent while live trading produces nothing like it.
How to check using Bar Replay:
Open the indicator on your chart and find a signal arrow in the past
Open Bar Replay and rewind to before that signal appeared
Step forward one bar at a time using Shift + →
Do not use the Play button (Shift + ↓) — bars move too fast to catch a disappearing arrow
If the arrow appears and stays permanently → safe to use. If the arrow appears then disappears or moves as you advance → repainting confirmed, do not use in a strategy.
How to check using Alert Log:
Enable the indicator's built-in alert, wait for it to fire on a live bar, then compare the alert log entry to the signal arrow on the chart. If they do not match in timing or direction → repainting.
Disclaimer
This script is published for educational purposes only. It is a framework and template — not a complete trading system and not financial advice. Backtest results shown in Strategy Tester reflect historical data only and do not guarantee future performance. Past performance is not indicative of future results.
All trading involves significant risk of loss. Do not trade with money you cannot afford to lose. The results produced by this template depend entirely on the signal logic the user provides — the author accepts no responsibility for any trading decisions made using this script or any modifications of it.
Before using any strategy in live trading, you should fully understand how it works, verify its logic independently, and test it thoroughly on a demo account. Always consult a qualified financial advisor before making investment decisions.
The pre-built Moving Average Cross trigger and Moving Average Trend filter included in the User Zone are provided as examples only — they are not recommendations to trade any specific method. Estrategia

Hurst Exponent Adaptive Supertrend [QuantAlgo]🟢 Overview
The Hurst Exponent Adaptive Supertrend identifies trending and mean-reverting market conditions by dynamically adjusting its sensitivity and band width based on the real-time persistence of price movement. It estimates the Hurst exponent through variance scaling to classify the current market regime, applies a Kalman smoother with a Hurst-scaled tracking gain to follow price with regime-appropriate responsiveness, and constructs a supertrend band whose width expands in choppy conditions and contracts in strongly trending ones. This allows traders to stay positioned through genuine trends while filtering out noise-driven whipsaws across any timeframe or instrument.
🟢 How It Works
The indicator's core methodology centres on a three-layer pipeline: regime classification via the Hurst exponent, adaptive price smoothing via a Kalman filter, and dynamic band construction that responds to the estimated market state.
First, the Hurst exponent is estimated by comparing short-run and long-run return variance over the configured lookback window. A lag-q variance is scaled against a lag-1 variance, and the ratio is log-transformed to produce a raw H value that is then clamped between 0 and 1:
var1 = ta.variance(close - close , active_h_period)
varq = ta.variance(close - close , active_h_period)
H_raw = math.log(varq / math.max(var1, 1e-10)) / (2.0 * math.log(active_h_lag))
H = math.max(0.0, math.min(H_raw, 1.0))
H values above 0.5 indicate persistent, trending behaviour. Values below 0.5 indicate mean-reversion or choppiness. This reading then drives every downstream calculation.
Next, a Kalman smoother tracks price using a gain that is amplified in trending regimes and suppressed in choppy ones, keeping the smoothed price line tight to momentum when it matters and sluggish when it does not:
adaptive_gain = math.max(math.min(active_kf_gain * (0.5 + safeH), 0.99), 0.01)
kf := na(kf ) ? close : kf + adaptive_gain * (close - kf )
Finally, the ATR-based band width is computed using a Hurst-scaled multiplier. When H is low (choppy market), the multiplier is large, widening the band to avoid false flips. When H is high (strong trend), the multiplier approaches the base value, keeping the band tight to price:
h_mult = active_atr_base + active_atr_hscale * (1.0 - safeH)
band = ta.atr(active_atr_len) * h_mult
The supertrend logic then ratchets the upper and lower bands in the direction of the prevailing trend, flipping state only when the Kalman-smoothed price crosses the opposing band. This prevents band drift from causing premature reversals during normal consolidation:
upBand := prevT == 1 ? math.max(kf - band, prevUp) : kf - band
dnBand := prevT == -1 ? math.min(kf + band, prevDn) : kf + band
trend := kf > prevDn ? 1 : kf < prevUp ? -1 : prevT
🟢 Signal Interpretation
▶ Bullish Trend (Supertrend Line Below Price with Bullish Color): When the Kalman-smoothed price crosses above the upper band, the indicator flips to a bullish state and the trailing line plots below price as a dynamic support level - the floor that price must decisively break before the uptrend is considered invalidated. The support level ratchets higher with each new bar, never pulling back, locking in the floor as the trend develops. In choppy regimes the band width is deliberately wide, meaning price can pull back significantly without breaching support, keeping traders positioned through noise-driven corrections that lack genuine bearish conviction.
▶ Bearish Trend (Supertrend Line Above Price with Bearish Color): When the Kalman-smoothed price crosses below the lower band, the indicator flips to a bearish state and the trailing line plots above price as a dynamic resistance level - the ceiling price must reclaim before a bullish reversal is confirmed. The resistance level ratchets lower with each new bar, tightening the ceiling as the downtrend develops. As with the bullish state, a wide band in low-H environments requires a substantial recovery move before the indicator reverses, allowing traders to hold directional bias through corrective bounces that stay within the noise threshold.
🟢 Features
▶ Preconfigured Presets: Three optimised parameter sets tailored to different trading styles and timeframes. "Default" delivers balanced trend detection for swing trading on 4-hour and daily charts, with moderate Kalman gain and band scaling suited to typical momentum cycles. "Fast Response" uses a higher tracking gain, shorter ATR window, and tighter base multiplier for intraday trading on 5-minute to 1-hour charts, producing earlier trend flips better suited to active traders. "Smooth Trend" applies a lower Kalman gain, longer ATR period, and wider band scaling for position trading on daily and weekly charts, confirming only major directional shifts with minimal false positives.
▶ Built-in Alerts: Two alert conditions enable automated monitoring of trend transitions without constant chart observation. "Bullish Trend Signal" triggers on the bar the indicator first flips to a bullish state, alerting for potential long entries. "Bearish Trend Signal" fires on the bar the indicator first confirms a bearish state, signalling potential short entries or long exits. Both alerts include the exchange, ticker, and timeframe in the alert message for immediate context.
▶ Visual Customisation: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, and Custom) accommodate different chart themes and personal preferences, with coordinated bullish and bearish color schemes applied consistently to the trend line. When the Custom preset is selected, independent color pickers for bullish and bearish states allow full manual control over the indicator's appearance.
Indicador

Volume Bubbles [QuantAlgo]🟢 Overview
The Volume Bubbles indicator is a multi-layered volume cluster detection system that identifies statistically significant volume events directly on your price chart, classifying them by magnitude (Small, Medium, Big) and direction (Buy, Sell, Mixed). By combining adaptive percentile thresholds across multiple lookback windows with optional volume delta analysis, this indicator highlights moments of elevated trading activity that often signal institutional participation, trend acceleration, or potential reversals across every timeframe and market.
🟢 How It Works
The indicator begins by establishing a lower timeframe for volume delta calculation. When auto-select is enabled, it picks a granular timeframe based on your chart period, using 1-second bars for sub-minute charts, 1-minute bars for intraday charts, 5-minute bars for daily charts, and 60-minute bars for higher timeframes. This allows the indicator to estimate net buying and selling pressure within each chart bar:
= taLib.requestVolumeDelta(lowerTimeframe)
float netDelta = nz(lastDelta)
float absDelta = math.abs(netDelta)
The core detection engine then calculates percentile thresholds for both volume and absolute delta across three independent lookback windows (Short, Medium, Long). Each window computes its own threshold for each cluster tier using linear interpolation:
float vSmallShort = ta.percentile_linear_interpolation(volume, shortLen, smallPct)
float vSmallMid = ta.percentile_linear_interpolation(volume, midLen, smallPct)
float vSmallLong = ta.percentile_linear_interpolation(volume, longLen, smallPct)
This means a bar's volume is not compared against a single average but ranked against the full distribution of recent volume history from multiple perspectives. A Small cluster must exceed the 75th percentile (top 25%), a Medium cluster the 90th percentile (top 10%), and a Big cluster the 97th percentile (top 3%) by default.
To filter noise, a consensus system requires agreement across the lookback windows before confirming a cluster:
f_consensus(bool pS, bool pM, bool pL, string mode) =>
int hits = (pS ? 1 : 0) + (pM ? 1 : 0) + (pL ? 1 : 0)
switch mode
"Any Window" => hits >= 1
"Majority (2 of 3)" => hits >= 2
"All Windows (strictest)" => hits >= 3
In Majority mode, for example, at least two of the three windows must agree that volume exceeds the threshold before a cluster is plotted. This prevents false signals from temporary spikes that look significant in one context but not another.
Once a cluster is confirmed, it is classified as Buy, Sell, or Mixed based on the selected method. Candle Direction uses the bar's open/close relationship, Delta Direction uses the sign of net volume delta, and Both requires agreement between the two, labeling any conflict as Mixed.
🟢 Key Features
▶ The indicator offers four detection methods, each designed to balance sensitivity and precision depending on data availability and trading style.
1. Volume Only: Uses raw bar volume as the sole input for cluster detection. This is the simplest and most universal mode, working on any symbol that provides volume data. It identifies all statistically elevated volume events regardless of whether buying or selling dominated, making it useful for spotting general activity surges around key levels, news events, or session opens.
2. Delta Only: Uses the absolute value of net volume delta instead of total volume. This mode triggers only when directional pressure (not just raw activity) is statistically elevated. It filters out high-volume bars where buying and selling were roughly balanced, focusing instead on bars where one side clearly dominated. Requires lower timeframe data availability.
3. Volume + Delta: Both volume and delta must independently exceed their respective percentile thresholds. This is the strictest detection mode. A cluster only appears when there is both unusually high total activity and unusually strong directional flow, filtering out ambiguous bars where volume was high but evenly split between buyers and sellers.
4. Volume OR Delta: Either elevated volume or elevated directional delta triggers a cluster. This is the most inclusive mode, capturing both pure volume events (such as index rebalancing or option expiration activity) and strong directional surges that may occur on relatively normal total volume. Best suited for traders who prefer broader coverage and are comfortable filtering signals with additional context.
▶ Detailed Tooltip Overlay: Hovering over any bubble reveals a comprehensive diagnostic panel summarizing the full context behind that cluster. The tooltip displays the cluster tier and direction label (e.g., BIG BUY or MEDIUM SELL), the formatted volume value, net delta value (or "n/a" if delta data is unavailable), the volume-to-average ratio expressed as a multiple, the active detection method (with a fallback note if delta was unavailable and the method defaulted to Volume Only), the individual window confirmations for both volume and delta shown as a compact S M L grid indicating which of the short, medium, and long lookback windows passed their threshold, and the classification mode used to determine the buy/sell label. This gives full transparency into exactly why each cluster was detected and how it was classified, without cluttering the chart itself.
▶ Built-in Alert System: Pre-configured alert conditions for Big clusters, Medium-or-larger clusters, and any cluster detection, allowing you to receive notifications for the volume events that matter most to your strategy.
▶ Visual Customization: Choose from 5 color presets (Classic, Aqua, Cosmic, Cyber, Neon) or define your own custom color scheme. Optional in-bubble text displays volume, delta, ratio, or combinations, while the tooltip diagnostic panel remains accessible on hover regardless of whether bubble labels are enabled or disabled.
🟢 Important Notes
1. This indicator requires volume data to function. Make sure you are using a ticker from an exchange that provides volume data. Symbols that do not report volume (such as certain forex pairs on specific brokers or custom-built indices) will trigger a warning message on the chart and produce no signals. If you see the "No Volume Data" warning, switch to a symbol or exchange that supports volume reporting.
2. Whether you are scalping on lower timeframes or swing trading on daily and weekly charts, Volume Bubbles is designed to complement your existing setup rather than replace it. Use it as a confirmation layer alongside your preferred strategy to identify when statistically significant volume activity aligns with your trade thesis, adding a data-driven edge to entries, exits, and key level analysis across any timeframe and market. Indicador

Adaptive SuperTrend Oscillator [QuantAlgo]🟢 Overview
The Adaptive SuperTrend Oscillator transforms the classic SuperTrend indicator into a normalized momentum score that adapts to changing market conditions. Instead of displaying a simple above/below signal on the price chart, it measures how far price has moved from the SuperTrend line and scales that distance against an Efficiency Ratio-driven ATR that automatically adjusts between trending and ranging environments. The result is a centered oscillator with dynamically calculated overbought and oversold thresholds, helping traders read the strength behind a trend rather than just its direction, across different markets and timeframes.
🟢 How It Works
The foundation of the indicator is the distance between the closing price and the SuperTrend line:
= ta.supertrend(active_multiplier, active_atr_length)
price_distance = close - supertrend_line
A positive distance means price is above the SuperTrend line, indicating a bullish condition. A negative distance indicates price is below it, reflecting a bearish condition. The raw distance alone is not directly comparable across instruments or timeframes, so the indicator normalizes it using an adaptive ATR.
The normalization layer is driven by an Efficiency Ratio, which measures how directionally efficient recent price movement has been. It compares the net price change over the lookback window against the total path length traveled:
price_change = math.abs(close - close )
path_length = math.sum(math.abs(close - close ), active_er_length)
efficiency_ratio = path_length != 0 ? price_change / path_length : 0.0
A high Efficiency Ratio means price is moving in a consistent direction with little back-and-forth. A low ratio indicates choppy, non-directional movement. This reading is then used to blend between a fast and slow ATR period:
adaptive_atr = efficiency_ratio * ta.atr(active_norm_fast) + (1.0 - efficiency_ratio) * ta.atr(active_norm_slow)
score = adaptive_atr != 0 ? price_distance / adaptive_atr * 100 : 0.0
During trending conditions the fast ATR period is weighted more heavily, allowing the score to move more freely. During choppy conditions the slow ATR period dominates, dampening the score and reducing low-conviction readings. The final score is expressed as a percentage of the adaptive ATR, making it directly comparable across different instruments and volatility environments.
Overbought and oversold levels are derived dynamically from the rolling standard deviation of the score itself rather than fixed values:
score_deviation = ta.stdev(score, 100)
ob_extreme = score_deviation * 3
ob_level = score_deviation * 2
os_level = -score_deviation * 2
os_extreme = -score_deviation * 3
This means the threshold levels expand during volatile periods and contract during quiet ones, keeping the overbought and oversold zones statistically consistent relative to recent score behavior.
🟢 Signal Interpretation
▶ Bullish Trend (Score Above Zero, Outside Neutral Zone, Green): When the score is positive and exceeds the neutral threshold, the oscillator confirms that price is above the SuperTrend line and momentum is directionally efficient enough to register. The score's gradient intensity reflects how far momentum has extended relative to the adaptive ATR baseline. The trend remains bullish until the score crosses back below zero or into the neutral zone.
▶ Bearish Trend (Score Below Zero, Outside Neutral Zone, Red): When the score is negative and falls below the neutral threshold, the oscillator confirms that price is below the SuperTrend line. A deeper negative score indicates stronger downside momentum relative to the normalization baseline. The trend remains bearish until the score crosses back above zero or into the neutral zone.
▶ Neutral Zone (Score Within Threshold, Grey): When the absolute score value is within the neutral threshold, the oscillator treats the reading as non-directional regardless of which side of zero it sits on. This filters out low-conviction conditions where the SuperTrend distance is small relative to the adaptive ATR, preventing the indicator from registering trend signals during consolidation or choppy price action.
▶ Overbought and Oversold Levels (2σ and 3σ Bands): When the score reaches the 2σ or 3σ bands, it indicates that momentum has extended significantly relative to its own recent history. These are not reversal signals by themselves, but they mark zones where the trend is stretched and worth monitoring for potential exhaustion.
🟢 Features
▶ Preconfigured Presets: Three parameter sets cover different trading approaches. "Default" uses moderate SuperTrend sensitivity for swing trading on 4-hour and daily charts. "Fast Response" tightens the SuperTrend bands and shortens normalization windows for intraday use on 5-minute to 1-hour charts. "Smooth Trend" widens the SuperTrend bands and extends normalization windows for position trading on daily and weekly timeframes.
▶ Built-in Alerts: Seven alert conditions cover the full range of oscillator states. Trend transition alerts fire when the score crosses into bullish, bearish, or neutral territory. Separate alerts trigger when the score reaches the 2σ overbought or oversold levels and again when it reaches the more extreme 3σ levels, enabling graduated monitoring without requiring constant chart observation.
▶ Visual Customization: Six color presets (Classic, Aqua, Cosmic, Cyber, Neon, plus Custom) coordinate colors across the score line, ribbon fills, overbought/oversold bands, and optional bar coloring. The ribbon uses three fill layers between the score line and zero, each at increasing transparency, creating a gradient that visually represents the weight of momentum behind the current reading. Optional bar coloring applies trend state colors directly to price bars for quick multi-timeframe reference.
Indicador

Auto Play Ping/Pong [UAlgo]Auto Play Ping/Pong is a fully self running arcade style mini game built entirely in Pine Script and rendered directly on the chart. Instead of analyzing price, this script turns the chart area into a compact game field where two AI controlled paddles rally a moving ball from one side to the other while the score updates in real time.
The script is designed as a visual and technical showcase of what Pine Script can do with custom objects such as boxes, lines, labels, arrays, and user defined types. It demonstrates persistent state handling, frame by frame physics updates, collision detection, automatic paddle control, scoring logic, and motion trail rendering, all inside a chart overlay.
The left and right paddles are both controlled by simple AI logic. Each paddle reacts to the vertical position of the ball and tries to align itself for the next return. The ball bounces off the top and bottom boundaries, changes direction when it touches a paddle, and resets to the center when one side misses. A trail effect is also added to make movement easier to follow and visually more dynamic.
What makes this script interesting is that it is not simply drawing static shapes. It maintains a persistent game state across updates, modifies that state on every bar, and redraws the field using live object coordinates. This makes it a playful but technically instructive example of animation and object control in Pine Script.
In practical terms, this script is a creative visual project rather than a trading tool. It is useful for demonstrating real time state management, chart object animation, and game style logic inside TradingView.
🔹 Features
🔸 Fully Automated Gameplay
Both paddles are controlled automatically. The script continuously tracks the ball position and moves each paddle vertically to intercept the ball without user input.
🔸 Persistent Game State
The script uses a dedicated game state object to store ball position, paddle positions, scores, trail points, and drawing references. This allows the whole game to evolve smoothly over time.
🔸 Ball Physics and Collision Logic
The ball moves with its own horizontal and vertical velocity, bounces off the top and bottom walls, reacts to paddle contact, and changes its vertical angle depending on where it hits the paddle.
🔸 Score Tracking
If one paddle misses the ball, the opposing side scores a point. The ball then resets to the center and starts a fresh rally with directional variation.
🔸 Paddle AI With Speed Limits
Each paddle follows the ball using its own maximum movement speed. This gives the game a natural chase behavior and prevents instant teleport style motion.
🔸 Motion Trail Effect
The ball leaves a fading trail behind it using a sequence of stored points and prebuilt lines. This improves visual clarity and gives the movement a smoother arcade feel.
🔸 Custom Game Field Rendering
The play area is drawn with a background box, two paddle lines, a circular ball label, a score label, and trail segments. Everything is positioned relative to the current bar index.
🔸 Chart Overlay Animation
The game is drawn directly over the chart with overlay=true , which turns the chart into a moving visual canvas.
🔹 Calculations
1) Defining the Game Geometry and Core Constants
var int GAME_WIDTH = 80
var float GAME_HEIGHT = 100.0
var float PADDLE_H = 20.0
var float BALL_SPD_X = 1.8
var float BALL_SPD_Y = 1.2
var int TRAIL_LEN = 10
var float AI_SPEED_1 = 1.1
var float AI_SPEED_2 = 1.2
This block defines the full physical layout and motion parameters of the game.
GAME_WIDTH sets the horizontal size of the play area.
GAME_HEIGHT sets the vertical size.
PADDLE_H defines paddle height.
BALL_SPD_X and BALL_SPD_Y define the initial ball speed.
TRAIL_LEN defines how many trail segments are stored.
AI_SPEED_1 and AI_SPEED_2 define how quickly each paddle can move.
So before any gameplay starts, the script already establishes the dimensions and motion rules of the whole arena.
2) Defining the Point and Game State Objects
type Point
float x
float y
type GameState
float ball_x
float ball_y
float ball_vx
float ball_vy
float p1_y
float p2_y
int p1_score
int p2_score
box bg_box
line p1_line
line p2_line
label ball_lbl
label score_lbl
array trail_pts
array trail_lines
This is the structural foundation of the script.
The Point type stores one coordinate pair. It is used for the trail system.
The GameState type stores the full live state of the game:
the ball position,
the ball velocity,
the vertical positions of both paddles,
both scores,
the main drawing objects,
and the trail arrays.
This design is important because the script is not just drawing shapes independently. It is managing a complete game world through one persistent object.
3) Creating the Visual Objects on the First Bar
method init_drawings(GameState state) =>
state.bg_box := box.new(na, na, na, na, border_color=color.new(color.gray, 60), border_width=1, bgcolor=C_BG)
state.p1_line := line.new(na, na, na, na, color=C_P1, width=4)
state.p2_line := line.new(na, na, na, na, color=C_P2, width=4)
state.ball_lbl := label.new(na, na, "", color=C_BALL, style=label.style_circle, size=size.small)
state.score_lbl := label.new(na, na, "0 - 0", color=color.new(color.white, 100), textcolor=color.silver, style=label.style_none, size=size.large)
This method creates the core objects that will later be updated every frame.
The script builds:
a background box for the game field,
a line for the left paddle,
a line for the right paddle,
a circular label for the ball,
and a score label.
These are created only once, then reused and repositioned as the game evolves. This is much more efficient than deleting and recreating everything on every update.
4) Preparing the Ball Trail System
for i = 0 to TRAIL_LEN - 1
color fade_color = color.new(C_BALL, 100 - int((TRAIL_LEN - i) * 100 / TRAIL_LEN))
state.trail_lines.push(line.new(na, na, na, na, color=fade_color, width=2))
state.trail_pts.push(Point.new(state.ball_x, state.ball_y))
This loop initializes the trail effect.
For each trail slot, the script creates:
a line object with progressively changing transparency,
and a point initialized at the current ball position.
The idea is simple. The newest trail segments remain more visible, while older trail segments fade away. This creates the illusion of motion persistence behind the ball.
So the trail is not a single effect. It is a chain of stored points and lines that move along with the ball.
5) Updating Ball Position Each Frame
method update_physics(GameState state) =>
state.ball_x += state.ball_vx
state.ball_y += state.ball_vy
This is the first step of the physics engine.
On every update, the ball position is advanced by its horizontal and vertical velocity values. This is the basic motion rule of the game.
If nothing else happened, the ball would keep moving in a straight line forever. The rest of the physics method exists to modify that path through AI movement, wall bounces, paddle collisions, and scoring resets.
6) Left Paddle AI Logic
if state.ball_vx < 0
if state.p1_y + PADDLE_H/2 < state.ball_y
state.p1_y += math.min(AI_SPEED_1, state.ball_y - (state.p1_y + PADDLE_H/2))
else if state.p1_y - PADDLE_H/2 > state.ball_y
state.p1_y -= math.min(AI_SPEED_1, (state.p1_y - PADDLE_H/2) - state.ball_y)
This block controls the left paddle.
The paddle only reacts when the ball is moving toward the left side, which is why the script first checks:
state.ball_vx < 0
Then it compares the ball’s vertical position to the top and bottom edges of the paddle. If the ball is above the paddle center zone, the paddle moves upward. If the ball is below it, the paddle moves downward.
The amount of movement is limited by AI_SPEED_1 , which prevents the paddle from moving instantly.
So the left paddle behaves like a simple tracking AI that tries to align itself with incoming ball position.
7) Right Paddle AI Logic
if state.ball_vx > 0
if state.p2_y + PADDLE_H/2 < state.ball_y
state.p2_y += math.min(AI_SPEED_2, state.ball_y - (state.p2_y + PADDLE_H/2))
else if state.p2_y - PADDLE_H/2 > state.ball_y
state.p2_y -= math.min(AI_SPEED_2, (state.p2_y - PADDLE_H/2) - state.ball_y)
This is the mirror logic for the right paddle.
It only moves when the ball is traveling toward the right side. It uses the same tracking idea as the left paddle, but its maximum speed is set independently by AI_SPEED_2 .
That means each side can have slightly different behavior and difficulty characteristics.
8) Keeping Paddles Inside the Arena
state.p1_y := math.max(PADDLE_H/2, math.min(GAME_HEIGHT - PADDLE_H/2, state.p1_y))
state.p2_y := math.max(PADDLE_H/2, math.min(GAME_HEIGHT - PADDLE_H/2, state.p2_y))
After paddle movement is updated, the script clamps both paddles so they cannot leave the top or bottom of the field.
The center of each paddle must remain between:
PADDLE_H/2
and
GAME_HEIGHT - PADDLE_H/2
This ensures that the visible paddle body never extends outside the game frame.
9) Ball Bounce on Top and Bottom Walls
if state.ball_y >= GAME_HEIGHT
state.ball_y := GAME_HEIGHT
state.ball_vy := -state.ball_vy
else if state.ball_y <= 0
state.ball_y := 0
state.ball_vy := -state.ball_vy
This block handles vertical wall collisions.
If the ball reaches or exceeds the top boundary, its vertical position is snapped to the top edge and its vertical velocity is reversed.
If the ball reaches or drops below the bottom boundary, the same thing happens at the lower edge.
This creates a classic arcade bounce effect where the ball reflects off the horizontal walls and stays inside the arena.
10) Left Side Paddle Collision and Right Side Scoring
if state.ball_x <= 0
if math.abs(state.ball_y - state.p1_y) <= PADDLE_H/2 + 3
state.ball_x := 0
state.ball_vx := -state.ball_vx
state.ball_vy += (state.ball_y - state.p1_y) * 0.15
state.ball_vy := math.max(-4.0, math.min(4.0, state.ball_vy))
else
state.p2_score += 1
state.ball_x := GAME_WIDTH / 2
state.ball_y := GAME_HEIGHT / 2
state.ball_vx := BALL_SPD_X
state.ball_vy := BALL_SPD_Y * (state.p2_score % 2 == 0 ? 1 : -1)
This is one of the main gameplay blocks.
When the ball reaches the left boundary, the script checks whether the ball is close enough to the left paddle vertically. If yes, it counts as a successful return.
On a successful return:
the ball is snapped to the left edge,
its horizontal velocity is reversed,
and its vertical velocity is modified based on where it hit the paddle.
This extra adjustment is important because it creates angled returns rather than perfectly repetitive motion. The farther from the paddle center the hit occurs, the more the vertical speed is changed.
The vertical speed is then clamped between negative four and positive four to keep the game stable.
If the left paddle misses, the right side scores a point. The ball resets to the center, moves back toward the right, and gets a vertical direction that alternates based on score parity.
11) Right Side Paddle Collision and Left Side Scoring
else if state.ball_x >= GAME_WIDTH
if math.abs(state.ball_y - state.p2_y) <= PADDLE_H/2 + 3
state.ball_x := GAME_WIDTH
state.ball_vx := -state.ball_vx
state.ball_vy += (state.ball_y - state.p2_y) * 0.15
state.ball_vy := math.max(-4.0, math.min(4.0, state.ball_vy))
else
state.p1_score += 1
state.ball_x := GAME_WIDTH / 2
state.ball_y := GAME_HEIGHT / 2
state.ball_vx := -BALL_SPD_X
state.ball_vy := BALL_SPD_Y * (state.p1_score % 2 == 0 ? 1 : -1)
This is the mirror version of the left side logic.
When the ball reaches the right boundary, the script tests whether the right paddle is in position. If it is, the ball bounces back left and its vertical speed changes according to impact location. If not, the left player scores and the ball resets to center.
Together, the left and right boundary blocks define the full rally and scoring logic of the game.
12) Updating the Trail Memory
state.trail_pts.unshift(Point.new(state.ball_x, state.ball_y))
state.trail_pts.pop()
After the new ball position is resolved, the script stores it at the front of the trail point array. Then it removes the oldest stored point from the end.
This gives the script a rolling history of recent ball positions. Those points are later used to position each trail segment.
So the trail always follows the newest motion path while keeping a fixed length.
13) Converting Game Coordinates Into Chart Coordinates
method draw_frame(GameState state, int base_x) =>
int right_x = base_x + 5
int left_x = right_x - GAME_WIDTH
This method begins the rendering step.
The game is not drawn in a separate graphics window. It is projected directly onto chart coordinates. The current bar index acts as the base anchor, and the script defines a right edge slightly ahead of it. From that right edge, it subtracts the game width to get the left edge.
So the whole game field is mapped into a section of chart space that moves with the current bar position.
14) Drawing the Background and Paddles
state.bg_box.set_lefttop(left_x, GAME_HEIGHT)
state.bg_box.set_rightbottom(right_x, 0)
state.p1_line.set_xy1(left_x, state.p1_y + PADDLE_H/2)
state.p1_line.set_xy2(left_x, state.p1_y - PADDLE_H/2)
state.p2_line.set_xy1(right_x, state.p2_y + PADDLE_H/2)
state.p2_line.set_xy2(right_x, state.p2_y - PADDLE_H/2)
This block updates the main field and the paddle drawings.
The background box spans from the left edge to the right edge and from zero to the full game height.
The left paddle is drawn as a vertical line on the left boundary.
The right paddle is drawn as a vertical line on the right boundary.
Each paddle extends above and below its center position by half the paddle height. That makes the paddle length consistent and easy to manage mathematically.
15) Drawing the Ball and the Score
state.ball_lbl.set_xy(left_x + int(math.round(state.ball_x)), state.ball_y)
state.score_lbl.set_xy(left_x + GAME_WIDTH/2, GAME_HEIGHT - 10)
state.score_lbl.set_text(str.tostring(state.p1_score) + " - " + str.tostring(state.p2_score))
This block positions the moving ball and updates the scoreboard.
The ball label is placed by adding the ball’s internal game x coordinate to the left boundary of the field. Its y coordinate is the current ball height.
The score label is placed near the top center of the arena and updated with the current left and right scores.
So every frame, the game communicates both live motion and match progress.
16) Drawing the Motion Trail
for i = 0 to TRAIL_LEN - 1
Point p1 = state.trail_pts.get(i)
Point p2 = i + 1 < TRAIL_LEN ? state.trail_pts.get(i + 1) : p1
line l = state.trail_lines.get(i)
l.set_xy1(left_x + int(math.round(p1.x)), p1.y)
l.set_xy2(left_x + int(math.round(p2.x)), p2.y)
This loop converts stored trail points into visible trail segments.
For each trail slot, the script reads one point and the next point after it. Then it updates the corresponding trail line so it connects those two positions.
Because the trail lines were created with different transparency levels earlier, the newest segments appear stronger and older segments fade out.
This gives the ball a continuous motion streak that makes gameplay easier to follow visually.
17) Persistent State Initialization
varip GameState state = GameState.new(
ball_x = GAME_WIDTH / 2,
ball_y = GAME_HEIGHT / 2,
ball_vx = BALL_SPD_X,
ball_vy = BALL_SPD_Y,
p1_y = GAME_HEIGHT / 2,
p2_y = GAME_HEIGHT / 2,
p1_score = 0,
p2_score = 0,
trail_pts = array.new(),
trail_lines = array.new()
)
This block creates the persistent live game state.
The ball starts in the center of the arena.
Both paddles start in the vertical center.
Both scores start at zero.
Empty arrays are prepared for the trail points and trail lines.
The use of varip is important here because it keeps the game state persistent as the script updates, allowing the game to evolve continuously rather than resetting each time.
18) First Bar Initialization and Main Update Loop
if barstate.isfirst
state.init_drawings()
state.update_physics()
state.draw_frame(bar_index)
This is the main execution flow.
On the very first bar, the script creates all required drawings through init_drawings() .
After that, every update performs two steps:
first the game physics are advanced,
then the new state is rendered onto the chart.
This is the standard game loop pattern:
update state,
then draw state.
19) Invisible Plot Anchors
plot(100, color=color.new(color.white, 100))
plot(0, color=color.new(color.white, 100))
These invisible plots help stabilize the vertical scale for the game area.
Because the whole arena is designed between zero and one hundred on the y axis, plotting hidden values at those levels ensures the script keeps a consistent vertical drawing space.
This is a subtle but important implementation detail. Without it, the game objects could be compressed or mispositioned by automatic scaling behavior.
20) Practical Interpretation
Auto Play Ping/Pong is best understood as a Pine Script animation and state management demo rather than as a market analysis indicator. Its real value comes from showing how chart objects, arrays, persistent state, and update logic can be combined to create a living visual system inside TradingView.
The script demonstrates:
state persistence,
object reuse,
basic game physics,
simple AI motion,
collision handling,
score management,
and visual effects such as motion trails.
That makes it a strong example for anyone exploring creative Pine development, chart animation, or non traditional overlay design. Indicador

Volatility-Adjusted Rate of Change [QuantAlgo]🟢 Overview
The Volatility-Adjusted Rate of Change (VA-ROC) is a momentum oscillator that normalizes price changes against current market volatility, helping traders identify meaningful momentum shifts, spot overbought/oversold extremes, and filter out noise caused by changing volatility regimes. By measuring how large a price move is relative to what's normal for the instrument, this indicator reveals genuine directional pressure that raw momentum readings often obscure.
🟢 How It Works
The indicator begins by calculating the single-bar price change and dividing it by the Average True Range over a configurable lookback period. This normalization step ensures that the same oscillator reading carries equal significance whether applied to a low-volatility blue chip or a highly volatile cryptocurrency, a concept absent from traditional rate of change indicators.
price_momentum = ta.change(close) / ta.atr(atr_length)
When price rises by an amount that is large relative to recent volatility, the normalized momentum produces a strong positive reading. Conversely, a decline that is modest in absolute terms but significant relative to the current ATR environment will register appropriately. This volatility-adjustment prevents the oscillator from generating inflated signals during high-volatility regimes or muted signals during quiet markets.
A sensitivity multiplier then scales the normalized value, allowing traders to compress or amplify the oscillator's range to suit their instrument and timeframe:
va_roc = calc_ma(price_momentum * sensitivity, ma_length, ma_type)
The scaled momentum is then smoothed using a configurable moving average (supporting SMA, EMA, WMA, RMA, HMA, VWMA, DEMA, and TEMA), which filters bar-to-bar noise while preserving the shape of genuine momentum waves. The smoothed output is the final VA-ROC value, plotted against a system of four threshold levels that define bullish, bearish, neutral, and extreme zones.
Momentum state is determined by the oscillator's position relative to these thresholds:
is_bullish = va_roc > upper_threshold
is_bearish = va_roc < lower_threshold
Crossings into bullish or bearish territory, zero-line crosses, and entries into extreme zones each generate distinct signals and corresponding alerts.
🟢 Key Features
The indicator is built around a threshold-based momentum framework with gradient-colored visualization, preset configurations, and a full alert system, all designed to give traders immediate clarity on momentum conditions without manual tuning.
1. Volatility Normalization: Unlike traditional ROC or momentum oscillators that produce raw price differences, VA-ROC divides every price change by the ATR, creating a dimensionless reading that remains consistent across instruments, timeframes, and volatility regimes. A reading of +1.0 always means "price moved one ATR's worth in a single bar", whether you're trading forex, equities, or crypto. This eliminates the need to recalibrate threshold levels when switching between assets.
2. Adaptive Threshold Zones: Four configurable levels (Upper Extreme, Upper Threshold, Lower Threshold, and Lower Extreme) divide the oscillator into five distinct momentum zones. The neutral zone between the upper and lower thresholds represents normal market fluctuation. Crossings above the upper threshold confirm bullish momentum, while crossings below the lower threshold confirm bearish momentum. The extreme levels mark climactic conditions where momentum is unusually powerful, often coinciding with exhaustion points or the early stages of a strong trend continuation.
3. Preset Configurations: Three built-in presets automatically optimize the sensitivity, ATR lookback, MA type, and smoothing length for different trading styles. Default provides balanced readings suited for swing trading on 4H and daily charts. Fast Response amplifies small moves with minimal smoothing for intraday scalping. Smooth Trend compresses the oscillator and applies heavier smoothing to highlight only significant directional moves for position trading.
4. Built-in Alert System: Comprehensive alerts covering all key momentum events, including bullish and bearish momentum confirmation, zero-line crossovers in both directions, and entries into upper and lower extreme zones. A combined momentum direction change alert is also included. All alerts carry exchange, ticker, and interval placeholders for seamless integration with notification workflows.
5. Visual Customization: Choose from 5 color presets (Classic, Aqua, Cosmic, Cyber, Neon) or create a fully custom color scheme using individual bullish, bearish, and neutral color pickers. Optional price bar coloring overlays the oscillator's momentum colors directly onto your main chart candles, tinting bars bullish or bearish based on the current threshold state while leaving neutral bars uncolored, providing instant trend confirmation without switching panels.
Indicador

3D Volume Profile [UAlgo]3D Volume Profile is a chart based volume profile indicator that takes a classic horizontal profile concept and presents it as a pseudo 3D structure directly on price. Instead of drawing flat histogram bars only, the script renders each profile row as a shaded 3D block with a front face, a side face, and a top face, which creates a stronger visual sense of depth and distribution.
The indicator runs on price ( overlay=true ) and builds a rolling volume profile over a user defined lookback window. It divides the recent price range into fixed bins, distributes candle volume across those bins, identifies the Point of Control and the Value Area, and then draws the result on the right side of the chart. Each row is color coded by dominant flow direction, which means the profile can show whether a bin was more buy dominated or sell dominated in addition to showing how much total volume accumulated there.
This makes the tool useful for traders who want more than a basic profile display. It combines:
A rolling horizontal volume profile
Buy versus sell dominance shading
Point of Control and Value Area detection
A forward projected 3D style histogram
Clear POC, VAH, and VAL reference lines on the chart
The final result is a visually rich profile tool designed for fast structural reading, especially when identifying acceptance zones, thin areas, and dominant participation regions.
🔹 Features
🔸 1) Rolling Volume Profile Over a Recent Window
The script builds a rolling profile from the most recent user selected number of bars. This means the profile continuously adapts as new bars come in, making it more useful for current market structure analysis than a fixed session only approach.
🔸 2) 3D Style Histogram Rendering
Each volume row is drawn as a pseudo 3D block rather than a flat rectangle. The script creates:
A front face
A side face
A top face
The side and top faces are shaded versions of the main color, which gives the profile a depth effect and makes the structure easier to read visually.
🔸 3) Customizable 3D Depth in X and Y
The 3D effect is controlled with two settings:
3D Depth X , which controls how far the rear face is shifted horizontally in bars
3D Depth Y , which controls how far the rear face is shifted vertically as a percentage of row height
This allows the user to make the profile look flatter or more pronounced depending on preference.
🔸 4) Buy and Sell Volume Dominance Coloring
Each bin tracks both buy volume and sell volume. If buy volume is greater than or equal to sell volume, the row uses the bullish color. If sell volume dominates, the row uses the bearish color.
This means the profile is not only a measure of total activity. It also adds directional context to each price zone.
🔸 5) Point of Control Detection
The script identifies the row with the highest total volume and marks it as the Point of Control. The POC is highlighted with its own dedicated color and is visually distinct from the rest of the profile.
This gives traders an immediate reference for the most active price zone in the rolling range.
🔸 6) Value Area Calculation
The indicator calculates a Value Area around the Point of Control based on the user selected percentage. Bins inside the Value Area are marked and recolored with the Value Area color, which makes the high participation region easy to identify.
🔸 7) Forward Projected Profile Layout
The profile is drawn to the right of current price using a configurable offset. This keeps the active candle area readable while still placing the profile in a clear and accessible location.
🔸 8) Adjustable Resolution and Width
Users can control:
The lookback length
The number of profile rows
The maximum width of the histogram
The right side offset
This makes the indicator suitable for both coarse structural analysis and more detailed profile inspection.
🔸 9) POC, VAH, and VAL Reference Lines
After the profile is built, the script calculates the POC, Value Area High, and Value Area Low, then projects horizontal reference lines across the chart. Labels are placed to the right so the key levels are clearly marked.
🔸 10) Row by Row Dominance and Acceptance Reading
Because each row stores total volume, buy volume, sell volume, Value Area membership, and POC status, the indicator gives a layered view of the market:
Where the most activity occurred
Which zones were accepted
Which zones were dominated by buyers
Which zones were dominated by sellers
🔸 11) Premium Visual Presentation
The script uses shaded faces, dedicated POC highlighting, Value Area recoloring, and clean right side labels. This makes it more presentation focused than a basic flat profile and improves chart readability for manual analysis.
🔹 Calculations
1) Profile Range Detection
The script first finds the highest high and lowest low inside the active lookback window. This defines the full vertical range of the volume profile. Only the most recent bars inside that window are used for profile construction.
2) Bin Initialization
Once the recent range is known, the script divides that price range into the chosen number of bins. Each bin stores:
Top boundary
Bottom boundary
Total volume
Buy volume
Sell volume
Flags for Value Area and POC
The bin size is calculated by dividing the total price range by the number of rows.
3) Volume Distribution Across Price Bins
For each candle, the script determines which bins the candle spans. It then spreads that candle’s volume evenly across all touched bins.
This is important because the script does not place the full candle volume into a single price level. Instead, it allocates the candle volume across the portion of the profile that candle covers.
Important implementation note:
This script uses equal distribution across the spanned bins, not proportional overlap weighting. That means each touched row receives the same share of the candle’s volume.
4) Buy Versus Sell Volume Classification
The script classifies each candle as buy dominated or sell dominated using candle direction:
If close is greater than or equal to open, the candle is treated as buy volume
If close is below open, the candle is treated as sell volume
That candle’s allocated volume is then added to either volBuy or volSell inside each touched bin.
This is a practical directional approximation, not true bid ask tape volume.
5) Total Volume and POC Detection
After all candles are processed, the script scans every bin and calculates:
The total volume across the profile
The maximum single bin volume
The POC index
The POC is the bin with the highest total volume. That bin is marked as both isPOC and isVA before Value Area expansion begins.
6) Value Area Expansion Logic
The Value Area is built around the POC by expanding upward and downward until the selected percentage of total profile volume is included.
The script compares the next bin above and the next bin below the current Value Area. It adds whichever side has greater volume first. This continues until cumulative included volume reaches the target Value Area percentage.
This creates a standard profile style Value Area centered on the highest participation region.
7) Histogram Width Normalization
Each row’s width is scaled relative to the maximum volume row:
The row with the most volume becomes the widest
Smaller rows are scaled proportionally
This means width directly communicates relative participation at each price zone.
8) Color Selection Logic
For each bin, the script first determines whether buy volume or sell volume dominates:
If buy volume is greater than or equal to sell volume, it uses the bullish color
Otherwise it uses the bearish color
Then the script overrides that base direction color if needed:
If the row is the POC, it uses the POC color
If the row is inside the Value Area, it uses the Value Area color
This gives the profile a clear visual hierarchy:
POC first
Value Area second
Directional dominance otherwise
9) 3D Face Construction
Each row is rendered as a pseudo 3D object using:
A front rectangle
A shifted back edge using the X and Y depth settings
A side face when horizontal depth is visible
A top or bottom face depending on vertical depth direction
The script shades the side face darker and the top face brighter than the base color to create a depth illusion.
This is a visual projection technique, not a true 3D engine, but it produces a convincing 3D profile effect on the chart.
10) Rendering Order Logic
The script changes draw order depending on the sign of the Y depth:
If vertical depth is positive, rows are drawn from bottom to top
If vertical depth is negative, rows are drawn from top to bottom
This helps the 3D faces stack more cleanly and reduces visual overlap issues.
11) POC, VAH, and VAL Price Calculation
After the profile is complete:
The POC price is the midpoint of the POC bin
VAH is the highest top boundary among all Value Area bins
VAL is the lowest bottom boundary among all Value Area bins
These levels are then drawn as horizontal lines extending from the left side of the lookback window toward the right side label area.
12) Label Placement
The labels for POC, VAH, and VAL are placed slightly to the right of the profile. This keeps them readable and avoids overlap with the 3D bars themselves. Indicador
