OPEN-SOURCE SCRIPT

Aladin Pair Trading System v1

484
Aladin Pair Trading System v1

What is This Indicator?

The Aladin Pair Trading System is a sophisticated tool designed to help traders identify profitable opportunities by comparing two related stocks that historically move together. Think of it as finding when one twin is running ahead or lagging behind the other - these moments often present trading opportunities as they tend to return to moving together.

Who Should Use This?

Beginners: Learn about statistical arbitrage and pair trading
Intermediate Traders: Execute mean-reversion strategies with confidence
Advanced Traders: Fine-tune parameters for optimal pair relationships
Portfolio Managers: Implement market-neutral strategies


💡 What is Pair Trading?
Imagine two ice cream shops next to each other. They usually have similar customer traffic because they're in the same area. If one day Shop A is packed while Shop B is empty, you might expect this imbalance to correct itself soon.
Pair trading works the same way:

You find two stocks that normally move together (like TCS and Infosys)
When one stock moves too far from the other, you trade expecting them to realign
You buy the lagging stock and sell the leading stock
When they come back together, you profit from both sides


Key Features
1. Z-Score Analysis

What it is: A statistical measure showing how far the price relationship has deviated from normal
What it means:

Z-Score near 0 = Normal relationship
Z-Score at +2 = Stock A is expensive relative to Stock B (Sell A, Buy B)
Z-Score at -2 = Stock A is cheap relative to Stock B (Buy A, Sell B)



2. Multiple Timeframe Analysis

Long-term Z-Score (300 bars): Shows the big picture trend
Short-term Z-Score (100 bars): Shows recent movements
Signal Z-Score (20 bars): Generates quick trading signals

3. Statistical Validation
The indicator checks if the pair is suitable for trading:

Correlation (must be > 0.7): Confirms the stocks move together

1.0 = Perfect positive correlation
0.7 = Strong correlation
Below 0.7 = Warning: pair may not be reliable


ADF P-Value (should be < 0.05): Tests if the relationship is stable

Low value = Good for pair trading
High value = Relationship may be random


Cointegration: Confirms long-term equilibrium relationship

YES = Pair tends to revert to mean
NO = Pair may drift apart permanently




Visual Elements Explained
Chart Zones (Color-Coded Areas)

Yellow Zone (-1.5 to +1.5)

Normal Zone: Relationship is stable
Action: Wait for better opportunities


Blue Zone (±1.5 to ±2.0)

Entry Zone: Deviation is significant
Action: Prepare for potential trades


Green/Red Zone (±2.0 to ±3.0)

Opportunity Zone: Strong deviation
Action: High-probability trade setups


Beyond ±3.0

Risk Limit: Extreme deviation
Action: Either maximum opportunity or structural break



Signal Arrows

Green Arrow Up (Buy A + Sell B):

Stock A is undervalued relative to B
Buy Stock A, Short Stock B


Red Arrow Down (Sell A + Buy B):

Stock A is overvalued relative to B
Sell Stock A, Buy Stock B


Settings Guide
Symbol Inputs

Pair Symbol (Symbol B): Choose the second stock to compare

Default: NSE:INFY (Infosys)
Example pairs: TCS/INFY, HDFCBANK/ICICIBANK, RELIANCE/ONGC

Z-Score Parameters

Long Z-Score Period (300): Historical context
Short Z-Score Period (100): Recent trend
Signal Period (20): Trading signals
Z-Score Threshold (2.0): Entry trigger level

Higher = Fewer but stronger signals
Lower = More frequent signals



Statistical Parameters

Correlation Period (240): How many bars to check correlation
Hurst Exponent Period (50): Measures mean-reversion tendency
Probability Lookback (100): Historical probability calculations

Trading Parameters

Entry Threshold (0.0): Minimum Z-score for entry
Risk Threshold (1.5): Warning level
Risk Limit (3.0): Maximum deviation to trade


How to Use (Step-by-Step)
Step 1: Choose Your Pair

