EnglishNederlandsPortuguesEspanolDeutschFrancais

MT4 Expert Advisor Programming: Your Complete Guide

By 8 min read trading Published:
Part of Prop Firm EA — our complete pillar guide on this topic.
MT4 Expert Advisor Programming: Your Complete Guide

An MT4 Expert Advisor (EA) programming tutorial guides traders through automating trading strategies on the MetaTrader 4 platform using MQL4. It involves learning the MQL4 language to write scripts that can analyze market data, open and close trades, and manage positions autonomously, executing predefined rules without manual intervention.

The Power of Automation: Why Learn MT4 Expert Advisor Programming?

In the fast-paced world of financial markets, the ability to execute trades with precision, speed, and unwavering discipline is paramount. This is where MetaTrader 4 (MT4) Expert Advisors (EAs) come into play. An Expert Advisor is a program that allows you to automate analytical and trading processes on the MT4 platform. Learning MT4 Expert Advisor programming empowers traders to:

For prop firm traders, in particular, EAs offer a critical advantage. The strict rules and objectives of prop firm challenges demand consistent performance and meticulous risk management. An expertly programmed EA can help maintain these standards, adhering to drawdown limits and profit targets with unparalleled accuracy.

Getting Started: Your MT4 Expert Advisor Programming Environment

Live JPTC Algo equity curve — real broker, public-share MyFxBook
Open full MyFxBook portfolio →

Before diving into the code, you need to set up your development environment. This primarily involves the MetaTrader 4 terminal and its integrated development environment, MetaEditor.

1. Installing MetaTrader 4

If you haven't already, download and install the MetaTrader 4 platform from your preferred broker. Once installed, launch the terminal.

2. Accessing MetaEditor

MetaEditor is where you'll write, compile, and debug your MQL4 code. You can open it directly from the MT4 terminal by clicking the 'MetaEditor' icon in the toolbar (it looks like a yellow star with a pen) or by pressing F4.

3. Creating Your First Expert Advisor

In MetaEditor, navigate to 'File' > 'New' or click the 'New' icon. Select 'Expert Advisor (template)' and click 'Next'. Give your EA a descriptive name (e.g., 'MyFirstEA'), add your name as author, and provide a link if desired. Click 'Next' and then 'Finish'. MetaEditor will generate a basic template for your new EA, which includes the essential functions.

MQL4 Fundamentals: The Language of MT4 EAs

Recent live trades — JPTC Algo
Auto-posted to Instagram. Real account, no demo.
JPTC Algo live trade screenshotJPTC Algo live trade screenshotJPTC Algo live trade screenshotJPTC Algo live trade screenshotJPTC Algo live trade screenshotJPTC Algo live trade screenshot
@jptradingcapital on Instagram →

MQL4 (MetaQuotes Language 4) is a C-like programming language specifically designed for developing trading applications on the MetaTrader 4 platform. Understanding its core components is crucial for any mt4 expert advisor programming tutorial.

Data Types and Variables

Variables are used to store data in your program. MQL4 supports several data types:

Variables must be declared before use. For example:


int    magicNumber = 12345;
double lotSize     = 0.01;
bool   canTrade    = true;

Operators

MQL4 uses standard arithmetic, assignment, comparison, and logical operators:

Control Flow Statements

These statements dictate the order in which your code is executed:

Example if statement:


if (Close[1] > Open[1])
{
   Print(\"Previous candle was bullish\");
}
else
{
   Print(\"Previous candle was bearish or doji\");
}

The Core Structure of an MT4 Expert Advisor

Every MT4 Expert Advisor template comes with three essential functions that define its lifecycle:

1. OnInit(): Initialization

This function is called once when the EA is attached to a chart or when the MT4 terminal starts. It's ideal for:

It must return INIT_SUCCEEDED for the EA to function correctly.


int OnInit()
{
   Print(\"MyFirstEA initialized!\");
   // Set a magic number for orders to identify them later
   magicNumber = 12345;
   return(INIT_SUCCEEDED);
}

2. OnDeinit(): De-initialization

This function is called when the EA is removed from a chart, the chart is closed, or the MT4 terminal is shut down. Use it for:


void OnDeinit(const int reason)
{
   Print(\"MyFirstEA de-initialized!\");
}

3. OnTick(): The Heartbeat of Your EA

This is the most critical function. It's called every time a new tick (a change in price) is received for the currency pair the EA is attached to. This is where your main trading logic resides:


void OnTick()
{
   // Your trading logic goes here
   // For example, check if there are no open trades and a condition is met
   if (OrdersTotal() == 0 && IsNewBar())
   {
      // Place a buy order example
      // OrderSend(Symbol(), OP_BUY, 0.1, Ask, 3, Ask - 50*Point, Ask + 100*Point, \"MyFirstEA Buy\", magicNumber, 0, clrGreen);
   }
}

Implementing Trading Logic: Order Management in MQL4

The core of any trading bot MT4 is its ability to interact with the market. MQL4 provides a robust set of functions for this purpose.

Placing Orders with OrderSend()

OrderSend() is the primary function for placing market or pending orders. Its parameters define the type of order, volume, price, stop loss, take profit, and more.


// Example: Placing a Buy Order
double lotSize = 0.1;
double stopLoss = Ask - 50 * Point;   // 50 points below current Ask
double takeProfit = Ask + 100 * Point; // 100 points above current Ask

int ticket = OrderSend(
    Symbol(),      // Current symbol
    OP_BUY,        // Order type: Buy
    lotSize,       // Volume
    Ask,           // Price (current Ask for market buy)
    3,             // Slippage (3 points)
    stopLoss,      // Stop Loss
    takeProfit,    // Take Profit
    \"My Buy Order\",// Comment
    magicNumber,   // Magic Number
    0,             // Expiration (0 for market orders)
    clrGreen       // Arrow color
);

if (ticket > 0)
{
   Print(\"Buy order placed successfully. Ticket: \", ticket);
}
else
{
   Print(\"Failed to place buy order. Error: \", GetLastError());
}

Modifying Orders with OrderModify()

To change the stop loss, take profit, or expiration of an open or pending order, use OrderModify().


// Example: Modifying an existing order's SL/TP
for (int i = 0; i < OrdersTotal(); i++)
{
   if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
   {
      if (OrderMagicNumber() == magicNumber && OrderSymbol() == Symbol())
      {
         double newStopLoss = OrderOpenPrice() - 60 * Point;
         double newTakeProfit = OrderOpenPrice() + 120 * Point;

         if (OrderModify(OrderTicket(), OrderOpenPrice(), newStopLoss, newTakeProfit, 0, clrNONE))
         {
            Print(\"Order \", OrderTicket(), \" modified successfully.\");
            break; // Exit loop after modifying our order
         }
         else
         {
            Print(\"Failed to modify order \", OrderTicket(), \". Error: \", GetLastError());
         }
      }
   }
}

Closing Orders with OrderClose()

To close an open position, use OrderClose().

Futures Challenge Prep

Software + validated setfiles + written risk plan + Discord community to help you pass your futures evaluation on your own account.

Get Started

Related Articles

trading
Best Prop Firms For Futures: Top 5 Platforms in 2026
8 min read
trading
FundedNext Futures Review 2026: 7 Key Insights for Prop Traders
8 min read
trading
7 Best MT4 Expert Advisors for Prop Firms in 2025: Tested EAs
13 min read
Pass your prop firm — JPTC Algo
See Results →
Risk Disclaimer

Trading forex and CFDs involves significant risk and is not suitable for all investors. Past performance does not guarantee future results. You should not invest money you cannot afford to lose. The content on this page is for informational purposes only and does not constitute financial advice. JPTradingCapital does not accept liability for any loss or damage arising from reliance on the information provided. Always conduct your own research before making trading decisions.