OPEN-SOURCE SCRIPT

Anchored Trend Channels [MQLSoftware]

11 296
Anchored Trend Channels is a structural overlay that maps each phase of price action between confirmed swing points as its own parallel trend channel. Instead of fitting one curve or band to all of price history, it breaks the chart into discrete pivot-to-pivot segments and renders each one as a self-contained anchored channel with its own slope, width, and angle. The active channel projects forward with a dashed extension so future support and resistance levels are visible at a glance.

A second, finer regression channel (Micro) lives inside the currently forming Macro segment to show local momentum and its relationship to the broader trend. A compact right-side panel reads off the resulting structure, the active segment angle, the segment chain, multi-timeframe context, and three optional structural events.

This is a visual analytical tool intended for chart reading and structure mapping. It does not execute trades and does not provide financial advice.

Key Features

  • Pivot-anchored Macro channels that segment price action into discrete trend phases (one channel per phase, anchored on confirmed swing pivots)
  • Active segment with a forward-extending dashed projection of about 20 bars, showing where the channel boundaries would lie if the trend continues
  • Adaptive Micro regression channel inside the active segment, with R-squared fit quality readout
  • Trend Bias scoring weighted by segment length and angle, combined with net price move across the analysis window
  • Acceleration metric showing how much the Micro angle deviates from the Macro angle (faster, slower, or flat)
  • Right-side panel with Macro angle, segment chain visualization, Micro R-squared, MTF context, and three structural signal states
  • Non-Repaint Mode toggle for users who prefer closed-bar-only updates on the active segment
  • Three optional structural event markers (Segment Break, Macro Pullback, Micro Continuation) with a configurable cooldown to avoid clustering


Core Concept

Most channel and trend indicators on TradingView take one of two approaches. They either fit a single continuous curve to all of price (linear regression channels, ATR-trailing bands, smoothed moving averages with deviation bands) or they detect individual trendlines through two pivots and project them indefinitely. Both approaches have known limitations. A single continuous channel cannot describe a market that has clearly changed phase. Two-pivot trendlines drift, get broken, and need constant manual maintenance.

This indicator builds on a third approach: piecewise channels anchored on confirmed pivots. Each finished segment is a closed, immutable object that describes one phase of price action between two opposite swing points. The chain of segments left behind is a structural history of how the trend developed, where it accelerated, where it reversed.

The indicator adds three specific algorithmic elements on top of that base.

1. Quality Filters at Segment Birth. Before a new segment is committed, two filters check that the pivot move is structurally meaningful. The pivot-to-pivot price distance must exceed a configurable ATR multiple (default 2.5x), and the bar count must exceed a minimum length (default 8 bars). Pivots that fail either check are skipped, so the visible chain reflects real phase changes, not noise.

2. Pivot-Anchored Geometry with Max-Deviation Width. Each segment's basis line is the straight line between its two anchor pivots. The channel half-width is the maximum deviation of any bar inside the segment from that basis line, scaled by a user multiplier and floored by an ATR-based minimum. This produces channels that visibly contain the price action that built them, rather than mathematical fits that ignore visible swings.

3. Trend Bias from Weighted Segments Plus Net Move. Most chain-based indicators classify direction by counting up-segments versus down-segments. That gives equal weight to a 30-bar trending move and a 5-bar choppy retracement. This indicator weights each segment by the product of its bar count and its absolute angle, then combines that with the net price move across the analysis window measured in ATR units. The result is a Trend Bias label (Strong Bull, Bullish, Mixed, Bearish, Strong Bear) that reflects which side has accumulated the actual structural progress, not just the count of segments.

Anatomy of the Display

Historical segments are drawn as parallel green or coral channels between confirmed past pivots. They are immutable once committed and form a left-to-right chain that visually traces the structure of the trend.

The active segment is the right-most channel, drawn in bright color with a wider glow layer. It anchors on the most recent confirmed pivot and extends to the current bar. The dashed projection continues the channel about 20 bars to the right at the current slope, so users see where price would touch the upper and lower boundaries if the segment kept its angle.

The Micro channel is a 20-bar linear regression with standard-deviation bands, rendered in cyan or pink depending on its own direction. It only appears when the regression's R-squared fit quality clears a user threshold, so it auto-hides when local price action is too noisy for a meaningful regression.

H and L pivot markers sit at the pivot anchor points. H labels mark confirmed high pivots, L labels mark confirmed low pivots.

The right-side panel groups the data into Trend Bias (top), Macro Active Segment (angle, direction, bars in segment, segment chain), Micro Channel (angle, direction, R-squared, acceleration), Signals (three states), and MTF (current angle of two higher timeframes).

Acceleration in the panel is the Micro angle minus the Macro angle. A positive number means the local momentum is steeper than the surrounding trend phase (often early-stage continuation). A negative number means the local momentum is flattening relative to the surrounding trend phase (often late-stage or stalling).

Optional Structural Event Markers

