OPEN-SOURCE SCRIPT
Wedge Pattern [Kodexius]

Wedge Pattern is a chart-overlay indicator designed to detect and manage classic Rising Wedge (bearish) and Falling Wedge (bullish) structures using strict, rules-based validation. The script focuses on producing clean, tradable wedge prints by building both boundaries from confirmed pivot swings, enforcing a mandatory “no closes outside the wedge” condition during formation, and requiring the wedge apex to be projected into the future to avoid premature or distorted patterns.
This implementation is built for practical execution charts. It continuously updates the active wedge boundaries in real time, clearly labels the pattern type, and reacts decisively when price confirms a valid breakout. When enabled, it also projects a measured-move target derived from the wedge geometry, so the trader can quickly evaluate reward potential without manual projection.
The detection logic is intentionally conservative. Rather than printing every possible converging structure, it aims to identify wedges that respect structural integrity: multiple touches on each boundary, controlled price action inside the converging range, and a valid convergence point (apex) ahead of the current bar. The result is a wedge tool that prioritizes quality, readability, and consistent behavior across symbols and timeframes.

🔹 Features
🔸 Rising and Falling Wedge Detection (Trendline Based)
The indicator detects two wedge types by constructing an upper trendline from pivot highs and a lower trendline from pivot lows:
Rising Wedge (Bearish): both lines slope upward, and the lower line rises faster than the upper line, creating a tightening upward channel that typically resolves with a downside break.

Falling Wedge (Bullish): both lines slope downward, and the upper line falls faster than the lower line, producing a tightening downward channel that typically resolves with an upside break.

