Blog / Code & convert EAs · Pine Script · MQL5 · Expert Advisors

Converting a Pine Script Strategy to MQL5, Step by Step

Learn how to convert a Pine Script strategy into an MQL5 EA, with practical examples covering signals, indicators, entries, exits, and testing.

· 5 min read

A Pine Script strategy can produce good backtest results on TradingView but behave differently after conversion into MetaTrader 5.

Copying its entry conditions into MQL5 is not enough. You must also reproduce its calculation timing, indicator values, position management and order behaviour.

This guide demonstrates the process using a simple moving average crossover strategy.

1. Identify the Original Strategy Rules

Start by understanding exactly what the Pine Script strategy does.

Consider this example:

Pine Script
//@version=6
strategy("MA Crossover", overlay=true)

fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 30)

longCondition = ta.crossover(fastMA, slowMA)
shortCondition = ta.crossunder(fastMA, slowMA)

if longCondition
    strategy.entry("Buy", strategy.long)

if shortCondition
    strategy.entry("Sell", strategy.short)

The strategy:

  • Calculates a 10-period simple moving average.
  • Calculates a 30-period simple moving average.
  • Opens a long trade when the fast average crosses above the slow average.
  • Opens a short trade when the fast average crosses below the slow average.

Before converting it, identify the settings that affect its behaviour:

Setting What to check
Instrument and timeframe Which symbol and chart period does it use?
Indicators Which indicators and parameters are required?
Entry and exit rules What opens and closes trades?
Position sizing Fixed volume, percentage risk or another method?
Pyramiding Can it add entries in the same direction?
Execution timing Does it evaluate closed candles or intrabar movements?

Don't assume the visible entry conditions describe the entire strategy. Inputs, exit rules and execution settings can all affect its results.

2. Match the Signal Timing

By default, a Pine Script strategy calculates at the closing update of a bar. A market order generated by that calculation is normally filled at the next available tick, typically the following bar's open in historical testing.

An MQL5 Expert Advisor uses event handlers such as OnTick(). Its logic can run when new quotes arrive, rather than automatically following Pine Script's default once-per-bar behaviour.

If the original strategy uses completed candles, the MQL5 version should detect a new bar and evaluate the candle that has just closed.

MQL5
bool IsNewBar()
{
   static datetime lastBarTime = 0;

   datetime currentBarTime = iTime(_Symbol, _Period, 0);

   if(currentBarTime == 0)
      return false;

   if(currentBarTime != lastBarTime)
   {
      lastBarTime = currentBarTime;
      return true;
   }

   return false;
}

This function detects the first received tick of a new candle. The EA can then evaluate the previous completed candle.

Check the original Pine settings before implementing this. Options such as calc_on_every_tick and process_orders_on_close can change the strategy's execution behaviour. Pine Script vs MQL5: How the Execution Models Differ explains each one.

3. Create MQL5 Indicator Handles

Pine Script calculates a moving average directly:

Pine Script
fastMA = ta.sma(close, 10)

In MQL5, you create a moving average indicator using iMA(). However, iMA() returns an indicator handle, not the calculated value. You retrieve the values with CopyBuffer() (more in Indicator Handles and CopyBuffer Explained).

Declare the handles:

MQL5
int fastMAHandle = INVALID_HANDLE;
int slowMAHandle = INVALID_HANDLE;

Create them in OnInit():

MQL5
int OnInit()
{
   fastMAHandle = iMA(
      _Symbol, _Period, 10, 0, MODE_SMA, PRICE_CLOSE
   );

   slowMAHandle = iMA(
      _Symbol, _Period, 30, 0, MODE_SMA, PRICE_CLOSE
   );

   if(fastMAHandle == INVALID_HANDLE ||
      slowMAHandle == INVALID_HANDLE)
   {
      Print("Failed to create moving average handles.");
      return INIT_FAILED;
   }

   return INIT_SUCCEEDED;
}

Release the handles when the EA is removed:

MQL5
void OnDeinit(const int reason)
{
   if(fastMAHandle != INVALID_HANDLE)
      IndicatorRelease(fastMAHandle);

   if(slowMAHandle != INVALID_HANDLE)
      IndicatorRelease(slowMAHandle);
}

This gives the EA access to the two moving averages without manually implementing their calculations.

4. Convert the Crossover Conditions

Pine Script's ta.crossover() checks whether the current value is above the comparison series while the previous value was below or equal to it.

The equivalent MQL5 logic is:

