pageview
Home / Tutorial / The Basics of MQL4 : How to Create Your First Forex EA

The Basics of MQL4 : How to Create Your First Forex EA

The Basics of MQL4 How to Create Your First Forex EA
Table of Contents
Table of Contents

SocialVPS — MetaTrader 4 (MT4) is one of the most popular platforms among Forex traders, and one of its biggest strengths is the ability to automate trades using Expert Advisors (EAs). If you’ve ever wondered how traders build those automated trading bots, this guide is your starting point. In this article, we’ll break down the basics of MQL4 (the programming language behind MT4) and walk you through how to create your very first Forex EA.

What Is MQL4 and Why Is It Important?

Before we dive into coding, let’s understand what MQL4 actually is.

MQL4 Apps for Forex EA

MQL4, or MetaQuotes Language 4, is a high-level programming language specifically designed for developing trading strategies on the MT4 platform. With MQL4, you can create custom indicators, scripts, and most importantly, Expert Advisors—also known as Forex robots or algorithmic trading bots.

Why does this matter to you? Because automating your strategy allows you to remove emotional bias, trade 24/7, and test ideas faster than manual trading ever could.

What Is a Forex EA?

A Forex EA (Expert Advisor) is a piece of software written in MQL4 that automates your trading strategy. It monitors the market, opens and closes trades based on conditions you define, and can even send you alerts. Essentially, it acts as your personal trading assistant—minus the salary.

Creating a forex EA is like giving life to your trading plan. It follows instructions with no emotion, no fatigue, and no second-guessing.

Tools You’ll Need to Create Your First EA

Let’s talk about the basic tools and setup you need to get started.

  • MetaTrader 4 Platform: Download from your broker or the official MetaTrader 4 website.
  • MetaEditor: Installed with MT4, this is where you’ll write and compile your code.
  • Patience: Learning to code—even just the basics—takes time.

Your First MQL4 Forex EA: Step-by-Step

Now we get to the fun part: building your very first Forex EA. Let’s start with a basic trading strategy:

Buy when the 10-period Moving Average crosses above the 20-period Moving Average.
Sell when the 10-period Moving Average crosses below the 20-period Moving Average.

Step 1: Open MetaEditor

  1. Open your MT4 platform.
  2. Click on the MetaEditor icon or press F4.

Step 2: Create a New EA File

  1. In MetaEditor, go to File → New → Expert Advisor (template).
  2. Name it something like SimpleMA_EA.
  3. Click Next → Finish.

Step 3: Write the EA Code

Below is a simplified EA code you can use to get started:

//+------------------------------------------------------------------+
//|                                                  SimpleMA_EA.mq4|
//+------------------------------------------------------------------+
#property strict

input int FastMA = 10;
input int SlowMA = 20;
input double LotSize = 0.1;

int start() {
    double fastMA = iMA(NULL, 0, FastMA, 0, MODE_SMA, PRICE_CLOSE, 0);
    double slowMA = iMA(NULL, 0, SlowMA, 0, MODE_SMA, PRICE_CLOSE, 0);
    double fastMA_prev = iMA(NULL, 0, FastMA, 0, MODE_SMA, PRICE_CLOSE, 1);
    double slowMA_prev = iMA(NULL, 0, SlowMA, 0, MODE_SMA, PRICE_CLOSE, 1);

    if (fastMA > slowMA && fastMA_prev <= slowMA_prev) {
        OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, 0, 0, "Buy Order", 0, 0, clrBlue);
    }

    if (fastMA < slowMA && fastMA_prev >= slowMA_prev) {
        OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, 0, 0, "Sell Order", 0, 0, clrRed);
    }

    return(0);
}

This Expert Advisor (EA) performs automated trading on MetaTrader 4 using a Simple Moving Average (SMA) crossover strategy. When the Fast MA crosses above the Slow MA, it opens a buy order. When the Fast MA crosses below the Slow MA, it opens a sell order.

Step 4: Compile and Test

  1. Hit the Compile button in MetaEditor.
  2. Go back to MT4 and drag your EA onto a chart to test it.

That’s it. You’ve just created your first automated trading system using MQL4.

Certainly! Let’s break down this MQL4 Expert Advisor script SimpleMA_EA.mq4, line by line, to help you or any beginner clearly understand what each part of the code does.

Code Breakdown and Function Explanations

#property strict
  • This enables stricter compile-time error checks to help ensure cleaner code.
input int FastMA = 10;
input int SlowMA = 20;
input double LotSize = 0.1;
  • These are input variables, which means users can easily change them in the EA settings:
    • FastMA: the period for the Fast Moving Average, e.g. 10.
    • SlowMA: the period for the Slow Moving Average, e.g. 20.
    • LotSize: How big will your trade be (0.1 lot in this case).