Three structural events can be displayed as on-chart markers. These describe what is happening to the channel geometry. They are not trade entries.

  • Segment Break (BRK). Price closes beyond the opposite boundary of the active segment. In an active uptrend channel, this is a close below the lower boundary. In a downtrend channel, a close above the upper boundary. This marks a violation of the active phase structure.
  • Macro Pullback (PB). Price closes within 0.2 ATR of the band on the same side as the trend direction. In an uptrend, price closes near the lower boundary. In a downtrend, price closes near the upper boundary. This marks a touch back to the channel boundary in the direction of the active phase.
  • Micro Continuation (CONT). The Micro channel breaks its own boundary in the same direction as the Macro segment, while the segment is still in its early stage (3 to 25 bars in). This marks a moment when local momentum aligns with the broader trend phase early in its life.


All three event types are gated by a configurable cooldown (default 15 bars) to prevent clustering. Each event is computed on closed bars only.

Multi-Timeframe Panel Row

The MTF row at the bottom of the panel shows the active segment angle on two higher timeframes. The two HTFs are selected automatically from the standard timeframe ladder based on the current chart timeframe. For example, on a 15m chart the panel reads 4H and 1D. On a 1H chart it reads 1D and 1W. HTF values are read with `lookahead=barmerge.lookahead_off` and a one-bar offset, which is the standard non-repainting pattern for higher-timeframe reads.

Notes on Repainting

  • Historical segments do not repaint. They are built from confirmed pivots (`ta.pivothigh` and `ta.pivotlow` with a right-bars parameter). A pivot is only confirmed several bars after it forms, so historical segments remain anchored in place forever once committed.
  • The active segment updates as new bars print. With Non-Repaint Mode ON (default), it recalculates only on closed bars, so its boundaries remain stable intra-bar. With Non-Repaint Mode OFF, it updates on every tick for users who prefer maximum responsiveness and accept the visual jitter.
  • Pivot detection has an inherent delay equal to the pivot lookback (default 30 bars on Very Long sensitivity). A pivot becomes visible after that many bars have closed past it. This is a property of all pivot-based indicators, not a flaw specific to this script.
  • All signal markers and alerts are gated by `barstate.isconfirmed`. They fire exactly once per closed bar and never intra-bar.
  • MTF panel data uses `lookahead=barmerge.lookahead_off` with a one-bar offset on every series, which is the canonical non-repainting pattern for higher-timeframe context.


Typical Analysis Workflow

A common analytical workflow may include:

  1. Reading the Trend Bias label and color in the panel header to anchor an overall directional view
  2. Checking the segment chain in the panel against the visible historical channels on the chart to confirm structure is consistent
  3. Watching the active segment's dashed projection to identify forward levels where the channel boundaries are heading
  4. Comparing the Micro channel direction and angle against the Macro segment direction and angle (Acceleration row) to read whether local momentum aligns with the broader phase
  5. Cross-checking the MTF row to see whether higher timeframes are in the same structural direction or in conflict
  6. Treating Segment Break, Macro Pullback, and Micro Continuation markers as structural events for context, then combining that read with other forms of analysis and risk management


Configuration

Pivot Sensitivity - Short (5), Medium (10), Long (18), or Very Long (30). Lower values produce more segments of shorter average length. Higher values produce fewer, longer-lived segments. Very Long is the default and produces the cleanest premium look.

Min Segment Size (x ATR) - Minimum price distance between consecutive pivots, measured in ATR. Pivots below this threshold are skipped. Higher values produce fewer, more significant segments.

Min Segment Length (bars) - Minimum bar count between consecutive pivots. Short segments are skipped.

Channel Width Multiplier - Multiplier on the max-deviation width. 1.0 means the channel just contains the price action that built it. 1.2 to 1.5 adds visible breathing room.

Min Band Width (x ATR) - Floor on the channel half-width. Prevents razor-thin channels on short segments where deviation is small.

Max Segments Stored - FIFO cap on historical segments (default 15). Older segments are removed as new ones form.

Regression Length (Micro) - Number of bars in the Micro regression window (default 20).

Std Dev Multiplier (Micro) - Width of the Micro band in standard deviations.

Min R-squared to Show (Micro) - Hides the Micro channel when regression fit quality is below this threshold.

Signal Cooldown (bars) - Minimum bars between consecutive same-type signal markers.

Non-Repaint Mode - When ON (default), the active channel uses closed-bar data only. When OFF, it updates live with each tick.

Show toggles - Macro segments, Micro channel, panel, status badge, endpoint labels, pivot markers, signal markers, basis lines, channel fills, MTF row.

Markets and Timeframes

The indicator can be applied across multiple markets and timeframes:

  • Forex
  • Stocks and Indices
  • Commodities
  • Cryptocurrencies


Because slope is ATR-normalized and channel width is ATR-floored, the visual behavior remains consistent across instruments and timeframes. The Pivot Sensitivity preset can be tuned per chart for the cleanest read on a given symbol and timeframe.

Alerts

Three alert conditions are available:

  • Segment Direction Changed - fires when the active segment direction flips between uptrend and downtrend
  • Segment Break - fires when price closes beyond the opposite boundary of the active segment
  • Micro Continuation - fires when the Micro channel breaks its own boundary in the same direction as the active Macro segment, in the early portion of the segment


All alerts evaluate on confirmed bars to avoid intra-bar oscillation.

إخلاء المسؤولية

لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.