Automate a Trading Strategy (Part 2) — Porting RSI to MT5 and Backtesting in OHLC (With Real Pros & Cons)

In Part 1 we built a fast prototype in TradingView (Pine Script + ChatGPT) to learn a very specific skill: not “finding a profitable strategy”, but learning when a backtest is not strong enough to support conclusions.

Now we take the next step: we port the same RSI lab prototype to MetaTrader 5 (MQL5) and test it inside the Strategy Tester using OHLC modelling.

The goal is still the same: contextualize the data. Not chase a green equity curve.

 

Why move from TradingView to MT5?

TradingView is excellent for fast ideation, visual debugging, and rapid iteration. MT5 is closer to an engineering environment: you get more control, more realism, and much better diagnostics.

In simple terms: TradingView helps you build the idea. MT5 helps you stress-test it.

 

The MQL5 RSI Lab Prototype (Pine → MT5 conversion)

This is the EA used in this test. It’s intentionally minimal: entry logic is RSI 30/70 crosses, exits are ATR-based stop/target, and execution is evaluated once per new bar (equivalent to process_orders_on_close behavior in Pine).

//+------------------------------------------------------------------+
//|                                                RSI_Lab_Prototype |
//|                         Pine -> MQL5 conversion (Part 1)         |
//+------------------------------------------------------------------+
#property strict
#include <Trade/Trade.mqh>
CTrade trade;
//------------------------- Inputs ----------------------------------//
input int      rsiLen       = 14;     // RSI Length
input int      overSold     = 30;     // Oversold
input int      overBought   = 70;     // Overbought
input int      atrLen       = 14;     // ATR Length
input double   slR          = 1.0;    // Stop (R in ATR)
input double   tpR          = 1.0;    // Target (R in ATR)
input double   lots         = 0.10;   // Fixed volume
input long     magic        = 20260208;
input int      deviationPts = 20;
//------------------------- Globals ---------------------------------//
int      rsiHandle = INVALID_HANDLE;
int      atrHandle = INVALID_HANDLE;
datetime lastBarTime = 0;
bool IsNewBar()
{
   datetime t0 = iTime(_Symbol, _Period, 0);
   if(t0 != lastBarTime)
   {
      lastBarTime = t0;
      return true;
   }
   return false;
}
double GetBufferValue(const int handle, const int shift)
{
   double v[];
   if(CopyBuffer(handle, 0, shift, 1, v) != 1)
      return EMPTY_VALUE;
   return v[0];
}
int CountMyPositions(int typeFilter = -1)
{
   int count = 0;
   for(int i = PositionsTotal() - 1; i >= 0; --i)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0) continue;
      if(!PositionSelectByTicket(ticket)) continue;
      string sym = PositionGetString(POSITION_SYMBOL);
      long   mg  = (long)PositionGetInteger(POSITION_MAGIC);
      int    typ = (int)PositionGetInteger(POSITION_TYPE);
      if(sym != _Symbol) continue;
      if(mg  != magic)   continue;
      if(typeFilter != -1 && typ != typeFilter) continue;
      count++;
   }
   return count;
}
void CloseMyPositionsByType(int typeToClose)
{
   for(int i = PositionsTotal() - 1; i >= 0; --i)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0) continue;
      if(!PositionSelectByTicket(ticket)) continue;
      string sym = PositionGetString(POSITION_SYMBOL);
      long   mg  = (long)PositionGetInteger(POSITION_MAGIC);
      int    typ = (int)PositionGetInteger(POSITION_TYPE);
      if(sym != _Symbol || mg != magic || typ != typeToClose) continue;
      if(!trade.PositionClose(ticket))
      {
         Print("PositionClose failed. Ticket=", ticket,
               " retcode=", trade.ResultRetcode(),
               " ", trade.ResultRetcodeDescription());
      }
   }
}
void EnforceStopLevel(int posType, double &sl, double &tp)
{
   int stopLevelPts = (int)SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
   if(stopLevelPts <= 0) return;
   double minDist = stopLevelPts * _Point;
   double bid     = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double ask     = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
   if(posType == POSITION_TYPE_BUY)
   {
      if((bid - sl) < minDist) sl = bid - minDist;
      if((tp - bid) < minDist) tp = bid + minDist;
   }
   else if(posType == POSITION_TYPE_SELL)
   {
      if((sl - ask) < minDist) sl = ask + minDist;
      if((ask - tp) < minDist) tp = ask - minDist;
   }
   sl = NormalizeDouble(sl, _Digits);
   tp = NormalizeDouble(tp, _Digits);
}
bool ModifySLTP(const ulong ticket, const double sl, const double tp)
{
   MqlTradeRequest req;
   MqlTradeResult  res;
   ZeroMemory(req);
   ZeroMemory(res);
   req.action   = TRADE_ACTION_SLTP;
   req.symbol   = _Symbol;
   req.position = ticket;
   req.sl       = sl;
   req.tp       = tp;
   req.magic    = magic;
   if(!OrderSend(req, res))
   {
      Print("OrderSend(TRADE_ACTION_SLTP) failed. err=", GetLastError());
      return false;
   }
   if(res.retcode != TRADE_RETCODE_DONE && res.retcode != TRADE_RETCODE_DONE_PARTIAL)
   {
      Print("SLTP modify rejected. retcode=", res.retcode);
      return false;
   }
   return true;
}
void UpdateAllStopsTargets(const double atrValue)
{
   if(atrValue <= 0.0 || atrValue == EMPTY_VALUE) return;
   for(int i = PositionsTotal() - 1; i >= 0; --i)
   {
      ulong ticket = PositionGetTicket(i);
      if(ticket == 0) continue;
      if(!PositionSelectByTicket(ticket)) continue;
      string sym = PositionGetString(POSITION_SYMBOL);
      long   mg  = (long)PositionGetInteger(POSITION_MAGIC);
      int    typ = (int)PositionGetInteger(POSITION_TYPE);
      if(sym != _Symbol || mg != magic) continue;
      double openPrice = PositionGetDouble(POSITION_PRICE_OPEN);
      double sl = 0.0, tp = 0.0;
      if(typ == POSITION_TYPE_BUY)
      {
         sl = openPrice - slR * atrValue;
         tp = openPrice + tpR * atrValue;
      }
      else if(typ == POSITION_TYPE_SELL)
      {
         sl = openPrice + slR * atrValue;
         tp = openPrice - tpR * atrValue;
      }
      sl = NormalizeDouble(sl, _Digits);
      tp = NormalizeDouble(tp, _Digits);
      EnforceStopLevel(typ, sl, tp);
      double oldSL = PositionGetDouble(POSITION_SL);
      double oldTP = PositionGetDouble(POSITION_TP);
      if(MathAbs(oldSL - sl) < (_Point * 0.1) && MathAbs(oldTP - tp) < (_Point * 0.1))
         continue;
      ModifySLTP(ticket, sl, tp);
   }
}
void ExecuteSignals(const bool goLong, const bool goShort)
{
   if(goLong && !goShort)
   {
      CloseMyPositionsByType(POSITION_TYPE_SELL);
      if(CountMyPositions(POSITION_TYPE_BUY) == 0)
      {
         if(!trade.Buy(lots, _Symbol))
            Print("Buy failed. retcode=", trade.ResultRetcode(),
                  " ", trade.ResultRetcodeDescription());
      }
   }
   else if(goShort && !goLong)
   {
      CloseMyPositionsByType(POSITION_TYPE_BUY);
      if(CountMyPositions(POSITION_TYPE_SELL) == 0)
      {
         if(!trade.Sell(lots, _Symbol))
            Print("Sell failed. retcode=", trade.ResultRetcode(),
                  " ", trade.ResultRetcodeDescription());
      }
   }
}
int OnInit()
{
   trade.SetExpertMagicNumber(magic);
   trade.SetDeviationInPoints(deviationPts);
   rsiHandle = iRSI(_Symbol, _Period, rsiLen, PRICE_CLOSE);
   atrHandle = iATR(_Symbol, _Period, atrLen);
   if(rsiHandle == INVALID_HANDLE || atrHandle == INVALID_HANDLE)
   {
      Print("Failed to create indicator handles.");
      return INIT_FAILED;
   }
   lastBarTime = 0;
   return INIT_SUCCEEDED;
}
void OnDeinit(const int reason)
{
   if(rsiHandle != INVALID_HANDLE) IndicatorRelease(rsiHandle);
   if(atrHandle != INVALID_HANDLE) IndicatorRelease(atrHandle);
}
void OnTick()
{
   if(!IsNewBar()) return;
   double rsi1 = GetBufferValue(rsiHandle, 1);
   double rsi2 = GetBufferValue(rsiHandle, 2);
   double atr1 = GetBufferValue(atrHandle, 1);
   if(rsi1 == EMPTY_VALUE || rsi2 == EMPTY_VALUE || atr1 == EMPTY_VALUE)
      return;
   bool goLong  = (rsi1 > overSold)   && (rsi2 <= overSold);
   bool goShort = (rsi1 < overBought) && (rsi2 >= overBought);
   ExecuteSignals(goLong, goShort);
   UpdateAllStopsTargets(atr1);
}

 

 

