From Trading Strategy to MQL5 Code: How to Create a Forex Trading Bot Using ChatGPT and MQL5 Part 1

Sat Oct 31 2026

From Trading Strategy to MQL5 Code: How to Create a Forex Trading Bot Using ChatGPT and MQL5 Part 1

Introduction: Why Do Traders Need Automated Trading?

Whether you have been trading Forex for years or you are just starting your trading journey, you may already have a trading strategy. You might know exactly when to enter a trade, where to place your stop-loss, and when to take profit.

But have you ever missed a trading opportunity simply because you were not in front of your computer?

Perhaps you were sleeping, working, travelling, or busy with something else. Forex markets operate 24 hours a day, five days a week, and manually monitoring every market movement is not always possible.

This is where automated trading becomes useful.

Instead of executing every trade manually, you can convert your trading strategy into computer instructions using code. This code can then be connected to your trading platform and account through an Expert Advisor (EA).

You can also run your automated system on a Virtual Private Server (VPS), which is a remote computer that can keep your trading platform running even when your personal computer is switched off. This allows your EA to monitor the market and execute its programmed rules without requiring you to sit in front of the screen.

However, automation does not mean that you will never miss a trade or experience technical problems. Your system still depends on a stable platform, internet connectivity, broker execution, and correctly programmed rules.

In this practical chapter, we will learn how to take a simple Forex trading strategy, convert it into measurable rules, and use an AI tool such as ChatGPT to generate MQL5 code for MetaTrader 5.

Even if you are a complete beginner with no programming experience, this tutorial will help you understand how a trading strategy can become an automated trading system.

Let's get started.

Step 1: Choose a Trading Strategy and Convert It into Clear Rules

Before building an automated trading system, the first thing you need to do is write your trading strategy into clear and measurable rules.

You may already have a strategy that you use manually. However, a computer cannot understand general instructions such as "enter when momentum is strong" or "buy when the breakout looks good." It needs specific conditions that can be converted into code.

To understand this practically, let's take an example of a strategy and learn how to write its rules.

Our Example Strategy: New York Opening Range Breakout with Momentum Confirmation

For this tutorial, we will use Gold (XAUUSD) on the 30-minute chart, following a New York Opening Range Breakout strategy.

First, we identify the first 30-minute candle of the New York trading session and mark its high and low. These two levels become our opening range.

Next, we wait for the market to break above or below this range. However, we don't want to enter simply because the price breaks a level. False breakouts can occur, so we need additional confirmation.

For this reason, we will use two technical conditions.

ADX (Average Directional Index) above 20:

This is our momentum filter. We want ADX to be above 20 to confirm sufficient market strength. ADX measures trend strength, not direction.

5 EMA and 20 EMA crossover:

This is our directional confirmation. For a buy trade, the 5 EMA must cross above the 20 EMA. For a sell trade, the 5 EMA must cross below the 20 EMA. The crossover must happen before our entry.

Once these conditions are satisfied, we wait for a 5-minute candle to close beyond the opening range. This candle-close confirmation helps us avoid entering on a temporary price movement outside the range.

For risk management, we will place the stop-loss at the opposite side of the opening 30-minute candle and use a 1:2 risk-to-reward ratio for our take-profit. This means that for every unit of money we risk, our target profit will be two units.

This is the complete trading idea we will use throughout our practical example.

Now Let's Write Our Trading Strategy into Rules

Instrument: XAUUSD (Gold)

Trading Session: New York session

Opening Range Timeframe: 30 minutes

Entry Confirmation Timeframe: 5 minutes

Opening Range Rules

  1. Identify the first 30-minute candle of the New York session.

  2. Mark its high and low as the opening range levels.

  3. Wait for the opening candle to close before considering an entry.

Buy Entry Rules

  1. Price must break above the opening range high.

  2. A 5-minute candle must close above the opening range high.

  3. ADX must be above 20.

  4. The 5 EMA must have already crossed above the 20 EMA before entry.

  5. Once the 5-minute candle closes above the range and all conditions are satisfied, enter the buy trade.

