Symbols Correlation, built for pair tradingOverview:
This script is designed for pairs trading. If you are not familiar with pairs trading, I suggest learning about it, as it can be a profitable strategy in neutral markets (or neutral trends between two assets). The correlation between two assets is the foundation of pairs trading, and without it, the chances of making a profit are low.
Correlation can be described in two opposite ways:
1: Absolute positive correlation (meaning the asset prices move together).
-1: Absolute negative correlation (meaning the asset prices move in opposite directions).
Any value between 1 and -1 indicates some degree of correlation, but generally, values higher than 0.7 or lower than -0.7 are considered significant.
Features:
Typically, correlation is measured using the closing prices. This script adds three more correlation studies based on open, high, and low prices. By using all four lines, we can get a better understanding of the pair's correlation.
How to Read This Indicator:
To use this indicator effectively, you need to input your pair as a ratio. For example, if your pair is TSN and ZBH, enter it in the symbol search as: TSN/ZBH
Gray Area : This area indicates "no high correlation" (default is between -0.8 and 0.8, adjustable in the settings).
Gray Line : This represents the close correlation within the "no high correlation" range.
Green Line : This represents the close correlation within the "high correlation" range.
Dot Lines : These represent the open, high, and low correlations.
Example Interpretations:
A : All four lines are close together & the line is green – very good correlation!
B : The line is gray, and the dot lines are apart – not a strong correlation.
C : When the close correlation remains green for a long time, it signals a strong correlation.
Application in Pairs Trading:
In pairs trading, aim for the highest possible correlation, and it is important to have a sustained correlation over a long period. Pairs that correlate only part of the year but not consistently are less reliable for pairs trading.
This is an example for good correlation for pairs trading:
This is an example for bad correlation for pairs trading:
Here is a view of my full indicators when doing pairs trading:
Pairtrading
Trend Momentum Strength Indicator, Built for Pairs TradingOverview:
This script combines multiple indicators to provide a comprehensive analysis of both trend strength and trend momentum. It is tailored specifically for pairs trading strategies but can also be used for other trading strategies.
Benefit of Comprehensive Analysis:
Having an indicator that evaluates both trend strength and trend momentum is crucial for traders looking to make informed decisions. It allows traders to not only identify the direction and intensity of a trend but also gauge the momentum behind it. This dual capability helps in confirming potential trade opportunities, whether for entering trades with strong trends or considering reversals during overbought or oversold conditions. By integrating both aspects into one tool, traders can gain a holistic view of market dynamics, enhancing their ability to time entries and manage risk effectively.
Features:
* Trend Strength:
Enhanced ADX Formula: The script includes modifications to the standard ADX formula along with DI+ and DI- to provide more responsive trend strength readings.
Directional Indicators: DI+ (green line) indicates positive directional movement, while DI- (red line) indicates negative directional movement.
Trend Momentum:
Modified Stochastic Indicators: The script uses %K and %D indicators, modified and combined with ADX to give a clear indication of trend momentum.
Momentum Strength: This helps determine the strength and direction of the momentum.
Trading Signals:
Combining Indicators: The script combines ADX, DI+, DI-, %K, and %D to generate comprehensive trading signals.
Optimal Entry Points: Designed to identify optimal entry points for trades, particularly in pairs trading.
Colored Area at Bottom:
This area provides two easy-to-read functions:
Color:
Green: Upward momentum (ratio above 1)
Red: Downward momentum (ratio below 1)
Height:
Higher in green: Stronger upward momentum
Lower in red: Stronger downward momentum
Legend:
Green Line: DI+ (Positive)
Red Line: DI- (Negative)
Black Line: ADX
How to Read This Indicator:
1) Trend Direction:
DI+ above DI-: Indicates an upward trend.
DI- above DI+: Indicates a downward trend.
2) Trend Strength:
ADX below 20: Indicates a neutral trend.
ADX between 20 and 25: Indicates a weak trend.
ADX above 25: Indicates a strong trend.
Trading Signals in Pairs Trading:
Neutral Trend: Ideal for pairs trading when no strong trend is detected.
Overbought/Oversold: Uses %K and %D to identify overbought/oversold conditions that support trade decisions.
Entry Signals: Green signals for long positions, red signals for short positions, based on combined criteria of neutral trend strength and supportive momentum.
Application in Pairs Trading:
Neutral trend: In pairs trading strategies, where neutral movement is often sought, this indicator provides signals that are especially relevant during periods of neutral trend strength and supportive momentum, aiding traders in identifying optimal entry
Risk Management: Combining signals from ADX, DI+, DI-, %K, and %D helps traders make more informed decisions regarding entry points, enhancing risk management.
Example Chart (The indicator is on the upper right corner):
Clean Presentation: The chart only includes the necessary elements to demonstrate the indicator’s functionality.
Demonstrates: Overbought/oversold conditions, upward/downward/no momentum, and trading signals with/without specific scenarios.
TTP Pair CipherPair Cipher can run your hedge pair trading strategy.
Pair cipher can use a spread chart (two assets ratio or difference) to manage a hedge position consisting of two assets: one long and one short position.
Event though the spread chart is used to determine the entries and exits each coin price action is used to calculate floating PNL.
It supports different bot platforms. It's backtestable and can run live.
Features:
- Internal and external entry signal
- In-chart realised PNL plot
- Hedge position floating PNL chart
- Individual floating PNL for each long and short ("show coins" toggle)
- Retracement exit strategy: determine at which retracement factor to exit your position while in profit
- PNL RSI exit strategy: determine at which RSI level crossunder you'd like to exit. RSI is applied to the floating PNL
- Static TP/SL levels
- ATR TP/SL levels with individual factors. When ATR is selected the TP or SL acts as a multiplier of ATR instead.
- On-chart debug labels for alerts
- Intra candle alert: signals can trigger intra candle in this mode, but this mode will cause repainting. Example: if the position goes below SL intra candle, the alert will be sent, but later if it goes in profit before closing the candle, the backtest will continue with the position open. The backtest does NOT have access to the intra candle data. Alert intra candle reduces the risk of not applying SL.
Example of setup:
1) Load an empty 1 hour timeframe chart with the spread BYBIT:REQUSDT.P / BYBIT:REEFUSDT.P
2) Select an investment amount
3) Select TP 1.2 and enable ATR
4) Select SL 1.1 and enable ATR
5) Select RSI profits of crossunder 70
6) Don't enable external signal (you can try with TTP PNR)
7) Select BYBIT:REQUSDT.P as symbol 1
8) Select BYBIT:REEFUSDT.P as symbol 2
Arbitrage SpreadThis indicator helps to find spreads between cryptocurrencies, assess their correlation, spread, z score and atr z score.
The graphs are plotted as a percentage. Because of the limitation in pine tradingview for 5000 bars a period was introduced (after which a new starting point of the graph construction will be started), if you want it can be disabled
The multiplier parameter affects only the construction of the joint diagram on which z score and atr z score are calculated (construction of the diagram is done by dividing one pair by another and multiplying by the multiplier parameter) is shown with a red line
To create a notification you have to specify the data for parameters other than zero which you want to monitor. For parameters z score and atr z score data are counted in both directions
The data can be tracked via the data window
Link to image of the data window prnt.sc
Cuban's Pair Trading IndexThe purpose of this indicator is to visually simplify the relationship between two assets when searching for pair trades or higher beta opportunities.
With highly correlated pairs, it can be a blessing or a curse during volatility when you're somehow stuck in the only lower beta pairs, or maybe you're market neutral and the wrong leg starts nuking.
This indicator was built as a visual way to track pair relationships.
Fundamentally, this script does the following:
Plots the relative performance of the relationship between two assets across multiple time horizons
Uses a consistent measurement of historical performance, regardless of asset -- currently standard deviations, may add log difference in the future
Plots a custom Average Directional Index on the current chart ticker for current asset contextual momentum
Plots the average 'rotation' of both the ADX and Pair Delta independently, over n numbers of rotations -- able to be specified using the 'Rotation Lookback' variable
If you've never pair traded crypto before (i.e. long $DYDX, short $ETH), you might not be aware that most highly correlated alt asset returns tend to oscillate on a low timeframe rolling basis around the performance of the majors -- and more recently, predominantly $ETH. With this in mind and using this oscillator, we can track that relationship.
Users are given the ability to adjust the following:
Comparison Asset
Fast and Slow Delta Lookbacks
Whether to wait for one bar delay during security calls
Rotation Lookback
Rotation Threshold for Pair Delta and ADX independently
ADX Lookback
Whether to utilize the ADX on the current chart ticker or also net that off against the ADX of the comparison asset
TO DO:
Aesthetic update to Pair Delta plot
Permanent fix for security call forced delay
Cuban's Asset ScreenerCuban's Asset Screener is a tool designed to view the health of the entire market in a single charting window, using a multi-timeframe, real-time heatmapped asset screener built natively within Tradingview.
You can use this tool to aggregate and display critical information required to identify your favorite trade ideas using other Cuban's Edge tools. Although the screener currently uses pre-built lists for over 200+ Binance and Bybit Futures pairs, the tool comes with custom watchlist support, allowing you to add as many additional assets as your screen and browser will support.
Currently tracking range positions and a custom cross asset delta function from Cuban's Pair Trading Index, the screener has an in-built sorting function which orders assets by similar market structure and colors them relative to their performance against the user's comparison asset -- their current chart ticker.
Cuban's Asset Screener is also valuable as a tool to monitor performance of your portfolio against any benchmark asset, by using the 'Asset Redenomination' option within the settings. This allows the user to redenominate the entire screener easily using their current chart ticker.
In order to setup the Asset Screener, the user will need to select an 'Asset List' and a 'Screen Location' value. This will load the screener into a set position on screen, from right to left. In order to add additional assets, multiple instances of the asset screener will need to be loaded on screen.
With this indicator, users get the option to adjust the following:
range positioning lookback
asset redenomination for range positioning
asset sorting order
screen location
multi-timeframe support
live pricing for PTI values
in-built asset lists for 200+ assets
TO DO:
add market filters to the coloring
add tradfi asset lists
Pair ViewerPair-Trading is a recognized and widely used trading method, this indicator is a tool that allows via several display interfaces (2 at the moment) to see relative performance ratios of two assets.
The inputs are pretty simple to understand but here is the list of them :
- Ticker #1 : The first Asset's ticker // numerator of the ratio
- Ticker #2 : The second Asset's ticker // denominator of the ratio
- View as : Display Method
- Up Color : Color of positive candle (when close > open)
- Down Color : Color of negative candle (when close < open)
Of course, this indicator only shows stuff at the chart, it does NOT provide any investment advice.
two_leg_spread_diffThis script helps you discern the relative change of each leg in a two-legged spread over a given period. The main plot is a difference in log return over the number of bars identified by the "lag" parameter. E.g. if "lag" is 10 and leg one has increased 3% over the past ten bars, while leg two has only increased 1%, the plot value is 2%. The main plot is also colored blue when leg one increases while leg two decreases on a given bar, and red if the opposite is true. This feature identifies periods where the correlation between the two legs diminishes. The one and two standard deviation of the main plot is also plotted in faint background lines. Additionally, a table indicates the percentage in which the main plot is within one standard deviation (acc 1) and two standard deviations (acc 2). Note that the standard deviation updates on each bar, so the current standard deviation is not the one used to calculate the accuracy. Rather, if there are N bars, N different standard deviation readings have been used to compute the accuracy statistics.
The inputs are:
- timeframe: the timeframe of the chart
- leg1_sym: the symbol of the first leg
- leg2_sym: the symbol of the second leg
- lag: the number of bars back to reference for computing the log return of each leg
- anchor_to_session_start: for intraday charts only, this overwrites the "lag" input so that the "lag" always sets the point of comparison to the session start. This setting is used to compute the relative change over a single session.
Bollinger Pair TradeNYSE:MA-1.6*NYSE:V
Revision: 1
Author: @ozdemirtrading
Revision 2 Considerations :
- Simplify and clean up plotting
Disclaimer: This strategy is currently working on the 5M chart. Change the length input to accommodate your needs.
For the backtesting of more than 3 months, you may need to upgrade your membership.
Description:
The general idea of the strategy is very straightforward: it takes positions according to the lower and upper Bollinger bands.
But I am mainly using this strategy for pair trading stocks. Do not forget that you will get better results if you trade with cointegrated pairs.
Bollinger band: Moving average & standard deviation are calculated based on 20 bars on the 1H chart (approx 240 bars on a 5m chart). X-day moving averages (20 days as default) are also used in the background in some of the exit strategy choices.
You can define position entry levels as the multipliers of standard deviation (for exp: mult2 as 2 * standard deviation).
There are 4 choices for the exit strategy:
SMA: Exit when touches simple moving average (SMA)
SKP: Skip SMA and do not stop if moving towards 20D SMA, and exit if it touches the other side of the band
SKPXDSMA: Skip SMA if moving towards 20D SMA, and exit if it touches 20D SMA
NoExit: Exit if it touches the upper & lower band only.
Options:
- Strategy hard stop: if trade loss reaches a point defined as a percent of the initial capital. Stop taking new positions. (not recommended for pair trade)
- Loss per trade: close position if the loss is at a defined level but keeps watching for new positions.
- Enable expected profit for trade (expected profit is calculated as the distance to SMA) (recommended for pair trade)
- Enable VIX threshold for the following options: (recommended for volatile periods)
- Stop trading if VIX for the previous day closes above the threshold
- Reverse active trade direction if VIX for the previous day is above the threshold
- Take reverse positions (assuming the Bollinger band is going to expand) for all trades
Backtesting:
Close positions after a defined interval: mark this if you want the close the final trade for backtesting purposes. Unmark it to get live signals.
Use custom interval: Backtest specific time periods.
Other Options:
- Use EMA: use an exponential moving average for the calculations instead of simple moving average
- Not against XDSMA: do not take a position against 20D SMA (if X is selected as 20) (recommended for pairs with a clear trend)
- Not in XDSMA 1 DEV: do not take a position in 20D SMA 1*standart deviation band (recommended if you need to decrease # of trades and increase profit for trade)
- Not in XDSMA 2 DEV: do not take a position in 20D SMA 2*standart deviation band
Session management:
- Not in session: Session start and end times can be defined here. If you do not want to trade in certain time intervals, mark that session.(helps to reduce slippage and get more realistic backtest results)
TASC 2022.07 Pairs Rotation With Ehlers Loops█ OVERVIEW
TASC's July 2022 edition of Traders' Tips includes an article by John Ehlers titled "Pairs Rotation With Ehlers Loops". This is the code that implements the Ehlers Loops applied to pairs rotation trading.
█ CONCEPTS
John Ehlers developed Ehlers loops as a tool to visualize the performance of one data stream versus another. Initially, he used this tool to chart price versus volume. However, Ehlers loops proved to be suitable for determining the timing of the pairs rotation strategy . This strategy works by having a long position in only one of two securities, depending on which one is considered stronger at a given time.
When the prices of two securities (filtered and scaled with a standard deviation for consistent presentation) are plotted against each other, the curvature and direction of rotation on the chart can help guide decisions on long positions. For example, when plotting a stock versus a referenced symbol, a vertical upward movement while rotating clockwise is a sign of going long the stock. Similarly, a horizontal movement to the right while rotating counterclockwise is the sign to go long the reference. A higher probability of a reversal is expected when the price moves more than one or two standard deviations.
█ CALCULATIONS
The script uses the following steps to calculate the Ehlers Loops:
The price data of both securities in the pair are individually filtered using identical high-pass and SuperSmoother filters. This results in two band-limited data streams, having a nominally zero mean. The input parameters Low-Pass Period and High-Pass Period control the filter bandwidth and thus can modify the shape of the Ehlers Loops.
Subsequently, the filtered data streams are scaled in terms of standard deviation by dividing each of them by their root-mean-square (RMS) values. These data streams are plotted as zero-mean oscillators.
Finally, the scaled data streams are displayed one against another for the selected time interval (defined by the input parameter Loop Segments ). In the resulting scatterplot, the thicker line corresponds to the later data points. The fluctuations of the filtered price data of the chart symbol are plotted along the y -axis, and the price changes of the referenced symbol are shown along the x -axis.
R2D2 v1.0Скрипт для парного трейдинга.
Можно анализировать дельту между 2 инструментами.
Гистограмма показывает силу расхождения между ними.
Добавлен коэффициент умножения для каждого тикера, что бы выравнять баланс между инструментами.
Можно работать на любом ТФ. Не забывайте, что данный скрипт работает на МА, поэтому при выборе больших числовых значений возможно запаздывание.
______________
Script for pair trading.
You can analyze the Delta between 2 tools.
The histogram shows the strength of the discrepancy between them.
Added a multiplication factor for each Ticker to even out the balance between instruments.
You can work on any TF. Do not forget that this script works on MA, so when selecting large numeric values, there may be a delay.
RW Simple Pairs TradeA Simple Implementation of a Pairs Trading Strategy
It uses a simple moving average of specified length (default = 20) and enters at cutoffs set by Entry ZScore. Trades are exited at the moving average.
It is intended to be run on pairs of stocks. To Spread KO and PEP, for example, use the ticker KO / PEP * 1000
To visualise the trade better add Bollinger bands to your charts, corresponding to the SMA length and Entry ZScore criteria you specified.
GoldGun by Frequu
Hi, I would like to present you the best script for manual / automatic trading
NO REPAINT
ALERT FIX
ALERT NO DOUBLE!
- ALL PAIR STOX (over 90%)
- GOLD (80-85%)
- and more more more ..
Script i`m testing on 1BROKER, binance and pepperstone, working brilliant !
Pair traderI figured I'd post this.
It's an indicator that plots the spread between two selectable instruments and also each individual instrument's line chart, with a colored fill to make it more clear visually when trading ratios.
In cointegrated pairs like audcad-0.50% , you can trade the range extremes, and buy the laggard/sell the leader when overbought/sold conditions are met + distance from the 66/253 EMAs, as outlined in my AUDCAD-0.50% post. (see related ideas)
Hope you find it useful!
Cheers,
Ivan.