Backtesting in MT5: what OHLC means (and what it does NOT mean)

In this Part 2, results were tested using OHLC modelling inside MT5. That means the tester reconstructs price movement using candle values:

  • Open
  • High
  • Low
  • Close

This is a major step up from “quick chart testing”, but it is still not the highest-fidelity simulation available.

What changes compared to Real Ticks backtesting

With Real Ticks you have a much more precise reconstruction of intrabar movement. This matters when:

  • TP and SL are both inside the same candle range
  • execution depends on micro moves (especially on low timeframes)
  • spread is variable and impacts fills

OHLC is a very useful intermediate model because it is fast and stable for testing logic. But it cannot reproduce the true tick-by-tick path of price.

Lab rule: OHLC is excellent for validating structure and debugging logic. Real Ticks is where you start measuring execution realism.

 

Why MT5 is powerful for strategy research (Pros)

Let’s be direct: MT5 is not as “friendly” as TradingView. But it offers capabilities that are much closer to professional research.

1) MT5 is free (and the data pipeline is simple)

MetaTrader 5 is free. You can download it, connect to a broker, and immediately start downloading historical data.

In contrast, TradingView is an outstanding platform, but many useful data features and professional-grade market access require paid plans.

2) Data is easier to access (broker-driven)

MT5 pulls historical bars and often tick data directly from the broker. That makes it very practical when you want to:

  • run tests quickly
  • avoid external data pipelines
  • standardize your workflow across symbols