Sell Entry Rules

  1. Price must break below the opening range low.

  2. A 5-minute candle must close below the opening range low.

  3. ADX must be above 20.

  4. The 5 EMA must have already crossed below the 20 EMA before entry.

  5. Once the 5-minute candle closes below the range and all conditions are satisfied, enter the sell trade.

Stop-Loss Rules

  • Buy: Stop-loss at the low of the opening 30-minute candle.
  • Sell: Stop-loss at the high of the opening 30-minute candle.

Take-Profit Rules

  • Risk-to-reward ratio: 1:2.
  • The take-profit distance will be twice the distance between the entry price and the stop-loss.

Why Are We Writing Everything Down?

Now we have converted our trading idea into specific instructions. We know which instrument to trade, when to identify the opening range, which indicators to use, what confirms an entry, and where to place the stop-loss and take-profit.

This is exactly how you should document your own trading strategy before automating it. Every condition must be clear enough that a computer can follow it without guessing.

Step 2: Convert Your Trading Strategy into MQL5 Code Using ChatGPT

Now that we have clearly defined our trading strategy and written down all its entry, exit, and risk management rules, the next step is to convert those rules into MQL5 code.

You do not necessarily need programming experience to get started. AI tools such as ChatGPT and Claude can help you convert your trading strategy into code.

For this practical example, we will use ChatGPT.

1. Give Your Strategy Rules to ChatGPT

Open ChatGPT and provide the actual rules of our New York Opening Range Breakout strategy that we defined in the previous step.

Ask ChatGPT to convert these rules into an MQL5 Expert Advisor (EA) for MetaTrader 5.

Make sure you include all the important conditions, such as the opening range, ADX confirmation, EMA crossover, entry conditions, stop-loss, and take-profit. The more clearly you explain your strategy, the easier it is for the AI to understand what you want to automate.

2. ChatGPT Generates the MQL5 Code

After submitting our strategy rules, ChatGPT will generate the MQL5 code for our automated trading system.

For this tutorial, we have prepared an example of the code based on our New York Opening Range Breakout strategy.

Our New York Opening Range Breakout Expert Advisor (MQL5 Code)

The following is an initial example of MQL5 code for our strategy. You can copy it and use it for learning and practice.

//+------------------------------------------------------------------+ //| New York Opening Range Breakout - XAUUSD | //| MetaTrader 5 Expert Advisor | //+------------------------------------------------------------------+ #property strict #property version "1.00"

#include <Trade/Trade.mqh>

CTrade trade;

//--- Trading settings input double FixedLotSize = 0.01; input ulong MagicNumber = 9302026; input int MaxTradesPerSession = 1; input int MaximumDeviationPoints = 30;

//--- Session settings input int BrokerUTCOffsetHours = 2; // Example: UTC+2 input int SessionStartHour = 9; // New York fixed EST: 09:30 input int SessionStartMinute = 30;

//--- Strategy settings input int ADXPeriod = 14; input double ADXMinimum = 20.0; input int FastEMAPeriod = 5; input int SlowEMAPeriod = 20; input double RiskRewardRatio = 1.0;

//--- Indicator handles int adxHandle = INVALID_HANDLE; int fastHandle = INVALID_HANDLE; int slowHandle = INVALID_HANDLE;

//--- Runtime variables datetime lastM5Bar = 0;

//+------------------------------------------------------------------+ //| Convert the fixed New York EST opening to broker server time | //+------------------------------------------------------------------+ datetime GetSessionStart() { MqlDateTime current; TimeToStruct(TimeCurrent(), current);

current.hour = 0; current.min = 0; current.sec = 0;

datetime brokerMidnight = StructToTime(current);

// 09:30 EST = 14:30 UTC. // Convert UTC opening time to broker server time. int minutesFromMidnight = SessionStartHour * 60 + SessionStartMinute + BrokerUTCOffsetHours * 60;

return brokerMidnight + minutesFromMidnight * 60; }

