MQL4 BASICS - CREATE YOUR OWN AUTOTRADING EXPERT ADVISORS FOR FREE

Structure of an MQL4 Program

MQL4 programs, whether they're scripts, indicators, or Expert Advisors (EAs), have a standard structure. This structure ensures that the program functions correctly within the MetaTrader 4 platform. Let's explore this structure in more detail.

Program Types

In MQL4, there are primarily three types of programs:

Basic Structure

Most MQL4 programs follow a standard structure, consisting of:

  1. Preprocessor Directives: Used for including external files or setting compiler conditions. Example: #include, #property, or extern bool, input double ect... (These are all accesible from the MT4 terminal without the need to go into the EA source code. Simply right click the chart with the EA on it and open "Expert Advisors -> Properties")
  2. Global Variables: Variables that are accessible throughout the program.
  3. Initialization Functions: Functions that run once when the program starts. Example: int OnInit() for EAs and Scripts.
  4. Deinitialization Functions: Functions that run when the program stops. Example: void OnDeinit().
  5. Main Functions: The core part of the program. For EAs, this is the void OnTick() function that runs on every new tick of data. (Your main code is in this section)
  6. Additional Functions: Custom functions to break up the code and make it more modular and readable.

Example

Here's an example of an Expert Advisor structure (Explanation to follow):

As we continue, we will expand on this EA. Notice the use of forward slashes //. Use these to write comments that the EA will ignore, but you can use as helpful reminders. They are written here to help give you explanations for each action taken in the EA.

Be sure to take your time and read SLOWLY as coding is very logic based and needs your full attention.

Once it has been grasped though, it opens up a whole new world of possibilities.

The following presents an overly detailed explanation of some key aspects of an expert advisor. Although it is a little lengthy, it is to fully explain these key parts to help eliminate guess work later on.



//////////////////////////////
// We will put some basic info about the Ea here and some #include files
/////////////////////////////


#property copyright "Copyright 2023, www.mql4trader.com."
#property link      "https://www.mql4trader.com"
#property version   "1.00"
#property strict
#include <stderror.mqh>
#include <stdlib.mqh>


///////////////////////////////////
// External items go below here... These are items that can be altered by the user via expert properties.
///////////////////////////////////


input double LotSize = 0.1; 

// We will use this to customize our trades lot sizes


extern bool TradingEnabled = true; 

// We will use this to turn on or off our trading operations later on, from the MT4 terminal


/////////////////////////////////
/// Global variables go here ////
/////////////////////////////////


double CalculateSpread() 
 
 { return Ask - Bid; }
 
 
 //////////////////////////////
 
// The above is a Custom function to calculate the spread...

// This will return the value of Ask-Bid OR whatever other calculations you tell it to. In this case we will use it to tell us the spread of whatever chart the EA is open on.

// return is being used here to "return" to us the value that is the result of "Ask - Bid"

// When we call on CalculateSpread later on in the EA it will perform this calculation and use its value for whatever we ask it to..

////////////////////////////////

// Lets create a bool now, that we will use later..

////////////////////////////////
bool MyFirstCondition=false; ///
///////////////////////////////


// This bool will start off false when the EA is first initialized... Later we will create a condition to trigger it to "true". We will also create a condition that will reset it back to false. 

// These are very helpful when you have several conditions that need to be met before opening trades or performing other actions...


////////////////////////////////////
// Expert initialization function //                
// Initialization code goes here //
///////////////////////////////////

int OnInit()
  
  { return(INIT_SUCCEEDED); }
  
  
  // This is when the EA starts up... It will send a message that it was succesfully initialized.
  
  
/////////////////////////////////
// Deinitialization code here //
////////////////////////////////


void OnDeinit(const int reason)

  {
  
// These are commands that will occur when the EA is stopped or removed..

// For example you could tell the EA to delete all chart objects when the EA is removed. You don't have to include this in your EA if you don't want to...

// We have not added any instructions here...

  }
  

///////////////////////////////
// OnTick Function goes here //
//////////////////////////////


