8 min read

The Easiest Way to Add the RSI Indicator to Your MetaTrader 5 EA

Learn how to add the RSI technical indicator straight into your Expert Advisor. It's pretty straightforward with this tutorial!
The Easiest Way to Add the RSI Indicator to Your MetaTrader 5 EA
Title Image for the Series, "Build Your Own MetaTrader 5 Expert Advisor"

Adding the RSI (or Relative Strength Indicator) to your MT5 Expert Advisor can be a great way to give your EA insight into market conditions. The RSI is one of the world's most popular technical indicators, and it is used by many traders to identify overbought and oversold conditions.

However, actually GETTING the value of the RSI from MetaTrader 5 in a format your EA can use is…non-intuitive.

In this article, I’ll show you the easiest way to get it and add it to the rest of your trading bot.


About This Series

In this series, I cover everything you need to build your own advanced Expert Advisor from scratch. I cover:

  • How to get started
  • Using built in technical indicators from MetaTrader
  • Making your EA autotrade
  • Adding some simple-yet-powerful risk management techniques to your EA
  • Backtesting and Optimizing your soon-to-be-awesome algorithm
  • Adding some advanced features

All of the code that I use is available on my public GitHub repo, and each episode contains working code snippets you can immediately use in your own trading bot.

If you’d like some more general help, join our Discord server here, and if you prefer content in a video format, you can check out my YouTube channel here.

Working Code for the Series on GitHub

Get the complete, working code for the series on my GitHub here.

GitHub - jimtin/build-your-own-mt5-ea: Learn how to build your own MetaTrader 5 Expert Advisor from Scratch!
Learn how to build your own MetaTrader 5 Expert Advisor from Scratch! - jimtin/build-your-own-mt5-ea

In This Episode

By the end of this episode, you’ll have added the RSI technical indicator to your trading bot! Not only that, but I’ll show you the easiest way to modify whether you want your RSI to be the latest value or a previous one.

What You’ll Need to Complete this Episode

  1. All your settings correct for autotrading on MetaTrader 5. Follow this article, or this YouTube video to see how.
  2. A trading bot with at least the functions OnInit() , OnDeinit() , and OnTick() . I recommend you check out my previous episode to see this.
  3. A MetaTrader 5 account to use. I strongly recommend a paper trading account.

If you want to learn more about the RSI, check out this article or this video for more.

💡
All trading is at your own risk, and in no way shape or form should you consider any of what I write to be investment or trading advice. My goal is to simply educate and inform, not provide investment advice.

Getting the RSI Value

A Note On Getting Built In Indicators in MT5

MT5 comes with quite a number of built in indicators. You can find them in the Insert -> Indicators menu.

The problem if you’re building an EA (or Expert Advisor) is that the MQL language doesn’t make them super easy to access.

Instead, you have to follow a multi-step process that looks a bit like this:

  1. Create a place to store the indicator values
  2. Tell MT5 what value to calculate the indicator on (Open, High, Low, Close etc.)
  3. Copy the calculated value in the storage location in step 1
  4. Retrieve the value you’ve copied
  5. Return it from your function

If you’d like that list in more technically correct language, you need to:

  1. Initialize an array to use as a buffer
  2. Specify what static property you want to calculate the indicator on
  3. Create a handle to that calculated value
  4. Use the handle to copy the array into the previously initialized buffer
  5. Retrieve the value from the buffer
  6. Return the function

It can honestly be a bit overwhelming at first. Especially if you’ve come from higher level languages / platforms that make this process substantially easier.

However, here we are.

Create the GetRSI Function

Here’s how you follow this process to get the RSI. If you’ve been following this series, you’ll be using the rsi_trading_bot_tutorial.mq5

Above the OnTick() function and below the OnDeinit() function, create a new function as follows:

double GetRSI(){ 
 
}

This function will handle all logic related to getting the RSI value you want to use in your trading bot.

Fill Out The RSI Function

Inside this function, update it with the code below so that your GetRSI() function looks like this:

//+------------------------------------------------------------------+
//| GetRSI                                                           |
//+------------------------------------------------------------------+
double GetRSI()
{
    // Initialize a buffer
    double rsiBuffer[];
    // Make it into an array
    ArraySetAsSeries(rsiBuffer, true);
    // Get the RSI Handle
    int rsiHandle = iRSI(_Symbol, _Period, 14, PRICE_CLOSE);
    // If the handle is invalid, return 0
    if (rsiHandle == INVALID_HANDLE)
    {
        return(0);
    }
    // Copy the RSI values to the buffer
    int rsiCount = CopyBuffer(rsiHandle, 0, 0, 1, rsiBuffer);
    // If the copy failed, return 0
    if (rsiCount == 0)
    {
        return(0);
    }
    // Get the actual RSI value
    double rsi = rsiBuffer[0];
    // Return the RSI value
    return(rsi);
}

As you can see, this function:

  1. Initializes a buffer called rsiBuffer
  2. Turns it into an array
  3. Retrieves the handle for the RSI using the built in iRSI() function from MQL5
  4. Extracts the latest value
  5. Returns that value to end the function

Adding the RSI to Your EA

Let’s add the output from this function to your EA. We will do this by inserting it into the OnTick() function we built in the previous episode.

Currently, this function is simply printing out the most recently close price for whatever asset you are tracking. Now we will add in another value, which will be the current RSI.