//+------------------------------------------------------------------+ //| Check whether this is a new M5 candle | //+------------------------------------------------------------------+ bool IsNewM5Bar() { datetime currentBar = iTime(_Symbol, PERIOD_M5, 0);

if(currentBar == 0 || currentBar == lastM5Bar) return false;

lastM5Bar = currentBar; return true; }

//+------------------------------------------------------------------+ //| Get the opening 30-minute candle | //+------------------------------------------------------------------+ bool GetOpeningRange(double &rangeHigh, double &rangeLow, datetime sessionStart) { if(TimeCurrent() < sessionStart + 30 * 60) return false;

int shift = iBarShift(_Symbol, PERIOD_M30, sessionStart, true);

if(shift < 0) return false;

if(iTime(_Symbol, PERIOD_M30, shift) != sessionStart) return false;

rangeHigh = iHigh(_Symbol, PERIOD_M30, shift); rangeLow = iLow(_Symbol, PERIOD_M30, shift);

return (rangeHigh > rangeLow && rangeLow > 0); }

//+------------------------------------------------------------------+ //| Find the latest EMA crossover direction this session | //| Returns 1 for bullish, -1 for bearish, 0 for no crossover | //+------------------------------------------------------------------+ int GetLatestCrossover(datetime sessionStart) { int startShift = iBarShift(_Symbol, PERIOD_M5, sessionStart, false);

if(startShift < 2) return 0;

int count = startShift;

double fast[]; double slow[];

ArraySetAsSeries(fast, true); ArraySetAsSeries(slow, true);

if(CopyBuffer(fastHandle, 0, 1, count, fast) < count) return 0;

if(CopyBuffer(slowHandle, 0, 1, count, slow) < count) return 0;

int latestDirection = 0;

// Examine candles from oldest to newest. for(int i = count - 2; i >= 0; i--) { if(fast[i] > slow[i] && fast[i + 1] <= slow[i + 1]) latestDirection = 1;

  if(fast[i] < slow[i] && fast[i + 1] >= slow[i + 1])
     latestDirection = -1;

}

return latestDirection; }

//+------------------------------------------------------------------+ //| Check whether this EA already has an open position | //+------------------------------------------------------------------+ bool HasOpenPosition() { for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i);

  if(ticket == 0)
     continue;

  if(PositionGetString(POSITION_SYMBOL) == _Symbol &&
     (ulong)PositionGetInteger(POSITION_MAGIC) == MagicNumber)
     return true;

}

return false; }

//+------------------------------------------------------------------+ //| Count entries made during the current session | //+------------------------------------------------------------------+ int CountSessionTrades(datetime sessionStart) { if(!HistorySelect(sessionStart, TimeCurrent())) return 0;

int entries = 0;

for(int i = 0; i < HistoryDealsTotal(); i++) { ulong ticket = HistoryDealGetTicket(i);

  if(ticket == 0)
     continue;

  if(HistoryDealGetString(ticket, DEAL_SYMBOL) != _Symbol)
     continue;

  if((ulong)HistoryDealGetInteger(ticket, DEAL_MAGIC) != MagicNumber)
     continue;

  ENUM_DEAL_ENTRY entry =
     (ENUM_DEAL_ENTRY)HistoryDealGetInteger(ticket, DEAL_ENTRY);

  if(entry == DEAL_ENTRY_IN || entry == DEAL_ENTRY_INOUT)
     entries++;

}

return entries; }

//+------------------------------------------------------------------+ //| Open a buy or sell trade | //+------------------------------------------------------------------+ void OpenTrade(bool isBuy, double openingHigh, double openingLow) { double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);

double entry = isBuy ? ask : bid; double stopLoss = isBuy ? openingLow : openingHigh;

// The stop-loss must be on the correct side of the entry. if(isBuy && stopLoss >= entry) return;

if(!isBuy && stopLoss <= entry) return;

double risk = MathAbs(entry - stopLoss);

if(risk <= 0) return;

