Cloud VPS from $1.98/mo · pay with Bitcoin, Ethereum, Monero, USDT or Solana · paid in crypto
Trading and crypto

MetaTrader 4 scripts: how they run and how to write one

How MetaTrader 4 scripts differ from expert advisors and indicators, where they live, how to write and run one safely, and when a script is the wrong tool.

CloudSat teamNovember 18, 20266 min read
Abstract illustration of a single glowing command card sliding into a chart window and dissolving after one pass
On this pageScripts, expert advisors and indicators

A MetaTrader 4 script is a small MQL4 program that does one job when you start it, then removes itself. Export the open trades to a file, print a symbol's contract details, set a stop on every order at once: tasks you would otherwise do by hand, done in a second. Scripts are the simplest kind of MQL4 program, which makes them a good first step into automation, and also easy to misuse.

Scripts, expert advisors and indicators

MT4 runs three kinds of programs, and each one reacts to different events:

Program When it runs Main event handler Typical job
Script Once, when you attach it to a chart OnStart() One-off tasks: exports, batch changes to orders, checks
Expert advisor Continuously, while attached OnTick(), plus OnTimer() and OnChartEvent() Automated trading or trade management
Custom indicator On each price update OnCalculate() Calculating and drawing values on a chart

MQL4's documentation spells out the lifecycle: scripts "are loaded immediately after they are attached to a chart" and "unloaded immediately after they complete their operation". A script receives the Start event and nothing else. Timer events and chart events are generated only for expert advisors and indicators, so a script cannot wake itself up later or react to clicks.

Threads matter too. Each script and each expert advisor runs in its own thread, while all indicators run in the terminal's interface thread. A script stuck in a loop cannot freeze other programs; an indicator stuck in a loop can stop the whole terminal.

Where scripts live

Every MT4 installation has a data folder. Open it from File > Open Data Folder; scripts sit in MQL4\Scripts. Source files end in .mq4, compiled ones in .ex4, and only the compiled file runs.

To add one, copy the .mq4 file into MQL4\Scripts, open it in MetaEditor (F4 from the terminal), compile with F7, then right-click Scripts in the Navigator and choose Refresh. To run it, drag it onto a chart or double-click it. Right-clicking a script in the Navigator also lets you set a hotkey, which is handy for tasks you repeat.

A first script: export open orders to CSV

This script writes every open and pending order to a CSV file. It only reads, which makes it a safe one to learn with:

#property strict
#property script_show_inputs

input string FileName = "open_orders.csv";

void OnStart()
{
   int h = FileOpen(FileName, FILE_WRITE | FILE_CSV, ',');
   if(h == INVALID_HANDLE)
   {
      Print("Cannot open the file, error ", GetLastError());
      return;
   }

   FileWrite(h, "ticket", "symbol", "type", "lots", "open_price", "sl", "tp", "profit");

   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         continue;
      FileWrite(h, OrderTicket(), OrderSymbol(), OrderType(), OrderLots(),
                OrderOpenPrice(), OrderStopLoss(), OrderTakeProfit(), OrderProfit());
   }

   FileClose(h);
   Print("Exported ", OrdersTotal(), " orders to MQL4\\Files\\", FileName);
}

A few things to notice:

  • #property strict turns on the stricter compiler mode. Use it in every new file.
  • #property script_show_inputs opens the input dialog before the script runs, so you can change FileName each time.
  • File functions are sandboxed. FileOpen() writes inside MQL4\Files of the data folder, not anywhere on disk.
  • The loop walks backward from the last order. For a read-only export the direction does not matter, but scripts that close or delete orders must walk backward, because each removal shifts the positions of the orders after it.
  • OrderType() returns a number: 0 for a buy, 1 for a sell, 2 to 5 for the four pending types.

Print() output appears in the Experts tab of the Terminal window. Errors from the terminal itself appear in the Journal tab.

A second script: read a symbol's contract details

Before automating anything on an instrument, know its rules. This script prints the values that decide what a position costs and where stops may sit:

#property strict

void OnStart()
{
   string s = _Symbol;
   PrintFormat("%s digits=%d spread=%d points", s,
               (int)MarketInfo(s, MODE_DIGITS), (int)MarketInfo(s, MODE_SPREAD));
   PrintFormat("tick size=%.5f tick value=%.2f %s",
               MarketInfo(s, MODE_TICKSIZE), MarketInfo(s, MODE_TICKVALUE), AccountCurrency());
   PrintFormat("lots min=%.2f step=%.2f max=%.2f",
               MarketInfo(s, MODE_MINLOT), MarketInfo(s, MODE_LOTSTEP), MarketInfo(s, MODE_MAXLOT));
   PrintFormat("stop level=%d points swap long=%.2f swap short=%.2f",
               (int)MarketInfo(s, MODE_STOPLEVEL), MarketInfo(s, MODE_SWAPLONG), MarketInfo(s, MODE_SWAPSHORT));
}

The stop level is the minimum distance, in points, between the current price and a stop or limit. Orders that ignore it are rejected, which is the most common reason a script that "should work" fails. Swap values show the overnight charge or credit per lot, in the units the broker configured.

Scripts that trade

A script that sends, modifies or closes orders acts the moment it starts, with no confirmation unless you add one. Three settings decide whether it may trade:

  1. The AutoTrading button on the toolbar must be on.
  2. Tools > Options > Expert Advisors > Allow automated trading must be ticked.
  3. When the script shows its settings dialog, Allow live trading on its Common tab must be ticked.

Add #property show_confirm to a trading script so the terminal asks before it runs, and test every trading script on a demo account first. The MT4 Strategy Tester cannot run scripts, so a demo account is the only test bed a script gets.

When a script is the wrong tool

Scripts need someone to start them. They do not run on a schedule and do not survive a terminal restart. If a task must run every minute, or react to every tick, write an expert advisor with OnTimer() or OnTick() instead.

The one exception the MQL4 documentation allows is a script that loops on purpose, handling only its single Start event. That works for a temporary monitor, such as logging equity every minute until you remove it:

#property strict

void OnStart()
{
   while(!IsStopped())
   {
      Print("Equity: ", DoubleToString(AccountEquity(), 2), " ", AccountCurrency());
      Sleep(60000);   // one minute
   }
}

IsStopped() turns true when you remove the script from the chart or close the terminal, so the loop ends cleanly. Use a pattern like this for a session, not as a permanent service. On a terminal that runs around the clock, such as MT4 on a CloudSat Trading RDP server, anything permanent belongs in an expert advisor that restarts with the terminal.

Running scripts from strangers

A compiled .ex4 file cannot be read, so you cannot check what it does before running it. Two terminal settings limit the damage a hostile program can do:

  • Allow DLL imports lets a program call Windows libraries, which means it can do anything your Windows account can, including reading files. Leave it off, and enable it per program only for code you trust.
  • Allow WebRequest for listed URL controls which web addresses programs may contact. Keep the list empty unless a program you wrote or audited needs it.

Prefer source code you can read and compile yourself. A script that exports or checks data is easy to audit in a few minutes; one that trades deserves the same care as an expert advisor. The differences between MQL4 and MQL5 programs are covered in MetaTrader 4 vs MetaTrader 5.

FAQ

Do MT4 scripts work in MetaTrader 5?

No. MT5 runs .ex5 programs written in MQL5, and its trading functions work differently. A script has to be ported and recompiled.

Why does my script do nothing when I drop it on a chart?

Check the Experts and Journal tabs. The usual causes are AutoTrading being off, live trading not allowed in the script's settings, or an error code returned by a trade function.

Can a script keep running after I disconnect from my VPS?

Yes. Closing a Remote Desktop window leaves the Windows session and the terminal running, along with any looping script. Signing out of Windows closes the terminal and stops it.

Trading involves risk of loss. Nothing in this article is financial advice.

Run it on CloudSat. Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. See plans or deploy a server.