This slope relationship is the core wedge classifier. It ensures the script is not just drawing random converging lines, but explicitly requires the characteristic “compression” geometry that defines wedges.
🔸 Pivot-Confirmed Structure with User Control
Wedges are built from confirmed pivots using:
Pivot Left and Pivot Right inputs to control how “strict” a pivot must be.
Min. Touches per Line to enforce multiple confirmations on each boundary.
Standard technical analysis commonly requires at least three touches to validate a trendline. This script supports that workflow by requiring a minimum number of pivot points before a wedge is eligible for drawing.
🔸 Mandatory Integrity Rule: No Closes Outside the Boundaries
A key quality filter is applied before a wedge can be accepted:
During formation, no candle close is allowed outside the upper or lower boundary.
If any close is detected above the upper line or below the lower line (with tick tolerance), the candidate wedge is rejected. This prevents patterns that already “broke” before they were formally detected and reduces false positives caused by messy price action.
🔸 Apex Validation to Avoid Distorted Prints
The wedge apex (the projected intersection point of the two trendlines) must be in the future. This avoids degenerate cases where lines intersect behind current price, which often indicates the structure is not a valid wedge or is already past its useful phase.
🔸 Live Updating Boundaries for Active Patterns
Once a wedge becomes active, its upper and lower lines are extended forward bar by bar. The script recalculates the boundary price at the current bar index using the stored slope, then updates the line endpoints so the wedge remains visually accurate as time advances.
🔸 Breakout Engine with Directional Confirmation
The script differentiates between:
Correct breakout: the wedge breaks in the expected direction.
Rising wedge breaks downward (close below the lower boundary).
Falling wedge breaks upward (close above the upper boundary).
When this happens, the wedge is marked as broken and labeled as BREAKOUT on the chart.
🔸 Invalidation and Failure Handling
If price violates the wedge in the wrong direction, or if the wedge collapses into an impossible structure (upper boundary falls below or equals the lower boundary), the wedge is flagged as FAILED. This keeps signals honest and prevents lingering drawings that no longer represent a valid pattern.
🔸 Optional Target Projection (Measured Move)
When Show Target Projection is enabled, the script plots a dashed target line and a target label after a valid breakout. The target is computed as a measured move using the wedge height, projected from the breakout boundary in the breakout direction. This provides an immediate objective reference for potential continuation.
🔸 Clean Object Management and Chart Readability
To maintain clarity, the script manages the “active” wedge per type:
If a new wedge is detected while an older one is still active and not broken or failed, the old drawings are removed and replaced with the newer valid pattern.
This prevents chart clutter and keeps the display focused on the most relevant wedge structures.
🔹 Calculations
1) Pivot Collection
The script uses pivot functions to confirm swing points:
Pine Script®
Each pivot is stored as a Coordinate containing:
index: the bar index where the pivot is confirmed
price: the pivot high or pivot low value
The arrays are capped (for example, last 20 pivots) to control memory and keep selection relevant.
2) Trendline Construction and Slope
A wedge candidate uses the earliest and latest required pivot points for each line. For each boundary, slope is computed as:
Pine Script®
With slope known, the trendline value at any bar index is:
Pine Script®
This approach allows the script to update wedge boundaries consistently without re-fitting lines on every bar.
3) Wedge Type Classification (Geometry Rules)
After both slopes are calculated, wedge type is determined by slope direction and relative steepness:
Rising wedge requires both slopes positive and lower slope greater than upper slope.
Falling wedge requires both slopes negative and upper slope more negative than lower slope (upper line falls faster).
In code logic:
Pine Script®
This enforces converging boundaries and avoids simple parallel channels.
4) Apex Projection (Trendline Intersection)
The apex is the projected intersection x-coordinate of the two trendlines:
Pine Script®
Validation requires:
apex_idx > bar_index (apex must be in the future)
This prevents late or structurally invalid wedges from being activated.
5) Mandatory “No Close Outside” Validation
Before activation, the script verifies the pattern has not been violated by candle closes:
Pine Script®
Interpretation:
For every bar from wedge start to current bar, the close must remain between the projected upper and lower boundary prices.
A tick tolerance (syminfo.mintick) is used to reduce micro false violations.
6) Live Update and Breakout Detection
Once active, lines are extended to the current bar and boundary prices are computed:
Pine Script®
Correct breakout conditions:
Rising wedge breakout: close below lower boundary.
Falling wedge breakout: close above upper boundary.
Pine Script®
Invalidation rules include:
wrong-direction break
boundary crossover (upper <= lower)
7) Target Projection (Measured Move)
If target display is enabled, the script calculates wedge height and projects a target from the breakout side:
Pine Script®
Interpretation:
m represents the wedge height near the start of the formation.
t is the target price, projected in the breakout direction.
Rising wedge: target below the lower boundary.
Falling wedge: target above the upper boundary.
A dashed target line and label are then placed forward in time for readability.
This implementation is built for practical execution charts. It continuously updates the active wedge boundaries in real time, clearly labels the pattern type, and reacts decisively when price confirms a valid breakout. When enabled, it also projects a measured-move target derived from the wedge geometry, so the trader can quickly evaluate reward potential without manual projection.
The detection logic is intentionally conservative. Rather than printing every possible converging structure, it aims to identify wedges that respect structural integrity: multiple touches on each boundary, controlled price action inside the converging range, and a valid convergence point (apex) ahead of the current bar. The result is a wedge tool that prioritizes quality, readability, and consistent behavior across symbols and timeframes.
🔹 Features
🔸 Rising and Falling Wedge Detection (Trendline Based)
The indicator detects two wedge types by constructing an upper trendline from pivot highs and a lower trendline from pivot lows:
Rising Wedge (Bearish): both lines slope upward, and the lower line rises faster than the upper line, creating a tightening upward channel that typically resolves with a downside break.
Falling Wedge (Bullish): both lines slope downward, and the upper line falls faster than the lower line, producing a tightening downward channel that typically resolves with an upside break.
This slope relationship is the core wedge classifier. It ensures the script is not just drawing random converging lines, but explicitly requires the characteristic “compression” geometry that defines wedges.
🔸 Pivot-Confirmed Structure with User Control
Wedges are built from confirmed pivots using:
Pivot Left and Pivot Right inputs to control how “strict” a pivot must be.
Min. Touches per Line to enforce multiple confirmations on each boundary.
Standard technical analysis commonly requires at least three touches to validate a trendline. This script supports that workflow by requiring a minimum number of pivot points before a wedge is eligible for drawing.
🔸 Mandatory Integrity Rule: No Closes Outside the Boundaries
A key quality filter is applied before a wedge can be accepted:
During formation, no candle close is allowed outside the upper or lower boundary.
If any close is detected above the upper line or below the lower line (with tick tolerance), the candidate wedge is rejected. This prevents patterns that already “broke” before they were formally detected and reduces false positives caused by messy price action.
🔸 Apex Validation to Avoid Distorted Prints
The wedge apex (the projected intersection point of the two trendlines) must be in the future. This avoids degenerate cases where lines intersect behind current price, which often indicates the structure is not a valid wedge or is already past its useful phase.
🔸 Live Updating Boundaries for Active Patterns
Once a wedge becomes active, its upper and lower lines are extended forward bar by bar. The script recalculates the boundary price at the current bar index using the stored slope, then updates the line endpoints so the wedge remains visually accurate as time advances.
🔸 Breakout Engine with Directional Confirmation
The script differentiates between:
Correct breakout: the wedge breaks in the expected direction.
Rising wedge breaks downward (close below the lower boundary).
Falling wedge breaks upward (close above the upper boundary).
When this happens, the wedge is marked as broken and labeled as BREAKOUT on the chart.
🔸 Invalidation and Failure Handling
If price violates the wedge in the wrong direction, or if the wedge collapses into an impossible structure (upper boundary falls below or equals the lower boundary), the wedge is flagged as FAILED. This keeps signals honest and prevents lingering drawings that no longer represent a valid pattern.
🔸 Optional Target Projection (Measured Move)
When Show Target Projection is enabled, the script plots a dashed target line and a target label after a valid breakout. The target is computed as a measured move using the wedge height, projected from the breakout boundary in the breakout direction. This provides an immediate objective reference for potential continuation.
🔸 Clean Object Management and Chart Readability
To maintain clarity, the script manages the “active” wedge per type:
If a new wedge is detected while an older one is still active and not broken or failed, the old drawings are removed and replaced with the newer valid pattern.
This prevents chart clutter and keeps the display focused on the most relevant wedge structures.
🔹 Calculations
1) Pivot Collection
The script uses pivot functions to confirm swing points:
float ph = ta.pivothigh(high, INPUT_PIVOT_LEFT, INPUT_PIVOT_RIGHT)
float pl = ta.pivotlow(low, INPUT_PIVOT_LEFT, INPUT_PIVOT_RIGHT)
if not na(ph)
pivot_highs.push(Coordinate.new(bar_index - INPUT_PIVOT_RIGHT, ph))
if not na(pl)
pivot_lows.push(Coordinate.new(bar_index - INPUT_PIVOT_RIGHT, pl))
Each pivot is stored as a Coordinate containing:
index: the bar index where the pivot is confirmed
price: the pivot high or pivot low value
The arrays are capped (for example, last 20 pivots) to control memory and keep selection relevant.
2) Trendline Construction and Slope
A wedge candidate uses the earliest and latest required pivot points for each line. For each boundary, slope is computed as:
method calc_slope(Trendline this) =>
(this.end.price - this.start.price) / (this.end.index - this.start.index)
With slope known, the trendline value at any bar index is:
method get_price_at(Trendline this, int bar_idx) =>
this.start.price + this.slope * (bar_idx - this.start.index)
This approach allows the script to update wedge boundaries consistently without re-fitting lines on every bar.
3) Wedge Type Classification (Geometry Rules)
After both slopes are calculated, wedge type is determined by slope direction and relative steepness:
Rising wedge requires both slopes positive and lower slope greater than upper slope.
Falling wedge requires both slopes negative and upper slope more negative than lower slope (upper line falls faster).
In code logic:
if tl_up.slope > 0 and tl_lo.slope > 0 and tl_lo.slope > tl_up.slope
w_type := 1 // Rising
if tl_up.slope < 0 and tl_lo.slope < 0 and tl_up.slope < tl_lo.slope
w_type := 2 // Falling
This enforces converging boundaries and avoids simple parallel channels.
4) Apex Projection (Trendline Intersection)
The apex is the projected intersection x-coordinate of the two trendlines:
method get_apex_index(Wedge this) =>
float m1 = this.upper.slope
float m2 = this.lower.slope
float y1 = this.upper.start.price
float y2 = this.lower.start.price
int x1 = this.upper.start.index
int x2 = this.lower.start.index
float apex_x = (y2 - y1 + m1 * x1 - m2 * x2) / (m1 - m2)
math.round(apex_x)
Validation requires:
apex_idx > bar_index (apex must be in the future)
This prevents late or structurally invalid wedges from being activated.
5) Mandatory “No Close Outside” Validation
Before activation, the script verifies the pattern has not been violated by candle closes:
method check_violation(Wedge this, int from_idx, int to_idx) =>
bool violated = false
for i = from_idx to to_idx
float up_p = this.upper.get_price_at(i)
float lo_p = this.lower.get_price_at(i)
float c_p = close[bar_index - i]
if c_p > up_p + syminfo.mintick or c_p < lo_p - syminfo.mintick
violated := true
break
violated
Interpretation:
For every bar from wedge start to current bar, the close must remain between the projected upper and lower boundary prices.
A tick tolerance (syminfo.mintick) is used to reduce micro false violations.
6) Live Update and Breakout Detection
Once active, lines are extended to the current bar and boundary prices are computed:
float u_p = w.upper.get_price_at(bar_index)
float l_p = w.lower.get_price_at(bar_index)
bool b_up = close > u_p
bool b_dn = close < l_p
Correct breakout conditions:
Rising wedge breakout: close below lower boundary.
Falling wedge breakout: close above upper boundary.
if (w.is_rising and b_dn) or (not w.is_rising and b_up)
w.is_broken := true
Invalidation rules include:
wrong-direction break
boundary crossover (upper <= lower)
7) Target Projection (Measured Move)
If target display is enabled, the script calculates wedge height and projects a target from the breakout side:
float m = math.abs(w.upper.start.price - w.lower.get_price_at(w.upper.start.index))
float t = w.is_rising ? l_p - m : u_p + m
Interpretation:
m represents the wedge height near the start of the formation.
t is the target price, projected in the breakout direction.
Rising wedge: target below the lower boundary.
Falling wedge: target above the upper boundary.
A dashed target line and label are then placed forward in time for readability.
Script open-source
Nello spirito di TradingView, l'autore di questo script lo ha reso open source, in modo che i trader possano esaminarne e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricordiamo che la ripubblicazione del codice è soggetta al nostro Regolamento.
All content provided by Kodexius is for informational & educational purposes only. Past performance does not guarantee future results.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.
Script open-source
Nello spirito di TradingView, l'autore di questo script lo ha reso open source, in modo che i trader possano esaminarne e verificarne la funzionalità. Complimenti all'autore! Sebbene sia possibile utilizzarlo gratuitamente, ricordiamo che la ripubblicazione del codice è soggetta al nostro Regolamento.
All content provided by Kodexius is for informational & educational purposes only. Past performance does not guarantee future results.
Declinazione di responsabilità
Le informazioni e le pubblicazioni non sono intese come, e non costituiscono, consulenza o raccomandazioni finanziarie, di investimento, di trading o di altro tipo fornite o approvate da TradingView. Per ulteriori informazioni, consultare i Termini di utilizzo.