APB Pair Trade Direct - Cointegration🔰 APB PRO - Cointegration Pair Trading (Fool-Proof)
📌 What is this?
APB stands for "A Prueba de Bolu2" (Spanish for "Fool-Proof" - with all due respect 😉).
This is a professional Pair Trading indicator that does all the heavy lifting for you. It automatically calculates cointegration, correlation, and provides crystal clear BUY and SELL signals directly on your chart.
You don't need to be a mathematician, a statistician, or a coding expert. Just look at the arrows and the background color. The indicator does the rest.
🎯 How Does It Work?
The indicator analyzes the spread of the pair you have open on your chart (e.g., BTC/ETH, SOL/ETH, LINK/BTC, etc.) and calculates:
Historical Mean → Where the pair should normally trade.
Standard Deviations → When the pair is extremely cheap or expensive.
Real-time Cointegration → Whether the pair is behaving stably or erratically.
When the spread moves too far from its mean, the indicator alerts you with a clear arrow signal.
🟢🔴 SIGNALS (Fool-Proof)
Signal Interpretation Recommended Action
🟢 GREEN arrow pointing UP with "BUY" The pair is at the FLOOR (cheap). Spread hit the lower limit. BUY the pair (expecting mean reversion up)
🔴 RED arrow pointing DOWN with "SELL" The pair is at the CEILING (expensive). Spread hit the upper limit. SELL the pair (expecting mean reversion down)
🟩 GREEN background ✅ Cointegration ACTIVE. The pair is stable. SAFE TO TRADE (signals are valid)
🟥 RED background ❌ Cointegration INACTIVE. The pair is erratic or trending. BETTER TO WAIT (indicator will NOT give signals)
⚙️ PARAMETERS (Only 2 to Adjust)
Parameter Recommended Value What It Does
Analysis Period 100 Number of candles for mean and deviation calculation. Higher = more stable but slower.
APB Sensitivity 2.0 Controls signal frequency.
• 1.5 = More signals (aggressive)
• 2.0 = Balanced (recommended)
• 2.5-3.0 = Fewer signals (conservative)
Advanced Filters (Optional)
Parameter Recommended Value What It Does
🔒 Activate Cointegration Filter true Filters signals when the pair is unstable. Keep this ON.
📐 Slope Period 20 How many candles to measure stability. (Default is fine)
📏 Slope Threshold 0.05 Lower = more strict. 0.03 is very strict. (Default is fine)
📊 CONTROL PANEL (Real-Time Info)
The panel in the top-right corner shows you everything you need at a glance:
Data What It Means
Deviation % How far the pair has moved from its mean (in percentage).
🔴 Ceiling (SELL) Upper limit. If spread reaches this → SELL signal.
🟢 Floor (BUY) Lower limit. If spread reaches this → BUY signal.
🔒 Cointegration ✅ ACTIVE = good to trade.
❌ INACTIVE = better to wait.
📐 Slope Close to 0 = stable pair. Far from 0 = trending (cointegration broken).
🚀 Which Pairs Work Best?
This indicator is designed for cryptocurrency pairs with high liquidity and historical correlation:
Pair Recommendation
BTC/ETH ⭐⭐⭐⭐⭐ (Most stable and reliable)
ETH/BTC ⭐⭐⭐⭐⭐ (The inverse, equally good)
SOL/ETH ⭐⭐⭐⭐ (Good, but more volatile)
LINK/BTC ⭐⭐⭐⭐ (Works well in cycles)
MATIC/ETH ⭐⭐⭐ (Adjust sensitivity lower)
BNB/ETH ⭐⭐⭐ (Similar to SOL/ETH)
AVAX/ETH ⭐⭐⭐ (Adjust sensitivity)
⚠️ Does NOT work well on:
Low-liquidity pairs
Highly volatile memecoins (DOGE, SHIB, PEPE)
Pairs with extreme trend movements
🔔 Automatic Alerts
The indicator includes native alerts so you never miss an opportunity:
Alert Message
🟢 APB BUY SIGNAL "🟢 APB BUY: Pair is cheap with active cointegration. Go LONG!"
🔴 APB SELL SIGNAL "🔴 APB SELL: Pair is expensive with active cointegration. Go SHORT!"
To activate: In PulseWire, go to "Alerts" → "Create Alert" → Select the condition → Done.
💡 Pro Tips for Best Results
1. Only Trade When Background is GREEN
If the background is red, the indicator won't give signals. This is a protection mechanism. Don't force trades when cointegration is broken.
2. Don't Trade Every Signal
Wait for the arrow to appear on a green background with decent volume. The best setups are when the spread touches the limit and the market is calm.
3. Use the Right Timeframe
Timeframe Best For
1h - 4h Swing trading (days to weeks)
15m - 30m Day trading (hours)
1m - 5m ❌ Too much noise. Avoid.
4. Adjust Sensitivity Per Pair
Pair Recommended Sensitivity
BTC/ETH 2.0 (perfect)
SOL/ETH 2.2 - 2.5 (avoid false signals)
LINK/BTC 2.0 - 2.2
Volatile pairs 2.5+ (more selective)
5. Watch the Slope
If you see the slope spiking (far from 0), it means the pair is in a strong trend and cointegration is breaking. Wait for it to stabilize before trading.
🧠 How Is It Calculated? (For the Curious)
Normalization → Price is divided by its moving average to put it on a percentage scale.
Spread → The percentage deviation of the price from its mean.
Limits → Mean ± (Sensitivity × Standard Deviation).
Cointegration → Measured by the spread's slope over a short period. If the slope is close to 0, the pair is stable.
Signals → Triggered when the spread crosses the limits AND cointegration is active.
📜 Technical Details
Aspect Details
Version 2.0 (Direct Pair)
Pine Script v6 (Compatible with PulseWire)
Author APB Community
Recommended Timeframes 1h, 4h, 1D
Recommended Cryptos BTC, ETH, SOL, LINK, MATIC, BNB, AVAX
Overlay Yes (shows directly on price chart)
❓ Frequently Asked Questions
Q: Can I use this on stocks or forex?
A: Technically yes, but it's optimized for cryptocurrencies due to their higher volatility and correlation patterns.
Q: Why are there no signals even when the spread hits the limits?
A: Because the cointegration filter is active and the pair isn't stable. This is a safety feature to protect you from false signals.
Q: What does "Slope" mean in the panel?
A: It measures the speed of the spread movement. Close to 0 = stable (cointegrated). Far from 0 = trending (cointegration broken).
Q: Can I disable the cointegration filter?
A: Yes, set "Activate Cointegration Filter" to false in the advanced parameters. But I don't recommend it unless you're an experienced trader.
Q: Why is the background red/ green?
A:
🟩 GREEN = Cointegration ACTIVE → Valid signals.
🟥 RED = Cointegration INACTIVE → No signals (wait).
⭐ Rating
Aspect Score
Ease of Use ⭐⭐⭐⭐⭐ (Fool-Proof)
Accuracy on BTC/ETH ⭐⭐⭐⭐⭐
Accuracy on Altcoins ⭐⭐⭐⭐ (Adjust sensitivity)
Signal Clarity ⭐⭐⭐⭐⭐
Beginner Friendly ⭐⭐⭐⭐⭐
Professional Quality ⭐⭐⭐⭐
⚠️ DISCLAIMER (Important!)
This indicator is a TOOL for analysis, NOT a guarantee of profits.
Pair Trading reduces risk but does not eliminate it.
Cryptocurrencies are extremely volatile and can break cointegration during extreme events (news, hacks, regulations, black swan events).
Always use proper risk management:
Set stop-losses
Use appropriate position sizing
Never risk more than you can afford to lose
Test the indicator in PAPER TRADING before using real money.
Past performance does not guarantee future results. Trade responsibly.
🙏 Acknowledgments
Thank you for using APB PRO - Cointegration Pair Trading!
Remember the golden rule: The best trades are the ones you DON'T take when the market isn't clear. The red background is your friend - it tells you to wait.
May the spread always return to its mean! 🚀📊
💬 Feedback & Community
If you find this indicator useful:
⭐ Leave a like on the publication
💬 Share your experience in the comments
🔄 Repost to help other traders
Questions or suggestions? Drop a comment and I'll get back to you!
🏷️ Tags
Pair Trading Cointegration Spread Mean Reversion BTC/ETH Cryptocurrencies Trading Signals APB Fool-Proof Statistical Arbitrage Crypto Trading Swing Trading Day Trading Pine Script v6 Algorithmic Trading Indicator