Add the indicator to your chart (this becomes Stock A)
In settings, select Stock B (the comparison stock)
Choose stocks from the same sector for best results

Step 2: Verify Pair Quality
Check the Statistics Table (top-right corner):

✅ Correlation > 0.70 (Green = Good)
✅ ADF P-value < 0.05 (Green = Good)
✅ Cointegrated = YES (Green = Good)

If all three are green, the pair is suitable for trading!
Step 3: Wait for Signals
BUY SIGNAL (Green Arrow Up)

Z-Score crosses above -2.0
Action: Buy Stock A, Sell Stock B
Exit: When Z-Score returns to 0

SELL SIGNAL (Red Arrow Down)

Z-Score crosses below +2.0
Action: Sell Stock A, Buy Stock B
Exit: When Z-Score returns to 0

Step 4: Risk Management

Yellow Zone: Monitor only
Blue Zone: Prepare for entry
Green/Red Zone: Active trading zone
Beyond ±3.0: Maximum risk - use caution


⚠️ Important Warnings

Not All Pairs Work: Always check the statistics table first
Market Conditions Matter: Correlation can break during market stress
Use Stop Losses: Set stops at Z-Score ±3.5 or beyond
Position Sizing: Trade both legs with appropriate hedge ratios
Transaction Costs: Factor in brokerage and slippage for both stocks


Example Trade
Scenario: TCS vs INFOSYS

Correlation: 0.85 ✅
Z-Score: -2.3 (TCS is cheap vs INFY)

Action to be taken:

Buy 1lot of TCS Future
Sell 1lot of INFOSYS Future

Expected Outcome:

As Z-Score moves toward 0, TCS outperforms INFOSYS
Close both positions when Z-Score crosses 0
Profit from the convergence


Best Practices

Test Before Trading: Use paper trading first
Sector Focus: Choose pairs from the same industry
Monitor Statistics: Check correlation daily
Avoid News Events: Don't trade pairs during earnings/major news
Size Appropriately: Start small, scale with experience
Be Patient: Wait for high-quality setups (±2.0 or beyond)


What Makes This Indicator Unique?

Multi-timeframe Z-Score analysis: Three different perspectives
Statistical validation: Built-in correlation and cointegration tests
Visual risk zones: Easy-to-understand color-coded areas
Real-time statistics: Live pair quality monitoring
Beginner-friendly: Clear signals with educational zones


Technical Background
The indicator uses:

Engle-Granger Cointegration Test: Validates pair relationship
ADF (Augmented Dickey-Fuller) Test: Tests stationarity
Pearson Correlation: Measures linear relationship
Z-Score Normalization: Standardizes deviations
Log Returns: Handles price differences properly


Support & Community
For questions, suggestions, or to share your pair trading experiences:

Comment below the indicator
Share your successful pair combinations
Report any issues for quick fixes


Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial advice. Pair trading involves risk, including the risk of loss.

Always:
Do your own research
Understand the risks
Trade with money you can afford to lose
Consider consulting a financial advisor


📌 Quick Reference Card
Z-ScoreInterpretationAction-3.0 to -2.0A very cheap vs BStrong Buy A, Sell B-2.0 to -1.5A cheap vs BBuy A, Sell B-1.5 to +1.5Normal rangeHold/Wait+1.5 to +2.0A expensive vs BSell A, Buy B+2.0 to +3.0A very expensive vs BStrong Sell A, Buy B
Good Pair Statistics:

Correlation: > 0.70
ADF P-value: < 0.05
Cointegration: YES


Version: 1.0
Last Updated: 10th October 2025
Compatible: TradingView Pine Script v6
Happy Trading!

Thông báo miễn trừ trách nhiệm

Thông tin và ấn phẩm không có nghĩa là và không cấu thành, tài chính, đầu tư, kinh doanh, hoặc các loại lời khuyên hoặc khuyến nghị khác được cung cấp hoặc xác nhận bởi TradingView. Đọc thêm trong Điều khoản sử dụng.