OPEN-SOURCE SCRIPT
Actualizado Swap Engine - Pair Rotation (Z-Score) [AGPro Series]

Swap Engine - Pair Rotation (Z-Score) [AGPro Series]
🔷 OVERVIEW
Swap Engine - Pair Rotation (Z-Score) transforms the log-ratio between two correlated crypto assets into a disciplined tier ladder decision framework. Rather than signalling single-asset direction, the engine measures how stretched one pair has become relative to its rolling mean and proposes rotation between the two assets when the spread reaches statistically meaningful extremes. Every decision is evaluated on confirmed Engine TF bar close, keeping suggestions non-repainting under the configured execution model.
🟣 UNIQUE EDGE
Unlike single-symbol mean-reversion or trend indicators, this engine treats the ratio itself as the tradable variable and pairs it with a full operational stack: a tiered exposure ladder (T0 to T3), an Integrity Gate that blocks entries when the pair relationship deteriorates, a Trend Regime filter that respects persistent one-sided moves, and a confirm-first execution model that converts raw signals into auditable decisions. A dedicated Signal Quality score (Q 0-100) and Integrity Score (IN 0-100) make every suggestion inspectable, not a black box.
🟢 METHODOLOGY
The engine fetches the closing price of Pair A and Pair B on the chosen Engine TF, computes the log-ratio L = ln(A / B), then derives a rolling z-score using user-defined lookback length. Entry thresholds (Z1, Z2, Z3) define the three tiers of exposure; exit thresholds (hysteresis) define when each tier is scaled back. A cost filter requires the expected mean-reversion edge to exceed a configurable multiple of estimated roundtrip cost before any entry is allowed. The Integrity Gate continuously validates rolling return correlation, ratio drift, and spread-volatility expansion, halting new entries when the pair relationship degrades.
🟡 SIGNALS & ALERTS
Each signal renders as a clearly tagged label on chart showing the action type (ENTRY / EXIT), source tier, target tier, direction (A->B or B->A), z-score snapshot, delta %, and Reason Code. Alerts are provided for: entry and exit events per direction, pending lifecycle (created, confirmed, skipped, expired), trend regime activation edges, duplicate suppression, and configuration warnings. All alerts fire on Engine TF bar close to remain consistent with the visible suggestions.
⚙️ KEY INPUTS
Pair A / Pair B: the two assets to rotate between (same quote currency recommended).
Engine TF: timeframe used for all ratio, z-score, and decision logic (240 / 4H default).
Lookback: bars used for rolling mean and standard deviation.
Entry Z1/Z2/Z3, Exit Z1/Z2/Z3: tiered thresholds for scaling in and out.
Tier Sizing (T1 / T2 / T3 %): rotation size per tier as a percentage of the active pool.
Trade Profile: preset gate behavior (Conservative, Balanced, Aggressive, Volatile Alt, High-Cost, Custom).
Integrity Gate: correlation, drift, and volatility expansion filter with configurable minimum score.
Execution Model: ASSUME (auto-advance), CONFIRM (pending + manual commit), or SIGNAL_ONLY (display only).
🔵 HOW TO USE
Start on the default BTCUSDT vs ETHUSDT pair on 4H Engine TF with the Balanced profile. Keep the chart timeframe equal to or lower than the Engine TF (the script warns otherwise). Watch the status panel for the current tier, direction, confidence strip (Q / IN / PH), and next action preview. In CONFIRM mode, a PENDING card appears when a signal fires; increase CONFIRM +1 to commit the rotation state, or SKIP +1 to discard. Use the Trade Profile dropdown to tighten or loosen effective gates without changing your base inputs.
🟠 LIMITATIONS & TRANSPARENCY
This is an indicator, not a strategy; no orders are placed and no backtest statistics are produced. Signals reflect statistical extremes in the pair's log-ratio and do not guarantee mean reversion. Performance depends heavily on pair selection - assets with persistent trends, broken correlation, or structural regime changes can cause extended adverse periods. The Integrity Gate mitigates but does not eliminate this risk. Costs, slippage, tax, and execution details are the user's responsibility; the Min Edge x filter is an estimate, not a realized-cost guarantee. Always validate on your own pair, timeframe, and account conditions before relying on any suggestion.
🔴 RISK DISCLOSURE
Trading and rotating between crypto assets involves substantial risk, including loss of capital. Past or simulated behavior of the ratio does not guarantee future results. This tool is shared for educational and analytical purposes only and does not constitute financial, investment, or trading advice. Users are solely responsible for their own decisions and should consult a qualified professional before committing capital.
🔷 OVERVIEW
Swap Engine - Pair Rotation (Z-Score) transforms the log-ratio between two correlated crypto assets into a disciplined tier ladder decision framework. Rather than signalling single-asset direction, the engine measures how stretched one pair has become relative to its rolling mean and proposes rotation between the two assets when the spread reaches statistically meaningful extremes. Every decision is evaluated on confirmed Engine TF bar close, keeping suggestions non-repainting under the configured execution model.
🟣 UNIQUE EDGE
Unlike single-symbol mean-reversion or trend indicators, this engine treats the ratio itself as the tradable variable and pairs it with a full operational stack: a tiered exposure ladder (T0 to T3), an Integrity Gate that blocks entries when the pair relationship deteriorates, a Trend Regime filter that respects persistent one-sided moves, and a confirm-first execution model that converts raw signals into auditable decisions. A dedicated Signal Quality score (Q 0-100) and Integrity Score (IN 0-100) make every suggestion inspectable, not a black box.
🟢 METHODOLOGY
The engine fetches the closing price of Pair A and Pair B on the chosen Engine TF, computes the log-ratio L = ln(A / B), then derives a rolling z-score using user-defined lookback length. Entry thresholds (Z1, Z2, Z3) define the three tiers of exposure; exit thresholds (hysteresis) define when each tier is scaled back. A cost filter requires the expected mean-reversion edge to exceed a configurable multiple of estimated roundtrip cost before any entry is allowed. The Integrity Gate continuously validates rolling return correlation, ratio drift, and spread-volatility expansion, halting new entries when the pair relationship degrades.
🟡 SIGNALS & ALERTS
Each signal renders as a clearly tagged label on chart showing the action type (ENTRY / EXIT), source tier, target tier, direction (A->B or B->A), z-score snapshot, delta %, and Reason Code. Alerts are provided for: entry and exit events per direction, pending lifecycle (created, confirmed, skipped, expired), trend regime activation edges, duplicate suppression, and configuration warnings. All alerts fire on Engine TF bar close to remain consistent with the visible suggestions.
⚙️ KEY INPUTS
Pair A / Pair B: the two assets to rotate between (same quote currency recommended).
Engine TF: timeframe used for all ratio, z-score, and decision logic (240 / 4H default).
Lookback: bars used for rolling mean and standard deviation.
Entry Z1/Z2/Z3, Exit Z1/Z2/Z3: tiered thresholds for scaling in and out.
Tier Sizing (T1 / T2 / T3 %): rotation size per tier as a percentage of the active pool.
Trade Profile: preset gate behavior (Conservative, Balanced, Aggressive, Volatile Alt, High-Cost, Custom).
Integrity Gate: correlation, drift, and volatility expansion filter with configurable minimum score.
Execution Model: ASSUME (auto-advance), CONFIRM (pending + manual commit), or SIGNAL_ONLY (display only).
🔵 HOW TO USE
Start on the default BTCUSDT vs ETHUSDT pair on 4H Engine TF with the Balanced profile. Keep the chart timeframe equal to or lower than the Engine TF (the script warns otherwise). Watch the status panel for the current tier, direction, confidence strip (Q / IN / PH), and next action preview. In CONFIRM mode, a PENDING card appears when a signal fires; increase CONFIRM +1 to commit the rotation state, or SKIP +1 to discard. Use the Trade Profile dropdown to tighten or loosen effective gates without changing your base inputs.
🟠 LIMITATIONS & TRANSPARENCY
This is an indicator, not a strategy; no orders are placed and no backtest statistics are produced. Signals reflect statistical extremes in the pair's log-ratio and do not guarantee mean reversion. Performance depends heavily on pair selection - assets with persistent trends, broken correlation, or structural regime changes can cause extended adverse periods. The Integrity Gate mitigates but does not eliminate this risk. Costs, slippage, tax, and execution details are the user's responsibility; the Min Edge x filter is an estimate, not a realized-cost guarantee. Always validate on your own pair, timeframe, and account conditions before relying on any suggestion.
🔴 RISK DISCLOSURE
Trading and rotating between crypto assets involves substantial risk, including loss of capital. Past or simulated behavior of the ratio does not guarantee future results. This tool is shared for educational and analytical purposes only and does not constitute financial, investment, or trading advice. Users are solely responsible for their own decisions and should consult a qualified professional before committing capital.
Notas de prensa
UPDATE NOTES - V1.1This update focuses on readability, visual structure, chart clarity, and usability.
The core purpose of the script remains unchanged.
This release improves how the existing pair-rotation z-score logic is presented, organized, and interpreted on the chart.
This script continues to function as an analytical and visualization tool.
It does not attempt to predict price direction or provide guaranteed outcomes.
------------------------
What Changed
------------------------
* Refined the publication identity
The script title now follows the updated AGPro Series naming standard while the panel title keeps the AG Pro brand format.
* Rebuilt the visual output layer
The chart now uses cleaner stretch, deep stretch, reversion, and integrity-block labels instead of a dense diagnostic label system.
* Added live right-edge state tags
The latest pair state, z-score, quality score, and integrity score now remain visible near the right edge of the chart.
* Simplified the pair integrity model
The integrity score now blends rolling correlation, mean drift, and spread-volatility expansion into a clearer 0-100 framework.
* Reworked the status panel
The panel now uses the standard single merged blue header row with configurable position, theme, and font size.
* Improved label density control
Minimal, Balanced, and Detailed modes now control how much rotation context appears on the chart.
* Reduced default label frequency after visual QA
Balanced mode is now more selective, mean-reversion labels are disabled by default, and spacing filters prevent repeated labels from stacking in the same chart area.
* Added compact live tag mode
The default right-edge display now uses a single compact state tag instead of three stacked tags, preventing overlap across 1H, 4H, and 1D chart scales.
* Added a subtle rotation trail
The chart now keeps visible pair-rotation context even when historical labels are intentionally sparse.
* Added small state markers
Stretch, deep stretch, mean-zone and integrity-block transitions now receive tiny non-text markers so the chart does not look empty on quiet timeframes.
------------------------
Visual Improvements
------------------------
* Improved chart readability by separating historical rotation labels, live right-edge tags, state tinting, and panel data.
* Reduced visual clutter by replacing the old stacked HUD system with a cleaner panel and compact live labels.
* Refined visual hierarchy so stretch, deep stretch, reversion, and blocked states are easier to distinguish.
* Kept on-chart labels in readable professional English while preserving lowercase hyphen-style terms only for the suggested tag list.
* Adjusted label placement so labels sit above or below candles instead of being buried inside price bars.
* Disabled state tint by default to prevent repeated background stripes from dominating publication screenshots.
* Increased historical label offset from candles so remaining labels have more breathing room on wide-range bars.
* Added visual context without increasing label clutter by using a low-noise trail and tiny state markers.
------------------------
Interface & Usability
------------------------
* Added a Show Panel toggle that remains enabled by default.
* Added configurable panel position, panel theme, panel font size, and label font size.
* Reorganized the panel into Pair, Action, Z / Ratio, Integrity, Quality, and Next.
* Improved tooltips with clearer professional English descriptions.
* Preserved alert conditions for stretch, deep stretch, reversion, and integrity-block events.
------------------------
Behavior Notes
------------------------
This update does not change the core analytical purpose of the script.
The script continues to use a pair log-ratio, z-score normalization, and integrity gating to evaluate relative-value rotation context.
The goal is to improve clarity and usability, not to introduce predictive behavior.
Users should interpret outputs the same way as before, but with a cleaner visual structure and more readable state hierarchy.
------------------------
Limitations Reminder
------------------------
The script remains a rule-based analytical tool.
Pair behavior can change when correlation weakens, liquidity shifts, quote currencies differ, volatility expands, or market regimes trend strongly.
Outputs should always be interpreted within broader market context.
------------------------
Risk Reminder
------------------------
This script is for educational and analytical purposes only.
It does not provide financial advice or guaranteed trading outcomes.
Users remain responsible for their own decisions.
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.
⚡ Precision Pine tools for crypto & FX traders
📊 ICT • Smart Money • Market Structure • Liquidity
🧠 Rules-based decision tools. No hype. No guesswork
⭐ Public AGPro Series + advanced invite-only tools
💬 t.me/agprolabs
📊 ICT • Smart Money • Market Structure • Liquidity
🧠 Rules-based decision tools. No hype. No guesswork
⭐ Public AGPro Series + advanced invite-only tools
💬 t.me/agprolabs
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.
⚡ Precision Pine tools for crypto & FX traders
📊 ICT • Smart Money • Market Structure • Liquidity
🧠 Rules-based decision tools. No hype. No guesswork
⭐ Public AGPro Series + advanced invite-only tools
💬 t.me/agprolabs
📊 ICT • Smart Money • Market Structure • Liquidity
🧠 Rules-based decision tools. No hype. No guesswork
⭐ Public AGPro Series + advanced invite-only tools
💬 t.me/agprolabs
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.