Swap Engine - Pair Rotation (Z-Score) [AGPro Series]Swap Engine - Pair Rotation (Z-Score)
🔷 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. Indicator

Pairs Trading Scanner [BackQuant]Pairs Trading Scanner
What it is
This scanner analyzes the relationship between your chart symbol and a chosen pair symbol in real time. It builds a normalized “spread” between them, tracks how tightly they move together (correlation), converts the spread into a Z-Score (how far from typical it is), and then prints clear LONG / SHORT / EXIT prompts plus an at-a-glance dashboard with the numbers that matter.
Why pairs at all?
Markets co-move. When two assets are statistically related, their relationship (the spread) tends to oscillate around a mean.
Pairs trading doesn’t require calling overall market direction you trade the relative mispricing between two instruments.
This scanner gives you a robust, visual way to find those dislocations, size their significance, and structure the trade.
How it works (plain English)
Step 1 Pick a partner: Select the Pair Symbol to compare against your chart symbol. The tool fetches synchronized prices for both.
Step 2 Build a spread: Choose a Spread Method that defines “relative value” (e.g., Log Spread, Price Ratio, Return Difference, Price Difference). Each lens highlights a different flavor of divergence.
Step 3 Validate relationship: A rolling Correlation checks if the pair is moving together enough to be tradable. If correlation is weak, the scanner stands down.
Step 4 Standardize & score: The spread is normalized (mean & variability over a lookback) to form a Z-Score . Large absolute Z means “stretched,” small means “near fair.”
Step 5 Signals: When the Z-Score crosses user-defined thresholds with sufficient correlation , entries print:
LONG = long chart symbol / short pair symbol,
SHORT = short chart symbol / long pair symbol,
EXIT = mean reversion into the exit zone or correlation failure.
Core concepts (the three pillars)
Spread Method Your definition of “distance” between the two series.
Guidance:
Log Spread: Focuses on proportional differences; robust when prices live on different scales.
Price Ratio: Classic relative value; good when you care about “X per Y.”
Return Difference: Emphasizes recent performance gaps; nimble for momentum-to-mean plays.
Price Difference: Straight subtraction; intuitive for similar-scale assets (e.g., two ETFs).
Correlation A rolling score of co-movement. The scanner requires it to be above your Min Correlation before acting, so you’re not trading random divergence.
Z-Score “How abnormal is today’s spread?” Positive = chart richer than pair; negative = cheaper. Thresholds define entries/exits with transparent, statistical context.
What you’ll see on the chart
Correlation plot (blue line) with a dashed Min Correlation guide. Above the line = green zone for signals; below = hands off.
Z-Score plot (white line) with colored, dashed Entry bands and dotted Exit bands. Zero line for mean.
Normalized spread (yellow) for a quick “shape read” of recent divergence swings.
Signal markers :
LONG (green label) when Z < –Entry and corr OK,
SHORT (red label) when Z > +Entry and corr OK,
EXIT (gray label) when Z returns inside the Exit band or correlation drops below the floor.
Background tint for active state (faint green for long-spread stance, faint red for short-spread stance).
The two built-in dashboards
Statistics Table (top-right)
Pair Symbol Your chosen partner.
Correlation Live value vs. your minimum.
Z-Score How stretched the spread is now.
Current / Pair Prices Real-time anchors.
Signal State NEUTRAL / LONG / SHORT.
Price Ratio Context for ratio-style setups.
Analysis Table (bottom-right)
Avg Correlation Typical co-movement level over your window.
Max |Z| The recent extremes of dislocation.
Spread Volatility How “lively” the spread has been.
Trade Signal A human-readable prompt (e.g., “LONG A / SHORT B” or “NO TRADE” / “LOW CORRELATION”).
Risk Level LOW / MEDIUM / HIGH based on current stretch (absolute Z).
Signals logic (plain English)
Entry (LONG): The spread is unusually negative (chart cheaper vs pair) and correlation is healthy. Expect mean reversion upward in the spread: long chart, short pair.
Entry (SHORT): The spread is unusually positive (chart richer vs pair) and correlation is healthy. Expect mean reversion downward in the spread: short chart, long pair.
Exit: The spread relaxes back toward normal (inside your exit band), or correlation deteriorates (relationship no longer trusted).
A quick, repeatable workflow
1) Choose your pair in context (same sector/theme or known macro link). Think: “Do these two plausibly co-move?”
2) Pick a spread lens that matches your narrative (ratio for relative value, returns for short-term performance gaps, etc.).
3) Confirm correlation is above your floor no corr, no trade.
4) Wait for a stretch (Z beyond Entry band) and a printed LONG / SHORT .
5) Manage to the mean (EXIT band) or correlation failure; let the scanners’ state/labels keep you honest.
Settings that matter (and why)
Spread Method Defines the “mispricing” you care about.
Correlation Period Longer = steadier regime read, shorter = snappier to regime change.
Z-Score Period The window that defines “normal” for the spread; it sets the yardstick.
Use Percentage Returns Normalizes series when using return-based logic; keep on for mixed-scale assets.
Entry / Exit Thresholds Set your stretch and your target reversion zone. Wider entries = rarer but stronger signals.
Minimum Correlation The gatekeeper. Raising it favors quality over quantity.
Choosing pairs (practical cheat sheet)
Same family: two index ETFs, two oil-linked names, two gold miners, two L1 tokens.
Hedge & proxy: stock vs. sector ETF, BTC vs. BTC index, WTI vs. energy ETF.
Cross-venue or cross-listing: instruments that are functionally the same exposure but price differently intraday.
Reading the cues like a pro
Divergence shape: The yellow normalized spread helps you see rhythm fast spike and snap-back versus slow grind.
Corr-first discipline: Don’t fight the “Min Correlation” line. Good pairs trading starts with a relationship you can trust.
Exit humility: When Z re-centers, let the EXIT do its job. The edge is the journey to the mean, not overstaying it.
Frequently asked (quick answers)
“Long/Short means what exactly?”
LONG = long the chart symbol and short the pair symbol.
SHORT = short the chart symbol and long the pair symbol.
“Do I need same price scales?” No. The spread methods normalize in different ways; choose the one that fits your use case (log/ratio are great for mixed scales).
“What if correlation falls mid-trade?” The scanner will neutralize the state and print EXIT . Relationship first; trade second.
Field notes & patterns
Snap-back days: After a one-sided session, return-difference spreads often flag cleaner intraday mean reversions.
Macro rotations: Ratio spreads shine during sector re-weights (e.g., value vs. growth ETFs); look for steady corr + elevated |Z|.
Event bleed-through: If one symbol reacts to news and its partner lags, Z often flags a high-quality, short-horizon re-centering.
Display controls at a glance
Show Statistics Table Live state & key numbers, top-right.
Show Analysis Table Context/risk read, bottom-right.
Show Correlation / Spread / Z-Score Toggle the sub-charts you want visible.
Show Entry/Exit Signals Turn markers on/off as needed.
Coloring Adjust Long/Short/Neutral and correlation line colors to match your theme.
Alerts (ready to route to your workflow)
Pairs Long Entry Z falls through the long threshold with correlation above minimum.
Pairs Short Entry Z rises through the short threshold with correlation above minimum.
Pairs Trade Exit Z returns to neutral or the relationship fails your correlation floor.
Correlation Breakdown Rolling correlation crosses your minimum; relationship caution.
Final notes
The scanner is designed to keep you systematic: require relationship (correlation), quantify dislocation (Z-Score), act when stretched, stand down when it normalizes or the relationship degrades. It’s a full, visual loop for relative-value trading that stays out of your way when it should and gets loud only when the numbers line up.
Indicator

Strength Comparison @joshuuuexample:
if you want to find the stronger/weaker pair between eurusd and gbpusd, what you can do is check the eurgbp charts. if eurgbp is bullish, that means, that longs longs on eurusd are better than on gbpusd.
Unfortunately, there is no such thing to compare for example usoil with ukoil, or us100 with us500.
That's where this indicator comes in handy. You can choose whatever two symbols you want, that are supported by pulsewire and you will get a chart, which shows symbol1/symbol2.
Now you can use normal market structure, or the ema option, to find out the stronger symbol.
This can also help predicting the so called SMT Divergences, taught by ICT.
⚠️ Open Source ⚠️
Coders and TV users are authorized to copy this code base, but a paid distribution is prohibited. A mention to the original author is expected, and appreciated.
⚠️ Terms and Conditions ⚠️
This financial tool is for educational purposes only and not financial advice. Users assume responsibility for decisions made based on the tool's information. Past performance doesn't guarantee future results. By using this tool, users agree to these terms. Indicator

Indicator

Strategy

Indicator

Indicator

Indicator

Indicator

Indicator

Indicator

Indicator