3) Higher granularity options

MT5 gives you multiple modelling modes (including Real Ticks). Even when you start in OHLC, you’re already inside an ecosystem that supports higher fidelity.

4) Much more realistic modelling (spread, commission, slippage)

MT5 allows you to test with:

  • spread (and more realistic bid/ask behaviour)
  • commissions
  • slippage (via settings and execution assumptions)
  • execution constraints such as stop level distance

Even if it’s still a simulation, it pushes you closer to reality than most “chart backtests”.

5) Advanced strategy design is possible

MQL5 is a full programming language. That means you can build:

  • dynamic risk models
  • multi-symbol logic
  • portfolio-level exposure controls
  • session filters and calendar filters
  • position management logic that is not possible in Pine

6) MT5 reports are significantly more diagnostic

This is one of the most underrated advantages.

MT5 gives you deep report metrics such as:

  • Profit Factor
  • Expected Payoff
  • Sharpe Ratio
  • Recovery Factor
  • Absolute / Relative Drawdown
  • AHPR / GHPR
  • Longest win/loss streak
  • Trade distribution by hour / day

These are not “nice to have”. They help you diagnose whether a strategy is structurally fragile, even when the equity curve looks fine.

 

The real drawbacks of MT5 (Cons)

1) MT5 is harder than TradingView

There’s no sugar-coating it: MT5 has a steeper learning curve. The Strategy Tester has more options, the platform is less intuitive, and mistakes are easier to make.

