OPEN-SOURCE SCRIPT

RSI Trend Following Strategy

Overview
The RSI Trend Following Strategy utilizes Relative Strength Index (RSI) to enter the trade for the potential trend continuation. It uses Stochastic indicator to check is the price is not in overbought territory and the MACD to measure the current price momentum. Moreover, it uses the 200-period EMA to filter the counter trend trades with the higher probability. The strategy opens only long trades.

Unique Features
  1. Dynamic stop-loss system: Instead of fixed stop-loss level strategy utilizes average true range (ATR) multiplied by user given number subtracted from the position entry price as a dynamic stop loss level.
  2. Configurable Trading Periods: Users can tailor the strategy to specific market windows, adapting to different market conditions.
  3. Two layers trade filtering system: Strategy utilizes MACD and Stochastic indicators measure the current momentum and overbought condition and use 200-period EMA to filter trades against major trend.
  4. Trailing take profit level: After reaching the trailing profit activation level script activates the trailing of long trade using EMA. More information in methodology.
  5. Wide opportunities for strategy optimization: Flexible strategy settings allows users to optimize the strategy entries and exits for chosen trading pair and time frame.


Methodology
The strategy opens long trade when the following price met the conditions:
  1. RSI is above 50 level.
  2. MACD line shall be above the signal line
  3. Both lines of Stochastic shall be not higher than 80 (overbought territory)
  4. Candle’s low shall be above the 200 period EMA


When long trade is executed, strategy set the stop-loss level at the price ATR multiplied by user-given value below the entry price. This level is recalculated on every next candle close, adjusting to the current market volatility.
At the same time strategy set up the trailing stop validation level. When the price crosses the level equals entry price plus ATR multiplied by user-given value script starts to trail the price with trailing EMA(by default = 20 period). If price closes below EMA long trade is closed. When the trailing starts, script prints the label “Trailing Activated”.

Strategy settings
In the inputs window user can setup the following strategy settings:
  • ATR Stop Loss (by default = 1.75)
  • ATR Trailing Profit Activation Level (by default = 2.25)
  • MACD Fast Length (by default = 12, period of averaging fast MACD line)
  • MACD Fast Length (by default = 26, period of averaging slow MACD line)
  • MACD Signal Smoothing (by default = 9, period of smoothing MACD signal line)
  • Oscillator MA Type (by default = EMA, available options: SMA, EMA)
  • Signal Line MA Type (by default = EMA, available options: SMA, EMA)
  • RSI Length (by default = 14, period for RSI calculation)
  • Trailing EMA Length (by default = 20, period for EMA, which shall be broken close the trade after trailing profit activation)


Justification of Methodology
This trading strategy is designed to leverage a combination of technical indicators—Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), Stochastic Oscillator, and the 200-period Exponential Moving Average (EMA)—to determine optimal entry points for long trades. Additionally, the strategy uses the Average True Range (ATR) for dynamic risk management to adapt to varying market conditions. Let's look in details for which purpose each indicator is used for and why it is used in this combination.

Relative Strength Index (RSI) is a momentum indicator used in technical analysis to measure the speed and change of price movements in a financial market. It helps traders identify whether an asset is potentially overbought (overvalued) or oversold (undervalued), which can indicate a potential reversal or continuation of the current trend.

How RSI Works? RSI tracks the strength of recent price changes. It compares the average gains and losses over a specific period (usually 14 periods) to assess the momentum of an asset. Average gain is the average of all positive price changes over the chosen period. It reflects how much the price has typically increased during upward movements. Average loss is the average of all negative price changes over the same period. It reflects how much the price has typically decreased during downward movements.

RSI calculates these average gains and losses and compares them to create a value between 0 and 100. If the RSI value is above 70, the asset is generally considered overbought, meaning it might be due for a price correction or reversal downward. Conversely, if the RSI value is below 30, the asset is considered oversold, suggesting it could be poised for an upward reversal or recovery. RSI is a useful tool for traders to determine market conditions and make informed decisions about entering or exiting trades based on the perceived strength or weakness of an asset's price movements.

This strategy uses RSI as a short-term trend approximation. If RSI crosses over 50 it means that there is a high probability of short-term trend change from downtrend to uptrend. Therefore RSI above 50 is our first trend filter to look for a long position.

The MACD (Moving Average Convergence Divergence) is a popular momentum and trend-following indicator used in technical analysis. It helps traders identify changes in the strength, direction, momentum, and duration of a trend in an asset's price.
The MACD consists of three components:

MACD Line: This is the difference between a short-term Exponential Moving Average (EMA) and a long-term EMA, typically calculated as: MACD Line = 12 period EMA − 26 period EMA

Signal Line: This is a 9-period EMA of the MACD Line, which helps to identify buy or sell signals. When the MACD Line crosses above the Signal Line, it can be a bullish signal (suggesting a buy); when it crosses below, it can be a bearish signal (suggesting a sell).

Histogram: The histogram shows the difference between the MACD Line and the Signal Line, visually representing the momentum of the trend. Positive histogram values indicate increasing bullish momentum, while negative values indicate increasing bearish momentum.

This strategy uses MACD as a second short-term trend filter. When MACD line crossed over the signal line there is a high probability that uptrend has been started. Therefore MACD line above signal line is our additional short-term trend filter. In conjunction with RSI it decreases probability of following false trend change signals.

The Stochastic Indicator is a momentum oscillator that compares a security's closing price to its price range over a specific period. It's used to identify overbought and oversold conditions. The indicator ranges from 0 to 100, with readings above 80 indicating overbought conditions and readings below 20 indicating oversold conditions.
It consists of two lines:

  • %K: The main line, calculated using the formula (CurrentClose−LowestLow)/(HighestHigh−LowestLow)×100. Highest and lowest price taken for 14 periods.
  • %D: A smoothed moving average of %K, often used as a signal line.


This strategy uses stochastic to define the overbought conditions. The logic here is the following: we want to avoid long trades in the overbought territory, because when indicator reaches it there is a high probability that the potential move is gonna be restricted.

The 200-period EMA is a widely recognized indicator for identifying the long-term trend direction. The strategy only trades in the direction of this primary trend to increase the probability of successful trades. For instance, when the price is above the 200 EMA, only long trades are considered, aligning with the overarching trend direction.

Therefore, strategy uses combination of RSI and MACD to increase the probability that price now is in short-term uptrend, Stochastic helps to avoid the trades in the overbought (>80) territory. To increase the probability of opening long trades in the direction of a main trend and avoid local bounces we use 200 period EMA.

ATR is used to adjust the strategy risk management to the current market volatility. If volatility is low, we don’t need the large stop loss to understand the there is a high probability that we made a mistake opening the trade. User can setup the settings ATR Stop Loss and ATR Trailing Profit Activation Level to realize his own risk to reward preferences, but the unique feature of a strategy is that after reaching trailing profit activation level strategy is trying to follow the trend until it is likely to be finished instead of using fixed risk management settings. It allows sometimes to be involved in the large movements.

Backtest Results
  • Operating window: Date range of backtests is 2023.01.01 - 2024.08.01. It is chosen to let the strategy to close all opened positions.
  • Commission and Slippage: Includes a standard Binance commission of 0.1% and accounts for possible slippage over 5 ticks.
  • Initial capital: 10000 USDT
  • Percent of capital used in every trade: 30%
  • Maximum Single Position Loss: -3.94%
  • Maximum Single Profit: +15.78%
  • Net Profit: +1359.21 USDT (+13.59%)
  • Total Trades: 111 (36.04% win rate)
  • Profit Factor: 1.413
  • Maximum Accumulated Loss: 625.02 USDT (-5.85%)
  • Average Profit per Trade: 12.25 USDT (+0.40%)
  • Average Trade Duration: 40 hours

These results are obtained with realistic parameters representing trading conditions observed at major exchanges such as Binance and with realistic trading portfolio usage parameters.

How to Use
Add the script to favorites for easy access.
Apply to the desired timeframe and chart (optimal performance observed on 2h BTC/USDT).
Configure settings using the dropdown choice list in the built-in menu.
Set up alerts to automate strategy positions through web hook with the text: {{strategy.order.alert_message}}

Disclaimer:
Educational and informational tool reflecting Skyrex commitment to informed trading. Past performance does not guarantee future results. Test strategies in a simulated environment before live implementation
Moving Average Convergence / Divergence (MACD)Relative Strength Index (RSI)Stochastic Oscillator

Script de código aberto

No verdadeiro espírito do TradingView, o autor desse script o publicou como código aberto, para que os traders possam compreendê-lo e analisá-lo. Parabéns ao autor! Você pode usá-lo gratuitamente, mas a reutilização desse código em publicações é regida pelas Regras da Casa. Você pode favoritá-lo para usá-lo em um gráfico.

Quer usar esse script no gráfico?


Get access to private PineScript strategies and turn script alerts into orders at your exchange account with easy-to-set up bots

Get free alert bot:
skyrexio.com
Também em:

Aviso legal