OPEN-SOURCE SCRIPT
Sector Rotation Z-Score Strategy

Sector Rotation Z-Score Strategy
This strategy trades one symbol based on the relative strength between two others. It takes the log ratio of Ticker 1 to Ticker 2, then converts that ratio into a z-score over a rolling lookback (default 63 bars). The z-score is plotted as a histogram: positive means Ticker 1 is outperforming its recent average relationship with Ticker 2, negative means it's lagging.
The idea is straightforward — buy when the pair is rotating back in favor of Ticker 1, exit when it rotates away.
Entry and exit logic
A long is triggered when the z-score crosses above the negative buffer level, and closed when it crosses below the positive buffer level. Both buffers are adjustable in z-score units, so you can enter earlier or later than the zero line rather than being locked to a single crossover point. An optional short side triggers when the z-score crosses back above the extreme rotation level.
The z-score can be used raw or smoothed with a short moving average to cut down on whipsaw crosses.
Filters
ADX gate — entries require ADX above a minimum threshold, so the strategy stays out when the underlying isn't trending. There's also an optional exit when ADX drops below a lower threshold, which closes trades that have gone flat.
PPP (Price % of Pivots) gate — this measures where price sits relative to the most recent pivot high and pivot low, producing a simple bullish or bearish bias. Entries can require that bias to agree with the trade direction. Because the pivot bias and the z-score cross rarely line up on the exact same bar, there's a match window: a cross stays armed for a set number of bars, and the bias is also checked backward over that same window. Exits can optionally close on a bias flip, or require confirmation — meaning the z-score cross is latched and the trade only closes once PPP agrees.
Percent TP/SL — optional fixed take profit and stop loss as a percentage of entry price.
Date range filter — restricts the backtest window and closes any open position on exit from the range.
Symbol handling
Either leg accepts a numeric value instead of a ticker (enter "1" to compare a symbol against a constant). Unresolvable or frozen data feeds fall back to a constant rather than breaking the script, with a configurable detection window.
Example shown as BTC vs RSP to compare crypto relative strength against the equal-weight S&P
Alerts
Entry, exit, take profit, and stop loss all fire formatted alert messages that include the symbol, price, and which leg is strengthening or weakening. Messages are structured for webhook use (Discord and similar). Standard alertcondition entries are also available in the alert dialog.
This strategy trades one symbol based on the relative strength between two others. It takes the log ratio of Ticker 1 to Ticker 2, then converts that ratio into a z-score over a rolling lookback (default 63 bars). The z-score is plotted as a histogram: positive means Ticker 1 is outperforming its recent average relationship with Ticker 2, negative means it's lagging.
The idea is straightforward — buy when the pair is rotating back in favor of Ticker 1, exit when it rotates away.
Entry and exit logic
A long is triggered when the z-score crosses above the negative buffer level, and closed when it crosses below the positive buffer level. Both buffers are adjustable in z-score units, so you can enter earlier or later than the zero line rather than being locked to a single crossover point. An optional short side triggers when the z-score crosses back above the extreme rotation level.
The z-score can be used raw or smoothed with a short moving average to cut down on whipsaw crosses.
Filters
ADX gate — entries require ADX above a minimum threshold, so the strategy stays out when the underlying isn't trending. There's also an optional exit when ADX drops below a lower threshold, which closes trades that have gone flat.
PPP (Price % of Pivots) gate — this measures where price sits relative to the most recent pivot high and pivot low, producing a simple bullish or bearish bias. Entries can require that bias to agree with the trade direction. Because the pivot bias and the z-score cross rarely line up on the exact same bar, there's a match window: a cross stays armed for a set number of bars, and the bias is also checked backward over that same window. Exits can optionally close on a bias flip, or require confirmation — meaning the z-score cross is latched and the trade only closes once PPP agrees.
Percent TP/SL — optional fixed take profit and stop loss as a percentage of entry price.
Date range filter — restricts the backtest window and closes any open position on exit from the range.
Symbol handling
Either leg accepts a numeric value instead of a ticker (enter "1" to compare a symbol against a constant). Unresolvable or frozen data feeds fall back to a constant rather than breaking the script, with a configurable detection window.
Example shown as BTC vs RSP to compare crypto relative strength against the equal-weight S&P
Alerts
Entry, exit, take profit, and stop loss all fire formatted alert messages that include the symbol, price, and which leg is strengthening or weakening. Messages are structured for webhook use (Discord and similar). Standard alertcondition entries are also available in the alert dialog.
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 cualquier 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 u otro tipo, proporcionadas o respaldadas por TradingView. Obtenga 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 cualquier 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 u otro tipo, proporcionadas o respaldadas por TradingView. Obtenga más información en Condiciones de uso.