metatrader script tutorial
This site provides users with the information about metatrader mql4, metatrader script basics, simple example, how to write mql4 script with MetaTrader 4, sample script, mql4 language, create expert advisors, guide, and more.
This tutorial is to teach you how to write a simple mql4 script with MetaTrader 4 from the very beginning to the end. You will see the script to be created get successfully executed. Please note that this tutorial will not teach you how to program with mql4 language in details.
What is a MQL4 script?
The script is a program you run once to execute an action and it will be removed immediately after the execution, which is different from the expert advisors which will be called every time in a new tick arrival.
How to write a MQL4 script with MetaTrader 4?
1. Open MetaEditor
2. Click New from File menu.
3. Choose Script.
4. Click Next and enter the program information.
5. Click Finish.
6. With the template created, you can add your code. In this tutorial, we are going to create a program to close all the orders. The following is the code which you need to add.
int total = OrdersTotal();
int type = OrderType();
bool result = false;
//Close opened long positions
case OP_BUY: result = OrderClose( OrderTicket(),
OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
//Close opened short positions
case OP_SELL: result = OrderClose( OrderTicket(),
OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
//Close pending orders
case OP_SELLSTOP: result = OrderDelete( OrderTicket() );
//Show error code
if(result == false)
Alert("The order " , OrderTicket() , " failed to close.
Error code:", GetLastError() );
7. Save it under the folder Script.
8. Press F5 the compile it.
9. If your Navigator window is not opened, go to View and go to Scripts.
10. Find the script just created and right-click and select "Execute On Chart"
11. You will see that all the orders get closed.
You can use the same principle above to create an Expert Advisors.