OPEN-SOURCE SCRIPT
Zaktualizowano 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.
Informacje o Wersji
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.
Informacje o Wersji
UPDATE NOTES - V1.2This update focuses on panel control, visual readability, chart-label clarity, and pair-rotation interpretation.
The core purpose of the script remains unchanged.
This release improves how the existing z-score pair-rotation 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
------------------------
- Added a complete panel location control.
The panel now supports top, middle, bottom, left, center, and right anchor positions for more flexible publication layouts.
- Improved panel rebuild behavior.
Panel position, theme, and visibility changes are now handled cleanly so the panel keeps its intended layout and border styling.
- Refined the panel information flow.
The panel now reads from Workflow to Pair, Action, Z / Ratio, Integrity, Quality / State, and Next for clearer first-glance interpretation.
- Added rotation label offset control.
The new Rotation Label Offset ATR input helps keep stretch and deep-stretch labels away from candles.
- Added live right-edge tag spacing control.
The new Live Tag Offset Bars input lets users move live tags farther away from the latest candle cluster.
- Preserved the core z-score rotation engine.
Pair selection, log-ratio calculation, z-score stretch logic, integrity scoring, reversion detection, rotation trail, markers, and alert conditions remain aligned with the prior version.
------------------------
Visual Improvements
------------------------
- Converted visible chart labels and right-edge tags to premium readable casing.
- Standardized chart label and live tag text as white text inside filled color boxes.
- Improved chart readability by using ATR-based label spacing around candles.
- Kept default label density balanced so the chart provides meaningful pair-rotation context without becoming overcrowded.
------------------------
Interface & Usability
------------------------
- Kept panel show/hide, theme, location, and font-size controls available from settings.
- Kept label font-size control with Normal as the default for chart labels and live tags.
- Added adjustable right-edge tag projection for cleaner screenshot spacing.
- Added adjustable chart-label offset for easier symbol and timeframe tuning.
------------------------
Behavior Notes
------------------------
This update does not change the core analytical logic of the script.
The goal is to improve clarity and usability, not to introduce new predictive behavior.
Users should interpret outputs the same way as before, but with a cleaner panel sequence and improved visual spacing.
------------------------
Limitations Reminder
------------------------
The script remains a rule-based analytical tool.
Market conditions such as volatility, liquidity, symbol behavior, quote mismatch, correlation changes, and timeframe differences may affect how pair-rotation states appear.
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.
Informacje o Wersji
UPDATE NOTES - V1.4This update focuses on final publication-view cleanup after visual QA.
The core purpose of the script remains unchanged.
This release improves the default first-glance chart appearance without removing any existing feature.
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
------------------------
* Cleaner default chart view
The rotation trail is now disabled by default. It remains available in settings for users who want continuous pair-rotation context.
* Shorter stretch labels
The default stretch label now reads "Stretch" instead of "Stretch Watch" for a cleaner premium label shape.
* Preserved advanced controls
Users can still enable the rotation trail, state markers, detailed live tags, label density, and all panel controls.
------------------------
Visual Improvements
------------------------
* Reduced line clutter across lower timeframes.
* Improved first-glance readability on 1H, 30m, and 15m charts.
* Kept meaningful historical labels visible without forcing a continuous trail over candles.
------------------------
Interface & Usability
------------------------
* The public default now opens cleaner.
* Optional visual depth remains available through settings.
* Panel structure, alerts, scoring, and hidden reference plots are unchanged.
------------------------
Behavior Notes
------------------------
This update does not change the z-score engine, integrity gate, event detection, alerts, or scoring model.
The goal is presentation quality, not new predictive behavior.
------------------------
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.
Informacje o Wersji
🔧 UPDATE NOTES - v1.5This update adds a revert-rate proof to the rotation engine.
The core purpose of the script remains unchanged.
This release keeps the same pair ratio z-score model, integrity gate and rotation states, and
adds a historical track record of how often stretched pairs rotated back to the mean zone.
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
------------------------
- Revert Rate proof layer
The panel now reports how often a stretch event returned to the mean zone within a defined
window of engine bars, shown with the sample count for transparency.
- Reversion Proof Window input
A new setting controls the window used to measure reversion, so the rate reflects prompt
reversion rather than the eventual reversion that a z-score model always produces over time.
- Per-stretch counting
Each stretch is counted once, so the rate is an honest measure of reversion behavior on the
selected pair and timeframe.
- Panel hierarchy
Added the Revert Rate row directly under Action so the rotation decision and its track record
sit together.
------------------------
Visual Improvements
------------------------
- Kept the rotation labels, live tags and optional trail unchanged
- Preserved the contrast-safe label badges and selective label density
- Maintained the clean, candle-clear chart layout
- Left the publication-ready visual style intact
------------------------
Interface & Usability
------------------------
- Added a Revert Rate row for an at-a-glance reversion track record
- Added a window setting so the proof measures prompt reversion
- Kept the existing workflow, pair, action, z-score, integrity and quality hierarchy
- Enhanced overall user experience without changing the core rotation logic
------------------------
Behavior Notes
------------------------
This update does not change the core analytical logic of the script.
The z-score, integrity gate and rotation states are unchanged. The Revert Rate is a separate
historical track-record layer and does not alter how rotation is detected.
------------------------
Limitations Reminder
------------------------
The script remains a rule-based analytical tool.
Market conditions such as volatility, correlation breakdown, and timeframe differences may
affect how stretches, reversion and the rate appear.
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.
Skrypt open-source
W zgodzie z duchem TradingView twórca tego skryptu udostępnił go jako open-source, aby użytkownicy mogli przejrzeć i zweryfikować jego działanie. Ukłony dla autora. Korzystanie jest bezpłatne, jednak ponowna publikacja kodu podlega naszym Zasadom serwisu.
Public-free scripts + invite-only AGPro workflows for market analysis, liquidity context, risk planning and execution review.
Rules-based. No hype. No guesswork.
Library & access: agprolabs.com/
Telegram: t.me/agprolabs
Rules-based. No hype. No guesswork.
Library & access: agprolabs.com/
Telegram: t.me/agprolabs
Wyłączenie odpowiedzialności
Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.
Skrypt open-source
W zgodzie z duchem TradingView twórca tego skryptu udostępnił go jako open-source, aby użytkownicy mogli przejrzeć i zweryfikować jego działanie. Ukłony dla autora. Korzystanie jest bezpłatne, jednak ponowna publikacja kodu podlega naszym Zasadom serwisu.
Public-free scripts + invite-only AGPro workflows for market analysis, liquidity context, risk planning and execution review.
Rules-based. No hype. No guesswork.
Library & access: agprolabs.com/
Telegram: t.me/agprolabs
Rules-based. No hype. No guesswork.
Library & access: agprolabs.com/
Telegram: t.me/agprolabs
Wyłączenie odpowiedzialności
Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.