1. Select two CORRELATED stocks. Here we'll use the same instrument in different TFs.
2. Generate the spread by calculating the difference between the prices/instruments. For distance based pair trading, we need to (rescale the data first and then) check the distance between them.
3. Define the logic to trade the spread and generate the trading signals. In this example we’ll calculate the rolling mean and rolling standard deviation of the spread. Whenever the spread goes above a rolling mean by one standard deviation, we’ll short the spread expecting the mean reversion behavior to hold true. And whenever the spread goes below its rolling mean by one standard deviation, we’ll go long on the spread.
Mind that the meaning of the orange and blue signals depends on whether tf variable is smaller or larger than the built-in timeframe.multiplier variable, i.e. tf of the chart.
For details see https://analyticsprofile.com/algo-tradin...
Donate: PayPal (paypal.me)
In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in a publication is governed by House Rules. You can favorite it to use it on a chart.