void OnTick()

  {
  
// Trading logic here/// 

// This is where everything thing goes that needs to be calculated on every new tick. Between these brackets...

// We will add in our conditions for trade entries and closing here.... Also our indicators we are using will be here... and so on.

// For now though, we will simply ask the EA to calculate and print the spread for us if our first condition is true OR to print us a message if it is not false... 

// We have not created any conditions to set MyFirstCondition to true though, so the EA will never Print the spread (Until we give the EA a way to set MyFirstCondition to true.)


/////////////////////////////////////
// This is how you check if a bool is true.
/////////////////////////////////////


if (MyFirstCondition) 

{ Print("The Spread is: ",CalculateSpread()); }

  
  // This is an example of using the Print function, based on a condition being met... 
  
  // It will Print the Spread for us, from our calculation in the global variables area...
  
  
/////////////////////////////////////
// Using ! we are checking if a bool is false... 
//////////////////////////////////////

if (!MyFirstCondition) 

{ Print("Sorry, but MyFirstCondition is still false"); }


// Since our bool "MyFirstCondition" is indeed false (As we have made no method yet for it to be changed to true), this condition will pass through, to give us the Print statement we have asked it to...

//////////////////////////////////////
// End of all OnTick functions...
// Let's tell the EA to return to the top and run again...
/////////////////////////////////////

 return;
 
// We have now told the EA to start over again

  } // This final bracket closes in our initial OnTick bracket.
  

Example Breakdown

Let's delve into the specifics of the MQL4 program example:

1. Program Header and Comments

The header section, demarcated by comments, typically includes the file name and copyright information. Comments (starting with '//') are not executed and serve as documentation for the programmer.


2. Property Directives

Property directives are special instructions that provide MetaTrader with information about the script, such as the script's copyright, a link for reference, its version, and whether it should operate in strict mode. Strict mode enforces explicit variable declaration and stricter error checks.


3. Include Directives

These directives import external MQH files, such as 'stderror.mqh' and 'stdlib.mqh', which contain standard functions and error handling routines. This helps in reusing code and maintaining standard functionality across various scripts.


4. External and Input Parameters

External ('extern') and input parameters define values that can be modified directly from the MetaTrader interface, enhancing user interaction. For instance, 'LotSize' and 'TradingEnabled' can be adjusted in the EA settings, allowing traders to modify EA behavior without changing the code.


5. Global Variables and Custom Functions

Global variables maintain their values throughout the program and can be accessed from any part of the script. Custom functions, like 'CalculateSpread', encapsulate specific logic or calculations, which promotes code reusability and readability.


6. Initialization Function - OnInit()

This special function is called when the EA or script is first attached to a chart. It's used for initial setups, such as initializing variables or setting up indicators. The 'INIT_SUCCEEDED' return value signals successful initialization.


7. Deinitialization Function - OnDeinit()

Triggered when the EA is removed from the chart, this function handles cleanup activities like closing files or deleting dynamically created objects. This is essential for efficient resource management.


8. Main Trading Function - OnTick()

The core of an EA, 'OnTick' is executed on every new market tick. This function contains the operational logic of the EA, such as analyzing market conditions, executing trades, and managing open positions.

This detailed breakdown explains the structure and components of an MQL4 program, clarifying how each part contributes to the overall functionality of the script.


Summary:

In summary, while this code lays out the basic structure of an MT4 EA, it doesn't execute any trading actions in its current form. It only provides a mechanism to calculate the spread based on the provided input, but the EA does not use this function in any trading logic as of now.

The EA also demonstrates a usage of the "if" statement and the Print function for demonstration purposes.


Conclusion

Understanding the structure of an MQL4 program is crucial to developing functioning and efficient trading tools. This structure ensures clarity, modularity, and the effective operation of your program within the MetaTrader 4 platform. Feel free to copy and paste the code provided into your MetaEditor and save it as whatever you like. Hit compile and we can use this EA as a base to create your first EA.

NEXT UP: Data types, variables, and constants.