int start() {
  • The start() function is the main loop in MQL4 EAs (used in older versions of MetaTrader 4).
  • This function runs every time a new tick (price update) is received.
double fastMA = iMA(NULL, 0, FastMA, 0, MODE_SMA, PRICE_CLOSE, 0);
double slowMA = iMA(NULL, 0, SlowMA, 0, MODE_SMA, PRICE_CLOSE, 0);
  • These lines calculate the current values of the Fast MA and Slow MA using iMA():
    • NULL: current chart symbol.
    • 0: current timeframe.
    • FastMA/SlowMA: period for each MA.
    • 0: shift (current candle).
    • MODE_SMA: use Simple Moving Average.
    • PRICE_CLOSE: based on candle close price.
    • 0: current candle.
double fastMA_prev = iMA(NULL, 0, FastMA, 0, MODE_SMA, PRICE_CLOSE, 1);
double slowMA_prev = iMA(NULL, 0, SlowMA, 0, MODE_SMA, PRICE_CLOSE, 1);
  • These lines get the previous candle’s MA values (shift = 1), so we can compare current vs previous for crossover logic.
Looking to Elevate Your Forex Trading?
Boost Your Trading Performance with Our Forex VPS

from $8.3 to $5.7/billed annually

SociaVPS Give The Best Forex VPS

Trading Logic

Buy Condition

if (fastMA > slowMA && fastMA_prev <= slowMA_prev) {
OrderSend(Symbol(), OP_BUY, LotSize, Ask, 2, 0, 0, "Buy Order", 0, 0, clrBlue);
}
  • This block checks:
    • Is the Fast MA currently above the Slow MA?
    • Was the Fast MA below or equal to the Slow MA in the previous candle?
  • If yes, it triggers a Buy order with:
    • Symbol(): current chart pair (e.g. EURUSD).
    • OP_BUY: order type.
    • LotSize: lot amount.
    • Ask: current ask price (buying price).
    • 2: slippage.
    • 0, 0: no Stop Loss or Take Profit.
    • "Buy Order": order comment.
    • clrBlue: color shown on the chart for the order.

Sell Condition

if (fastMA < slowMA && fastMA_prev >= slowMA_prev) {
OrderSend(Symbol(), OP_SELL, LotSize, Bid, 2, 0, 0, "Sell Order", 0, 0, clrRed);
}
  • This block checks:
    • Is the Fast MA now below the Slow MA?
    • Was the Fast MA above or equal to the Slow MA previously?
  • If yes, it places a Sell order using OrderSend() with the same parameters, but for OP_SELL.
return(0);
}
  • Ends the start() function and returns 0 (not required for functionality but standard syntax).

Next Steps in Building Better EAs

Once your EA works, you’ll probably want to improve it. You can:

  • Add Stop Loss and Take Profit logic.
  • Implement trailing stops.
  • Use more indicators or custom filters.
  • Include risk management features.

The possibilities are endless. The more you learn, the more powerful your forex EA becomes.

Why Use a Forex VPS for Your Expert Advisor?

At this point, you might be thinking: “Cool, I made my EA. But do I need to leave my computer on 24/7?”

The answer is no—that’s what a Forex VPS is for. A Virtual Private Server (VPS) allows your EA to run non-stop on a remote server, giving you stable uptime, low latency, and uninterrupted trading—especially crucial for automated trading, robot forex systems, and algorithmic strategies.

Using a VPS ensures your EA keeps working even if your internet goes down or your PC crashes.
If you’re serious about automation, you need a Forex VPS. Get your own high-performance Forex VPS from SocialVPS and keep your EA running smoothly 24/7.

FAQs

How long does it take to learn MQL4?

For beginners, you can start writing simple EAs in just a few days. Learning more advanced features can take a few weeks or months depending on your dedication.

Can I create a Forex EA without coding?

Yes, there are no-code EA builders available online, but they are often limited. Learning MQL4 gives you full control and flexibility over your strategies.

Is a Forex EA profitable?

A Forex EA can be profitable if it’s based on a sound strategy and well-tested. Backtesting and optimization are crucial to long-term success.

Can I use the same EA on different currency pairs?

Yes, but you may need to tweak the settings (like MA periods or lot size) to fit different pairs or timeframes.

Why should I run my Forex EA on a VPS?

A VPS keeps your EA online 24/7, prevents downtime, and improves execution speed—which can make or break your strategy in fast-moving markets.

author avatar
Writer SocialVPS
A content writer at SocialVPS who focuses on creating informative and educational articles related to Forex VPS services, trading guides, and VPS usage tips to help traders improve their trading performance.
Top-Tier VPS

Starts from $5.7 first month for Standard VPS! Unlock lightning-fast speeds and reliable uptime today, and elevate your online experience with our secure and optimized virtual private servers.

People Choice SocialVPS Top Tier Forex VPS

Share

Email
WhatsApp
Facebook
LinkedIn
X
Other Posts
Get High-Quality VPS at an Affordable Price!

Experience top-notch server performance for your business or personal needs with SocialVPS. Enjoy speed, security, and reliability all in one package.