Update your OnTick() function so that it looks like this:

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{

    double close = iClose(_Symbol, _Period, 0);
    double rsi = GetRSI();
    Print("Close Price: ", close, " RSI: ", rsi);
}

Compile your code update and run it in your MT5.


A Common Challenge with This RSI for Your EA

Although we’ve technically got an RSI up and running on your Expert Advisor, if you’re into trading, you might find that the current implementation isn’t that useful.

To see what I mean, have a look at this GIF.

You can probably see that not only is the current close jumping around, but so is the RSI.

Why Is the RSI Jumping Around?

The reason for this is that we’ve applied the RSI to the current close, which will change with every price.

The problem is that

Many algorithms actually use the PREVIOUS candles close to calculate their entry and exit points.

Let’s update your RSI function to make this work.

We will be adding two parts — an input to choose whether we want the current RSI or the previous value, and then updating the actual RSI function.

Add an Input to Your Expert Advisor

First, near the top of your EA, under the intro section, put the following line:

input bool liveRSIPrice = false;                    //Use the live RSI price?

This specifies an input that you can choose when you run your bot. The input allows you to use the live RSI price (select true ) or the previous candle (select false )

Update the RSI Function

Now we’re going to return to the GetRSI() function and update it. There’s two parts to this update.

  1. We need to update the array so that it copies the last two values of the RSI
  2. We need to modify the function so that it provides the correct RSI base on the live price or previous price input

Update your RSI Function so that it looks like this:

//+------------------------------------------------------------------+
//| GetRSI                                                           |
//+------------------------------------------------------------------+
double GetRSI()
{
    // Initialize a buffer
    double rsiBuffer[];
    // Make it into an array
    ArraySetAsSeries(rsiBuffer, true);
    // Get the RSI Handle
    int rsiHandle = iRSI(_Symbol, _Period, 14, PRICE_CLOSE);
    // If the handle is invalid, return 0
    if (rsiHandle == INVALID_HANDLE)
    {
        return(0);
    }
    // Copy the RSI values to the buffer
    int rsiCount = CopyBuffer(rsiHandle, 0, 0, 2, rsiBuffer);
    // If the copy failed, return 0
    if (rsiCount == 0)
    {
        return(0);
    }
    // Get the actual RSI value
    if(liveRSIPrice == true)
    {
        double rsi = rsiBuffer[0];
        return(rsi);
    }else{
        double rsi = rsiBuffer[1];
        return(rsi);
    }
}

Recompile and Check It Out

If you recompile your RSI Trading EA now, you’ll be able to watch the results.

When you set your live price to true the RSI will change every time the price moves.

When you set your live price to false the RSI will only change when a new candle appears.

Pretty cool!


Wrapping Up

Nice work on getting to the end of the episode! You’ve now got a working RSI indicator you pull directly into your trading bot to make trading decisions with your EA.

In the next episode, I’ll show you how to start identifying entry and exit points for trades using the RSI.

List of Articles in this Series

  1. Build Your Own AutoTrading MetaTrader 5 Expert Advsior
  2. The Easiest Way to Add the RSI Indicator to Your MetaTrader 5 EA
  3. The Easiest RSI Algorithm for Your MetaTrader Expert Advisor
  4. The Easiest Way to Place BUY and Sell Orders with your MetaTrader EA
  5. The Simplest Way to Manage Your Expert Advisor Trades on MetaTrader
  6. Four Simple Steps to Backtest and Optimize Your EA on MetaTrader 5

Connect With Me

My name is James, and you’ll often see me online using the AppnologyJames handle. Although my background and training is in Cyber Security, I’ve spend the last few years building trading algorithms for clients, along with a powerful market analysis platform called TradeOxy.

I love hearing from my readers and viewers, so feel free to reach out and connect with me:

Complete Code for this Episode

//+------------------------------------------------------------------+
//|                                  RSI_EA_from_TradeOxy.mq5        |
//|                              AppnologyJames, TradeOxy.com        |
//|                                  https://www.tradeoxy.com        |
//+------------------------------------------------------------------+


input bool liveRSIPrice = false;                // Use live RSI price?

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // Print the name of the Expert Advisor and a Welcome message
    Print("RSI Trading Bot Expert Advisor from TradeOxy.com");
    // Return value of initialization
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // Deinitialization code
    Print("Expert advisor deinitialized. Reason: ", reason);
}


//+------------------------------------------------------------------+
//| GetRSI                                                           |
//+------------------------------------------------------------------+
double GetRSI()
{
    // Initialize a buffer
    double rsiBuffer[];
    // Make it into an array
    ArraySetAsSeries(rsiBuffer, true);
    // Get the RSI Handle
    int rsiHandle = iRSI(_Symbol, _Period, 14, PRICE_CLOSE);
    // If the handle is invalid, return 0
    if (rsiHandle == INVALID_HANDLE)
    {
        return(0);
    }
    // Copy the RSI values to the buffer
    int rsiCount = CopyBuffer(rsiHandle, 0, 0, 2, rsiBuffer);
    // If the copy failed, return 0
    if (rsiCount == 0)
    {
        return(0);
    }
    // Get the actual RSI value
    if(liveRSIPrice == true)
    {
        double rsi = rsiBuffer[0];
        return(rsi);
    }else{
        double rsi = rsiBuffer[1];
        return(rsi);
    }
}


//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{

    double close = iClose(_Symbol, _Period, 0);
    double rsi = GetRSI();
    Print("Close Price: ", close, " RSI: ", rsi);
}