2) MQL5 code is more complex

Even a “simple RSI strategy” becomes longer in MQL5 because you need to handle:

  • position management
  • broker constraints (stop levels, digits, contract specs)
  • trade execution results / retcodes
  • indicator handles and buffers

This is good for realism, but it slows iteration.

3) AI assistance is less reliable than in Pine

Pine Script is a small domain-specific language. ChatGPT tends to perform extremely well in Pine because the scope is narrow.

MQL5 is larger and more error-prone. AI can still help a lot, but:

  • the code is longer,
  • platform-specific quirks matter,
  • small mistakes can silently change results.

4) Data quality depends on the broker

This is a critical point. MT5 data is often good, but it is not always institutional-grade. Different brokers can have:

  • different tick histories
  • different spreads
  • different session definitions
  • different price feeds

For serious research, you eventually need a controlled data pipeline (and that’s where Part 3 is going).

5) You can still get false confidence if you don’t control assumptions

Even with a better tester, you can still fool yourself if:

  • your sample is too short,
  • your modelling mode is too optimistic,
  • you ignore slippage and spread sensitivity,
  • you optimize parameters aggressively.

 

Results of the RSI Strategy on SP500, m1
Results of the RSI Strategy on SP500, m1
Results of the RSI Strategy on SP500, m1
Results of the RSI Strategy on SP500, m1

 

Analyzing the MT5 results (OHLC test)

Le’ts see now the results of this same test.  On the surface, the strategy may look “active” and structured: it generates trades, it has defined exits, and it produces a full equity curve.

But the report metrics reveal the truth quickly:

  • Profit Factor ≈ 0.52 → losses dominate profits.
  • Expected Payoff is negative → average value per trade is structurally negative.
  • Sharpe Ratio is strongly negative → risk-adjusted performance is poor.
  • Win rate is low (~31%) → and the payoff structure does not compensate for it.
  • Loss streaks are long (many consecutive losses) → typical of naive mean-reversion in trending regimes.

Even more interesting: the drawdown percentage is small in this specific run. That does not mean the strategy is safe — it means the position sizing and test window did not expose tail risk.

Engineering interpretation: this is not a strategy that is “almost working”. It is a strategy that is working exactly as expected for a naive RSI mean-reversion rule: it loses in regimes where mean-reversion is not dominant.

 

What this Part 2 actually teaches

Part 2 is not about proving RSI works. It’s about learning a workflow:

  • TradingView builds the prototype quickly.
  • MT5 forces the prototype into a more realistic execution environment.
  • The report gives you diagnostic metrics that are hard to ignore.

This is the professional shift: you stop asking “Is it profitable?” and you start asking:

  • Is this robust?
  • Is this sensitive to regime?
  • Is this result an artifact of modelling?
  • Is the sample size meaningful?

 

Part 3 preview: testing it properly and starting an optimization process

In Part 3, we’ll take this one step further and move toward a research workflow that is closer to professional standards. Because the objective of this series is not to create a “nice backtest”. It’s to build a process that produces truthful measurements. See you in part 3.

The Trading Engineer
The Trading Engineer
For over five years I’ve used trading as a real laboratory: I design rule-based strategies, test them on real data with code, bots, and tools I build myself, and deploy them on funded accounts with a verifiable track record. I hold three technical degrees, all completed with top grades, and I bring the same rigor into the markets. I founded Trading Engineering Lab to document this work transparently: no shortcuts, no easy promises, no “signals” or improvised courses—just numbers, journaling, rigorous analysis, and continuous system improvement. I write about systematic trading, risk management, statistical validation of strategies, and how discipline in trading and in life shapes performance. For me, trading is an experiment, not a lottery ticket. If you’re looking for hype, I’m probably not the right fit. If you’re interested in models, data, and process, welcome to the lab.

Artículos relacionados

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subscribe to our newsletter

To stay up to date with the latest news, offers and special announcements.

I have read and agree to the terms of use page and privacy policy provided in accordance with Article 13 of EU Regulation 679/2016 and I consent to email marketing purposes.

Trending Now