MQL5
fastCurrent > slowCurrent &&
fastPrevious <= slowPrevious

For a downward crossover:

MQL5
fastCurrent < slowCurrent &&
fastPrevious >= slowPrevious

First, retrieve the two most recently completed indicator values:

MQL5
double fastValues[2];
double slowValues[2];

if(CopyBuffer(fastMAHandle, 0, 1, 2, fastValues) != 2)
   return;

if(CopyBuffer(slowMAHandle, 0, 1, 2, slowValues) != 2)
   return;

There is an important detail about array order. CopyBuffer() places the oldest copied value at the beginning of the physical array.

Because the request starts at bar 1 and copies two values:

  • fastValues[0] contains bar 2's value.
  • fastValues[1] contains bar 1's value.

Now evaluate the signals:

MQL5
bool buySignal =
   fastValues[1] > slowValues[1] &&
   fastValues[0] <= slowValues[0];

bool sellSignal =
   fastValues[1] < slowValues[1] &&
   fastValues[0] >= slowValues[0];

This reproduces the crossover conditions using completed candles rather than changing intrabar values.

5. Convert Pine Entries into MQL5 Trades

Pine Script uses commands such as:

Pine Script
strategy.entry("Buy", strategy.long)
strategy.entry("Sell", strategy.short)

MQL5 can send corresponding trade requests using the CTrade class:

MQL5
#include <Trade/Trade.mqh>

CTrade trade;

input double Lots = 0.10;

// Buy request
trade.Buy(Lots, _Symbol);

// Sell request
trade.Sell(Lots, _Symbol);

However, the position-management behaviour needs attention.

Pine Script's strategy.entry() can automatically reverse an existing position when an opposite entry is generated. MQL5 behaviour depends on the account's position system and the requests sent by the EA.

  • Netting accounts: Maintain one net position per symbol. Opposite trades can reduce, close or reverse that exposure.
  • Hedging accounts: Can maintain multiple independent positions, including opposite positions.

If the original strategy reverses positions, implement that behaviour deliberately. Don't assume that calling Buy() or Sell() will reproduce it on every account type.

Also, a successful CTrade method return does not by itself guarantee execution. Inspect the server return code and resulting trade activity.

6. Build the Converted Expert Advisor

The following example combines the main conversion steps into a basic moving average crossover EA.

It:

  • Uses 10- and 30-period simple moving averages.
  • Checks signals once per new candle.
  • Uses the two most recently completed candles.
  • Closes an opposite position before opening a new one.
  • Checks trade-server return codes.

Important: This example assumes a netting account and that the traded symbol is reserved for this EA. It uses fixed lot sizing and does not include stop-loss, take-profit or risk-management rules. Those must be added to match a more complete original strategy.

MQL5
#include <Trade/Trade.mqh>

CTrade trade;

input double Lots = 0.10;
input ulong MagicNumber = 16001;

int fastMAHandle = INVALID_HANDLE;
int slowMAHandle = INVALID_HANDLE;

bool IsNewBar()
{
   static datetime lastBarTime = 0;

   datetime currentBarTime = iTime(_Symbol, _Period, 0);

   if(currentBarTime == 0 || currentBarTime == lastBarTime)
      return false;

   lastBarTime = currentBarTime;
   return true;
}

int OnInit()
{
   // This example is designed for netting accounts.
   if((ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE)
      == ACCOUNT_MARGIN_MODE_RETAIL_HEDGING)
   {
      Print("This example requires a netting account.");
      return INIT_FAILED;
   }

   fastMAHandle = iMA(
      _Symbol, _Period, 10, 0, MODE_SMA, PRICE_CLOSE
   );

   slowMAHandle = iMA(
      _Symbol, _Period, 30, 0, MODE_SMA, PRICE_CLOSE
   );

   if(fastMAHandle == INVALID_HANDLE ||
      slowMAHandle == INVALID_HANDLE)
   {
      Print("Failed to create moving average handles.");
      return INIT_FAILED;
   }

   trade.SetExpertMagicNumber(MagicNumber);

   return INIT_SUCCEEDED;
}

void OnDeinit(const int reason)
{
   if(fastMAHandle != INVALID_HANDLE)
      IndicatorRelease(fastMAHandle);

   if(slowMAHandle != INVALID_HANDLE)
      IndicatorRelease(slowMAHandle);
}

bool TradeRequestAccepted()
{
   uint retcode = trade.ResultRetcode();

   return (retcode == TRADE_RETCODE_DONE ||
           retcode == TRADE_RETCODE_DONE_PARTIAL);
}

