Master MetaTrader 4/5 Scripts: Automate One-Click Tasks

Learn to install, run, and create MQL4/MQL5 scripts for MT4 and 5. Automate repetitive tasks like closing all trades or setting stop-losses with one.

master-metatrader-4-5-scripts-automate-one-click

Why Every Trader Should Use MetaTrader Scripts

If you have ever manually closed ten losing positions one by one, or applied the same stop-loss to a dozen orders, you know how tedious and error-prone repetitive trading tasks can be. MetaTrader scripts are the solution. Unlike Expert Advisors (EAs), which run continuously on a chart, a script executes once immediately when you drag it onto a chart and then terminates. This makes scripts perfect for one-time actions: close all buy orders, delete all pending orders, set a trailing stop on every open position, or export trade history to a CSV file.

In this guide, you will learn exactly what scripts are, how to install and run them in MT4 and MT5, and how to write your own simple script using the MetaEditor. By the end, you will be able to automate dozens of routine operations and save hours of manual clicking each week.

Prerequisites

  • MetaTrader 4 or 5 installed on your PC (any broker build).
  • MetaEditor (comes bundled with the terminal; no separate download needed).
  • A demo or live trading account logged in (scripts do not trade on demo-only accounts, but you need a chart to attach them to).
  • Basic familiarity with the Navigator panel (Ctrl+N).

Step-by-Step: Installing and Running Scripts

Step 1: Locate the Scripts Folder

Every MetaTrader installation has a dedicated Scripts folder inside the MQL4 or MQL5 directory. To open it:

  1. Open MetaTrader.
  2. Go to File → Open Data Folder (or press Ctrl+Shift+D in MT5).
  3. Navigate to MQL4/Scripts/ (MT4) or MQL5/Scripts/ (MT5).

Any .ex4 or .ex5 file placed here will appear in the Navigator panel under the Scripts section.

Step 2: Install a Script from a File

  1. Download a script file (usually .ex4 or .ex5).
  2. Copy the file into the Scripts folder from Step 1.
  3. Restart MetaTrader, or right-click the Navigator and select Refresh.
  4. In the Navigator panel, expand Scripts. Your script should now appear.

Step 3: Run a Script on a Chart

  1. Open any chart (e.g., EURUSD, H1).
  2. From the Navigator, drag the script name onto the chart and release the mouse button.
  3. A settings dialog may appear if the script has input parameters. Configure as needed and click OK.
  4. The script executes immediately. In MT4, a smiley face icon appears in the top-right corner of the chart while the script runs (usually less than a second). In MT5, you see a small script icon.

Step 4: Verify Execution

Open the Experts tab in the Terminal panel (Ctrl+T). Look for a message like Script 'MyScript' removed — this confirms the script ran and finished. If you see any error messages, refer to the troubleshooting section below.

Creating Your First MQL4 Script in MetaEditor

Writing a script is easier than writing an EA. You only need the OnStart() function — no OnTick(), no OnInit() required.

Step 1: Open MetaEditor and Create a New Script

  1. In MetaTrader, press F4 to open MetaEditor.
  2. Click File → New → Expert Advisor (this is the same wizard for scripts; we will change the type).
  3. In the wizard, select Script as the file type (MT4) or Script in the dropdown (MT5).
  4. Give it a name, e.g., CloseAllOrders, and click Finish.

Step 2: Write the Script Code

Replace the generated template with this simple script that closes all open market orders for the current symbol:

//+------------------------------------------------------------------+
//|                                                  CloseAllOrders.mq4 |
//|                                                      Your Name     |
//|                                                                  |
//+------------------------------------------------------------------+
#property strict

void OnStart()
  {
   int total = OrdersTotal();
   for(int i = total - 1; i >= 0; i--)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
         if(OrderSymbol() == Symbol() && OrderType() <= OP_SELL)
           {
            if(!OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 3, clrNONE))
              {
               Print("Error closing order #", OrderTicket(), ": ", GetLastError());
              }
           }
        }
     }
   Print("All orders closed for ", Symbol());
  }
//+------------------------------------------------------------------+

