OPEN-SOURCE SCRIPT
Automatic Trendline [Metrify]

Metrify Automatic Trendlines is an auto-drawing support/resistance channel built around pivot clustering + scoring, not “connect two perfect points”. The script continuously collects swing pivots (high/low) over a configurable lookback window, then searches for the best single support line and the best single resistance line that behave like a human-drawn trendline: multiple interactions, controlled slope, limited break-throughs, and (most importantly) still relevant to the current price. (configurable in "Max Relevance Distance" input)
The fundamental problem with algorithmic trendlines is subjectivity. To solve this mathematically, we treat trendlines as a statistical regression problem with specific constraints. We do not use linear regression on all candles, instead, we use a brute-force iterative approach on specific "Pivot Points."
The logic operates on a simple premise: Generate every possible line between past swing points, validate them against price history, score them based on fit, and render only the winner.
The Calculation Engine (f_find_best_line)
This function contains the primary computational load. It performs a nested loop operation:
For every pair of pivots (P1,P2), we calculate the slope (m) and the y-intercept concept. This gives us a tentative trendline equation:
y=mx+c
The Scoring Matrix
We assign a score to each candidate line based on weighted heuristics:
The line with the highest localBest score is returned as the dominant trendline.
What you can use it for?
This is a structure visualizer that tries to keep a clean, current S/R channel on screen with volatility-aware rules. It’s not a signal generator, it doesn’t predict breakouts, and it won’t always draw something, if the market is messy and no line survives the filters, it will show none instead of hallucinating geometry. If you need more lines (multiple concurrent channels), that’s a different design tradeoff (and usually becomes clutter + false confidence fast).
The fundamental problem with algorithmic trendlines is subjectivity. To solve this mathematically, we treat trendlines as a statistical regression problem with specific constraints. We do not use linear regression on all candles, instead, we use a brute-force iterative approach on specific "Pivot Points."
The logic operates on a simple premise: Generate every possible line between past swing points, validate them against price history, score them based on fit, and render only the winner.
The Calculation Engine (f_find_best_line)
This function contains the primary computational load. It performs a nested loop operation:
- Outer Loop (newer): Iterates through recent pivots.
- Inner Loop (older): Iterates through older pivots to form a candidate line segment.
For every pair of pivots (P1,P2), we calculate the slope (m) and the y-intercept concept. This gives us a tentative trendline equation:
y=mx+c
The Scoring Matrix
We assign a score to each candidate line based on weighted heuristics:
- Touch Count (touches * 2.8): The primary driver. More touches = higher statistical significance.
- Recency (recency * 1.2): Lines originating closer to the current price action are weighted higher.
- Tightness (avgErr): We calculate the average distance of all touches from the line. A "tighter" fit (lower error) increases the score.
Penalties: - violations * 2.2: False breaks heavily penalize the score.
- barBreakRatio * 2.0: If the line cuts through candle bodies (even if pivots are fine).
The line with the highest localBest score is returned as the dominant trendline.
What you can use it for?
This is a structure visualizer that tries to keep a clean, current S/R channel on screen with volatility-aware rules. It’s not a signal generator, it doesn’t predict breakouts, and it won’t always draw something, if the market is messy and no line survives the filters, it will show none instead of hallucinating geometry. If you need more lines (multiple concurrent channels), that’s a different design tradeoff (and usually becomes clutter + false confidence fast).
Script de código abierto
Fiel al espíritu de TradingView, el creador de este script lo ha convertido en código abierto, para que los traders puedan revisar y verificar su funcionalidad. ¡Enhorabuena al autor! Aunque puede utilizarlo de forma gratuita, recuerde que la republicación del código está sujeta a nuestras Normas internas.
Exención de responsabilidad
La información y las publicaciones no constituyen, ni deben considerarse como asesoramiento o recomendaciones financieras, de inversión, de trading o de otro tipo proporcionadas o respaldadas por TradingView. Más información en Condiciones de uso.
Script de código abierto
Fiel al espíritu de TradingView, el creador de este script lo ha convertido en código abierto, para que los traders puedan revisar y verificar su funcionalidad. ¡Enhorabuena al autor! Aunque puede utilizarlo de forma gratuita, recuerde que la republicación del código está sujeta a nuestras Normas internas.
Exención de responsabilidad
La información y las publicaciones no constituyen, ni deben considerarse como asesoramiento o recomendaciones financieras, de inversión, de trading o de otro tipo proporcionadas o respaldadas por TradingView. Más información en Condiciones de uso.