double takeProfit = isBuy ? entry + risk * RiskRewardRatio : entry - risk * RiskRewardRatio;

int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);

stopLoss = NormalizeDouble(stopLoss, digits); takeProfit = NormalizeDouble(takeProfit, digits);

trade.SetExpertMagicNumber(MagicNumber); trade.SetDeviationInPoints(MaximumDeviationPoints);

bool result = false;

if(isBuy) result = trade.Buy(FixedLotSize, _Symbol, 0, stopLoss, takeProfit, "NY Opening Range Buy"); else result = trade.Sell(FixedLotSize, _Symbol, 0, stopLoss, takeProfit, "NY Opening Range Sell");

if(!result) { Print("Trade request failed. Retcode: ", trade.ResultRetcode(), " - ", trade.ResultRetcodeDescription()); } }

//+------------------------------------------------------------------+ //| Expert initialization | //+------------------------------------------------------------------+ int OnInit() { if(FixedLotSize <= 0 || ADXPeriod < 1 || FastEMAPeriod < 1 || SlowEMAPeriod < 1 || RiskRewardRatio <= 0 || MaxTradesPerSession < 1) { Print("Invalid input settings."); return INIT_PARAMETERS_INCORRECT; }

adxHandle = iADX(_Symbol, PERIOD_M5, ADXPeriod);

fastHandle = iMA(_Symbol, PERIOD_M5, FastEMAPeriod, 0, MODE_EMA, PRICE_CLOSE);

slowHandle = iMA(_Symbol, PERIOD_M5, SlowEMAPeriod, 0, MODE_EMA, PRICE_CLOSE);

if(adxHandle == INVALID_HANDLE || fastHandle == INVALID_HANDLE || slowHandle == INVALID_HANDLE) { Print("Unable to create indicator handles."); return INIT_FAILED; }

trade.SetExpertMagicNumber(MagicNumber);

Print("New York Opening Range EA initialized."); return INIT_SUCCEEDED; }

//+------------------------------------------------------------------+ //| Expert deinitialization | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { if(adxHandle != INVALID_HANDLE) IndicatorRelease(adxHandle);

if(fastHandle != INVALID_HANDLE) IndicatorRelease(fastHandle);

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

//+------------------------------------------------------------------+ //| Main trading logic | //+------------------------------------------------------------------+ void OnTick() { // Evaluate conditions once per newly opened M5 candle. if(!IsNewM5Bar()) return;

datetime sessionStart = GetSessionStart();

double openingHigh, openingLow;

if(!GetOpeningRange(openingHigh, openingLow, sessionStart)) return;

if(HasOpenPosition()) return;

if(CountSessionTrades(sessionStart) >= MaxTradesPerSession) return;

// Read the most recently completed M5 candle. MqlRates candle[]; ArraySetAsSeries(candle, true);

if(CopyRates(_Symbol, PERIOD_M5, 1, 1, candle) != 1) return;

// Read ADX from the completed M5 candle. double adx[]; ArraySetAsSeries(adx, true);

if(CopyBuffer(adxHandle, 0, 1, 1, adx) != 1) return;

if(adx[0] <= ADXMinimum) return;

// Check the latest EMA crossover direction this session. int crossoverDirection = GetLatestCrossover(sessionStart);

// Buy: completed candle closes above range high, // with bullish EMA crossover and ADX above threshold. if(candle[0].close > openingHigh && crossoverDirection == 1) { OpenTrade(true, openingHigh, openingLow); return; }

// Sell: completed candle closes below range low, // with bearish EMA crossover and ADX above threshold. if(candle[0].close < openingLow && crossoverDirection == -1) { OpenTrade(false, openingHigh, openingLow); return; } } //+------------------------------------------------------------------+

Important Note: Use This Code for Learning and Practice

The code provided above is an educational example created specifically for this tutorial. You can copy it, study its structure, compile it in MetaTrader 5, and use the Strategy Tester to understand how trading rules are converted into an automated trading system.