Explanation: The script loops through all open orders backwards (to avoid index shifting), selects each one, checks if it belongs to the current chart symbol, and closes it. Any errors are printed to the Experts tab.

Step 3: Compile the Script

  1. Press F7 or click the Compile button.
  2. If no errors appear in the bottom pane, the compiled .ex4 or .ex5 file is automatically placed in your Scripts folder.
  3. Switch back to MetaTrader, refresh the Navigator (right-click → Refresh), and drag your new script onto a chart to test it.

Key Differences Between MT4 and MT5 Scripts

Aspect MT4 MT5
File Extension .ex4 .ex5
Trade Functions OrderSend(), OrderClose() PositionOpen(), PositionClose()
Main Entry Point OnStart() OnStart()
Order/POSITION Model Orders and positions are combined Separate Position and Order objects

Tips and Best Practices

  • Always test scripts on a demo account first. A small coding error can close the wrong positions or delete all pending orders. Demo testing is free insurance.
  • Use input parameters for flexibility. For example, add an extern bool CloseOnlyBuys = false; parameter so users can choose which side to close without editing code.
  • Add confirmation dialogs for destructive scripts. Use MessageBox() to ask "Are you sure?" before executing a mass close. This prevents accidental double-clicks.
  • Keep scripts single-purpose. A script that closes all orders AND exports data AND sets a trailing stop is harder to debug. Write one script per task.
  • Use the #property strict directive in MT4 to enable compile-time checks that catch variable type mismatches.
  • Name your scripts descriptively (e.g., CloseAllOrders_Symbol.mq4), so you can quickly find them in a long list.

Common Mistakes and Troubleshooting

Mistake 1: Script Does Not Appear in Navigator

Cause: The compiled file is in the wrong folder, or the terminal has not refreshed. Fix: Verify the file is in MQL4/Scripts/ (MT4) or MQL5/Scripts/ (MT5). Right-click the Navigator and choose Refresh. If it still does not appear, restart MetaTrader.

Mistake 2: Script Runs But Does Nothing

Cause: The script logic may not find any orders matching its criteria. Fix: Check the Experts tab for Print() output. For example, if your script closes only buy orders and you only have sells, it will exit silently. Add a print statement to confirm the loop ran: Print("Total orders found: ", OrdersTotal());

Mistake 3: "Function is not allowed in scripts" Error

Cause: You used an MT5-only function like PositionSelect() in an MT4 script, or vice versa. Fix: Use the correct API for your platform. In MT5, use PositionsTotal() and PositionSelect(); in MT4, use OrdersTotal() and OrderSelect().

Mistake 4: Compilation Errors

Cause: Missing semicolons, undeclared variables, or incorrect function signatures. Fix: Read the error message in the MetaEditor bottom pane. Double-click the error line to jump to the offending code. Common fixes: add a semicolon, declare a variable with int or double, or check that function names match exactly (case-sensitive).

Summary and Next Steps

You now understand how to install, run, and create your own MetaTrader scripts. Scripts are the fastest way to automate single-shot tasks like closing trades, setting stops, or exporting data. Start by downloading a few free scripts from trusted sources (like the MQL5 Community Market) to see what is possible, then modify them to suit your workflow.

Next challenge: Write a script that moves all stop-losses to breakeven for your open positions. You already have the foundation from the CloseAllOrders example — just replace the OrderClose() call with OrderModify() using a new stop-loss price. Happy scripting!

Frequently Asked Questions

Can a script run automatically on multiple charts at once?

No. Each script must be manually dragged onto each chart. If you need the same action on multiple symbols, you can write a script that loops through all open charts using ChartFirst() and ChartNext() in MQL5, but in MT4 you need a separate script per chart or use an EA that runs continuously.

Will a script continue running if I change timeframes?

No. The script executes once and terminates within milliseconds. Changing timeframes after the script has run has no effect. The script does not persist.

How do I delete a script I no longer need?

Remove the .ex4/.ex5 file from the Scripts folder (and the source .mq4/.mq5 if desired). Refresh the Navigator. The script will disappear from the list. You can also right-click the script in the Navigator and choose Delete (MT5 only).

Community

Clap for the article and open comments only when you want to read them.

0 claps0 comments

Related articles