void ExecuteSignal(int signal)
{
   if(PositionSelect(_Symbol))
   {
      ENUM_POSITION_TYPE positionType =
         (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);

      // No action if the existing position matches the signal.
      if((signal == 1 && positionType == POSITION_TYPE_BUY) ||
         (signal == -1 && positionType == POSITION_TYPE_SELL))
         return;

      // Close the opposite position before reversing.
      if(!trade.PositionClose(_Symbol) || !TradeRequestAccepted())
      {
         Print("Position close failed: ",
               trade.ResultRetcodeDescription());
         return;
      }

      // Do not open the opposite trade if a position remains.
      if(PositionSelect(_Symbol))
      {
         Print("Position has not been fully closed.");
         return;
      }
   }

   bool requestSent = false;

   if(signal == 1)
      requestSent = trade.Buy(Lots, _Symbol);

   if(signal == -1)
      requestSent = trade.Sell(Lots, _Symbol);

   if(!requestSent || !TradeRequestAccepted())
   {
      Print("Trade request failed: ",
            trade.ResultRetcodeDescription());
   }
   else
   {
      Print("Trade request accepted: ",
            trade.ResultRetcodeDescription());
   }
}

void OnTick()
{
   if(!IsNewBar())
      return;

   double fastValues[2];
   double slowValues[2];

   if(CopyBuffer(fastMAHandle, 0, 1, 2, fastValues) != 2)
   {
      Print("Could not copy fast MA values.");
      return;
   }

   if(CopyBuffer(slowMAHandle, 0, 1, 2, slowValues) != 2)
   {
      Print("Could not copy slow MA values.");
      return;
   }

   bool buySignal =
      fastValues[1] > slowValues[1] &&
      fastValues[0] <= slowValues[0];

   bool sellSignal =
      fastValues[1] < slowValues[1] &&
      fastValues[0] >= slowValues[0];

   if(buySignal)
      ExecuteSignal(1);

   if(sellSignal)
      ExecuteSignal(-1);
}

This demonstrates the conversion of the core crossover rules. It is not a complete reproduction of every TradingView strategy setting.

If the original strategy uses hedging, multiple entries, partial exits or pending orders, the position-management code must be adapted.

7. Compare the Converted EA with the Original

Once the MQL5 version compiles, don't assume the conversion is correct just because it produces trades.

Compare both versions using matching conditions:

  • Same instrument and timeframe.
  • Same indicator periods and applied prices.
  • Same entry and exit rules.
  • Same candle timing.
  • Same position sizing and pyramiding settings.
  • Comparable historical periods and price data.
  • Equivalent spread, commission and slippage assumptions where available.

Compare entry and exit timestamps, not just the final result. Investigate the first point where the trade histories diverge; Why Your Pine Backtest and MT5 Backtest Don't Match walks through how.

TradingView's broker emulator and the MT5 Strategy Tester do not necessarily simulate fills in the same way. Even with real-tick testing in MT5, identical results are not guaranteed.

8. Common Conversion Mistakes

Problem What to check
Too many trades Whether signals are evaluated on every tick instead of completed candles
Missing crossover signals Crossover conditions and CopyBuffer() return counts
Entries occur one candle late Pine execution settings and MQL5 bar shifts
Different trade direction Signal conditions and reversal handling
Different trade count Pyramiding and position-management rules
Different backtest results Historical data, spreads, commissions and execution assumptions
EA sends requests but no trade opens Trade-server return code and description

Conclusion

Converting a Pine Script strategy to MQL5 requires more than translating its conditions into another programming language.

You must reproduce the original indicator calculations, signal timing, order handling and position-management rules.

Start with a clear understanding of the Pine strategy, convert its indicators and signals, implement the trade logic, and compare both versions using equivalent testing conditions.

A successful conversion should preserve the intended trading behaviour, not simply produce code that compiles.

PositionAlpha's Pine Script to MQL5 converter converts TradingView indicators (Pine Script v4, v5 and v6) into MT5 indicators and reports what it changed or left out. From a strategy() script it converts the calculations and plots, not the order logic. For the trading rules, describe them in the Bot Builder to get an MT5 Expert Advisor. Compile and test either result in MT5 before you rely on it.

Build a bot from your idea

Describe your trading idea and the AI writes MT4 or MT5 code for you to review and test, with a plain-English explanation and setup steps. Your first bot is free.

More from the blog