You can also use ChatGPT or another AI tool to convert your own trading strategy rules into MQL5 code. Simply provide your strategy conditions and explain how you want the automated system to work.

Remember that AI-generated code can contain errors or assumptions. Always review the code, compile it, resolve any errors, and test it thoroughly using historical market data before considering live trading. This example does not guarantee trading performance or profitability.

However, generating the code is not the final step. We still need to place it in MetaTrader 5, compile it using MetaEditor, check for programming errors, and test whether it follows our strategy correctly.

In the next article, we will open MetaTrader 5, access MetaEditor, and learn how to install and compile our Expert Advisor before moving on to backtesting.

Frequently Asked Questions (FAQs)

1. Do I need programming knowledge to create a Forex trading bot?

No. You can use AI tools such as ChatGPT or Claude to help convert your trading strategy rules into MQL5 code. However, you should understand your strategy and learn how to review, compile, and test the generated code.

2. What is MQL5 in automated Forex trading?

MQL5 is the programming language used to develop automated trading programs for MetaTrader 5. It allows traders to create Expert Advisors that can analyse market conditions and execute trades according to predefined rules.

3. Can ChatGPT create an automated trading bot?

Yes. ChatGPT can generate MQL5 code based on clearly defined trading rules. However, generated code may contain errors or assumptions, so it must be checked, compiled, and tested before use.

4. What is an Expert Advisor (EA)?

An Expert Advisor is an automated trading program that runs on MetaTrader. It follows programmed instructions to monitor market conditions and can automatically open, manage, and close trades.

5. Can I use my own trading strategy to create an EA?

Yes. You can automate your own trading strategy by converting its entry conditions, exit rules, indicators, stop-loss, take-profit, and risk management settings into clear instructions that can be programmed.

Conclusion: Your First Step Towards Automated Forex Trading

We have now taken an important step towards building an automated Forex trading system. We started with a trading idea, converted it into clear rules, and used ChatGPT to generate an initial MQL5 Expert Advisor.

This is how the automation process begins. You do not need to become a professional programmer before exploring automated trading. What matters first is understanding your trading strategy and expressing its conditions clearly enough for a computer to follow.

However, creating the code is only the beginning. We still need to install it in MetaTrader 5, compile it, backtest it, understand its performance, and make sure it behaves as expected before considering live deployment. We will cover these practical steps in the next part of this learning journey.

If you are completely new to automated trading and want to understand everything from the beginning, explore our Forex Automated Trading Masterclass. We have designed this learning series to take you from understanding what automated trading is and why traders use it to building, testing, and deploying automated trading systems.

And if you are new to Forex trading and want to learn the subject from A to Z, or if you are already a trader looking to improve your trading discipline and psychology, explore our Forex Trading Foundation Masterclass and Trader Psychology Series.

Our goal is to make Forex education easier to understand, practical to apply, and accessible to traders at every stage of their journey.

DISCLAIMER All content published on this website is for educational, informational, and research purposes only. It does not constitute financial, investment, trading, legal, or tax advice in any manner. The opinions, views, and analysis presented are based on publicly available information, market observations, and personal interpretation, which may change over time without prior notice. The author and website do not guarantee the accuracy, completeness, or timeliness of any information provided. Nothing on this website should be interpreted as a direct or indirect recommendation to buy, sell, or hold any security, derivative, commodity, forex instrument, cryptocurrency, or financial product. The website does not provide personalized investment advice, trading signals, or portfolio management services. Investing and trading involve substantial risk, including the potential loss of principal. Readers and users are solely responsible for their own investment decisions and should conduct independent research and/or consult a SEBI-registered investment advisor before taking any financial action. The website, its owners, authors, contributors, and affiliates shall not be held liable for any financial losses, damages, or legal consequences arising from the use of any information provided herein. By using this website, you acknowledge that you have read, understood, and accepted this disclaimer in full.
Trade Together Research

Written by

Trade Together Research

Trade Together Research is a professional market analysis team providing forex, gold, and crypto trading insights, technical analysis, and educational guides.. Learn more about our research team on the About page.