Understanding the FrameWork of an Expert Advisor in MQL4

Here you will learn the basics framework of an EA(Expert Advisor).

We will be walking through our Expert Advisor Template that was given FREE in the "How to use Meta Editor" chapter.

Please download it by clicking the link below. A new tab or window will open.

Simply copy and paste the code, over the current MACD_Sample Expert code, that comes with MetaEditor.

Now, save as a new file name and then hit compile.

Here is the link:

We have made this EA as simple and user friendly as possible. You can use it as a great reference point for your Expert Advisors.

Our greatest hope, is that we can explain this all, in terms you can understand. Not everyone has a coding mind and most of the coding information on the web, is a little overwhelming... Enjoy!

Once you have it open and ready to go, we can begin.

Step 1: Input Parameters

You should now have your MQL4 template page open. It should look like the picture above...

We are going to focus on the lines of code with "Extern" as the starting point

As you can see, there are a few different ones.

The purpose of each of these is to make something customizable from outside of the MetaEditor.

The two pictures below shows these exact inputs outside of MetaEditor, as used in the "Strategy Tester" and on a chart, via the "Expert Advisor Properties".

This means that when using the "Strategy Tester", you can change all of these inputs without changing your MQL4 code.

Maybe you want to tweak your "Take Profit" and "Stop Loss" levels, in order to find the perfect amount, for maximum profit. This may take you 10 runs on the "Strategy Tester".

Instead of editing code every time, in the Meta Editor, you can just change these parameters directly from the"Strategy Tester", by clicking "Expert Properties", as seen below...

The same applies for an "Expert Advisor" that you have attached to a chart.

Maybe on your chart, you want to start with only a 1 Lot investment, until your bankroll has grown high enough to change it to a 2 Lots investment.

You can do that by "Right Clicking" the chart with your Expert Advisor attached to it... Then going to "Expert Advisors"... Then clicking "Properties".

Now, you can adjust your lot number, to the new investment amount that you want to use, without having to change your MQL4 code.

The picture below shows this and shows the "Lots" input, in the "red square"...

Ok, so let's address these different types of "Input Parameters".

"extern" stands for external, as described above.

The next parts represent the type of inputs that can be handled by the "extern variable"

extern int

Extern int, is an extern variable, that must be a whole number (NO DECIMALS), between -2,147,483 648 and 2,147,483,648. No clue as to why they chose that number, for the max and min, but that's them!

extern double

And extern double, is just an external number that can handle decimals, such as 125.24, whereas an extern int can only handle the number 125.

In certain circumstances you will need the decimals and others you won't.

Let's do a quick example... Let's say you want to be able to have the ability to change your buy or sell point externally.

To do this we need to create an "extern double", so that we can use decimals, for our RSI INDICATOR that is used in the Expert Advisor Template.

In the following picture you will see that there is no customizable Buy or Sell Point, as of yet.

Now, we want to add in a Buy and Sell point. We will call them "BUYPOINT" and "SELLPOINT".

Here is the code we will use and will put it below the period, applied price, and barshift in the "Template Expert Advisor":

extern double BUYPOINT=22.25;

extern double SELLPOINT=76.75;

You can use whatever numbers you want in the above code. It all depends on your strategy. Remember, this is where you are going to trigger a buy or sell, based on your RSI indicator.

There, now we just put that code into our Expert Advisor like so...

Now, if we used Extern int instead, it would still work, but only with whole numbers and NOT decimals.

To keep things understandable, we will jump forward, before moving on, in order to complete the usage of this example.

So now we have a "BUYPOINT" and a "SELLPOINT"... BUT FOR WHAT!??? HOW DO WE USE IT!??

Ok, ok, now we scroll down to our buy and sell "conditions" on the "Template Expert Advisor".

Right here...

As you can see in the picture above, our current "Open Sell" condition... in Human terms, says... "If RSI indicator(Named "RSI1CUSTOM" in our code) reaches "greater than(>)70", "halt1" alert has not occured and "tradeTime" is ok, we then Send a Sell order, using the number of Lots listed from our "extern double Lots=1;", at the top of the page and our "extern int Slip=10", at the top of the page.

Ok, so next, we want to make it so that we can change this SellPoint strategy, from outside of the MetaEditor. So now, we remove the number 70 in the "RSICUSTOM>70" bit of code and replace it with, "SELLPOINT".

This tells the autotrader to refer to our line of code at the top of the page that says extern double SELLPOINT=76.75;

What happens now, is that when the MT4 terminal runs through the code and gets to this spot, it refers to whatever that number is set to. We do the same with our BUYPOINT and the result will look like this...

And the outcome in the "MT4 TERMINAL" will be this...

You can now change these numbers on the fly, as they are attached to an EA or as you are testing in the strategy tester.

IMPORTANT: Just remember though, that these external, editable values, only change externally. They will stay changed externally, unless you hit reset. If you attach the EA to a new chart, the values will revert to the original code. So, if your code has your SELLPOINT set at 70 and you attach your EA to a EURUSD chart and change the SELLPOINT value to 75, that chart will operate under the 75. Now, if you attach the EA to a second chart, like USDJPY, it will operate under the original SELLPOINT number of 70. You can change this one to whichever number you like, as well and both EA'S will run with the different SELLPOINTS you have given them.

Extern string

At the moment, as with our MQL4 BASICS, strings can be a little beyond basics.

With the template you now have, you can do literally hundreds of thousands of operations, without having to learn hard coding.

That is our goal. To get you up and running, without having to learn the hard stuff.


To summarize Step one... Your input parameters are the values that you want to be able to change externally. They can be a BUYPOINT, your TakeProfit levels, your indicator settings, your time settings and so on. Anything in the input parameters is given a name by you. You use that name later on in your code to link its value, to that piece of code. Just like what you did with BUYPOINT and SELLPOINT.

Step 2: Program Starting Point

If you scroll down a bit farther past the input parameters, in your template.mq4 file, you will get to int start(){, as seen below...

This is the official starting place of your actual program. Any further instructions, other than external integers, doubles and what not, MUST go below this.

As you can see, but may not have noticed, the first brace has appeared... " { " . You will see a lot of these throughout your code. Parenthesis() and braces{} are used frequently.

Braces close in code statements.

Immediately after; int start(){ the left brace encompasses everything, until the very end of the code, where a final Right brace } encloses it all.

If you remove one of these braces your whole code will not work. So, they are very important.

Luckily when you hit compile, your errors will mention if there is one missing or misplaced.

Everything beyond this starting point is the functioning of the code.

Step 3: Little rules

Next, there are a couple little rules.

The first is "if (Bars>BarsCount)", as seen below...

This little rule is there to ensure that our autotrader does not make more than one trade per bar. Without it, you might send off 50 trades on one bar. That would be no good, so that's why it's there.

After that, you see a little bit of code that is in the picture below.

The only part in there that you ever need to worry about is the "MagicNumber1" and "MagicNumber2" parts. These magic numbers are like order ID numbers. Every Expert Advisor needs its own unique Magic Number for Buy orders and Sell orders.

If you don't make sure to change this number in each Expert Advisor, you will notice that only one trade is ever active at a time. This is because as long as one MagicNumber ID is in use, another one will not open, even if it is on a different chart, with a different EA.

So, just always remember to change these numbers, when creating new EAs and you will be just fine.

Step 4: Check Open Orders

Next, as you scroll down your "Template EA", is this piece of code, that has in its comments, "Check Open Orders". Refer to the picture below, please.

This bit of code is telling the program not to trade, if ordersTotal are greater than(>) 0. In other words, if there are any open orders, DO NOT OPEN any new orders. You can leave this code, as is.

Beneath it, is a string of code that also says, if a certain magic number is in use, not to open another order for that MagicNumber.

So, if a SELL ORDER is open, then no more SELL ORDER will be opened, unless you are operating a program that has more than one Sell, MagicNumbers, available for use(Two OPEN SELL conditions).

One new BUY ORDER can still be opened though, unless you add both "halts" to the OPEN BUY condition(Don't worry about this now though).

Step 5: Trade Times - Start Hour End Hour

For most EAs, you will be running them around the clock, but for some, depending on your strategy, you may want to avoid certain times of the day.

The picture below shows this little bit of code...

As you can see, the words "StartHour" and "EndHour" are highlighted in Red.

As, you probably have realized, that means they are "extern" inputs, from the very top of the code, as discussed in the previous steps.

So, you guessed it, they are editable through the "Strategy Tester" and on charts that the EA is attached to, as shown in the picture below.

As you can see the "StartHour" and "Endhour" relate to a 24 hour clock and will relate to the timezone you are using.

How to trade certain hours only:

Let's pretend you don't want any trades to open from 5am-6am, for whatever reason. Now if you are Mountain time, for example you will see on your chart that 24:00 is actually your 3:00pm. So you will have to alter and match up your chart times appropriately.

So, assuming you are on GMT timezone, then your 5am would actually be 14:00 on your chart time.

So, to make your EA avoid trading on that hour, you would have to change the inputs of the picture above to StartHour=15 and EndHour=13.

It will run until 13:59 and 59 seconds, then stop until 14:59 and 59 seconds, then continue on again and again, over and over.

The reason we are using 13 as the end hour instead of 14, is because the code says (Hour() <= EndHour). This symbol " <= " means "Less than or equal to". If we rewrote it to say just " < ", it would then be "Less than" and we would use 14 as our number. The "Equal to" part, makes it so that anywhere from 13:00 to 13:59 and 59 seconds, is still considered "Equal to" 13.

Step 6: Indicators Section

Moving right along down our lines of code in the "Template" Expert Advisor, we come to the indicator section. This is where the magic begins for your autotraders.

In this section of code you can add as many different indicators as you would like, to call upon, for use in your autotrader.

Currently the template uses, just the RSI INDICATOR, as seen in the picture below...

There are two RSI indicators in the code you are looking at. Both can be used, but only one can be customized outside of the MetaEditor.

As already mentioned, you can add as many indicators as you want.

If you want to use an RSI, MACD, Envelope and Bollinger Bands indicators all together, you can. It's easy!

The adding of more indicators will be covered in the chapter How to add Indicators to Expert Advisors

Now, a great feature of the MetaEditor, is its little, fill in the blanks, assistance.

If you go to where it says RSI1=iRSI(NULL,0 and now erase the ZERO and the COMMA, after the word NULL, and now retype a COMMA, a little popup will happen, as seen in the picture below...

It would pop up on its own if you had started writing the line of code from scratch too.

Now as you can see, it shows all the different inputs needed for that indicator. This can be helpful when you can't remember everything you need in an indicator.

It shows the following:

Const string Symbol, which is the currency pair, commodity or stock you are wanting to use the indicator for, however, if you just always use NULL, it will work on any of them.

Int timeframe, is the chart time frame you want to use your indicator on. When you use, 0, it works on all and uses the chart timeframe the EA is attached to.

Int period, is the period for the RSI INDICATOR. Standard period being 14, but you can use any period you want. Period means the same thing on all indicators.

ENUM_APPLIED_PRICE applied_price, is the applied price the indicator is using.

Standard is "Close". Instead of using the word close, you use numbers.

0=Close, 1=Open, 2=High, 3=Low, 4=Median, 5=Typical and 6=Weighted.

Int shift, is the shift of the indicator. It means how many bars back it is referring to.

The strategy tester will not work on 0, which is "Current bar", so it is best to use 1 and beyond.

What this means, is that if you have the shift set to 5 and your "OpenBuy" is to happen when the indicator reaches below 30, that it will not open the trade, until 5 bars have past.

This is because you have told it to make its move, based on a shift of five. So the current RSI indication will be based on what happened 5 bars ago.

This function has its usefulness depending on your strategy.


Next up in your code, is the "Open Buy" and "Open Sell" section, as seen below. This is where we tell the autotrader what to do.

This is where you take your strategy and put it into steps, for the Expert Advisor to follow.

In the picture above you see a few very simple conditions to open trades with.

They both basically say "If the RSI INDICATOR hits the BUYPOINT or SELLPOINT, No other orders are open with MagicNumber1 or 2 and Trading hours are ok, Open Buy or Sell."

This is a very simple opening strategy for both. You may have noticed that the code uses BUYPOINT and SELLPOINT from the STEP 1.

If you wanted to add in some more strategies, you just need to get creative.

&&: You must use && when adding new conditions. If you don't, you will get an error, when you compile.

Maybe you have a second indicator, you want to use for an additional condition OR maybe you want to say that the last bar close, MUST be less than 100 bars ago, in order for a Sell order to be Opened.

All you need to do for that is this: (Close[1] < Close[100] ) && and now put that at the start of your open condition, within the first parenthesis.

Your new Sell order would look like this:

Step 6: Closing Conditions

We have arrived at a very crucial point in the code. If you have scrolled down from the Opening conditions section, you will now be at the "Closing Conditions" section of the Template mql4 code.

Please refer to the picture below, noticing the two boxes. One red and one blue, outlining the code.

The red box contains a little snip of code, that simply means, if there is an order open, called openbuy or opensell, that the auto trader is to continue. If there isn't an order open, it has no need to read the rest of the EA, so it goes back to the start and continues running its loops.

If there is an order open, named "openbuy" or "opensell", then it will continue on to the closing conditions, for the currently open trades.

In the Blue Box, from the picture above, there are your closing conditions.

They basically say, "For this MagicNumber, if the RSI gets to Greater than 70, close the BuyOrder and for this MagicNumber, if the RSI gets to Less than 30, close the SellOrder.

You do not have to use these. You could just run on TakeProfit and StopLoss, but it is a good idea to have a fail safe or something to allow you to make more and lose less, than if you just had TakeProfit and StopLoss, as your closing strategy.

You can do all sorts of conditions here.

You can call on other indicators to perform closing conditions such as Moving Average, MACD, Ichimoku, Envelopes and so on.

You can also add in simple closes, that could, for example, close a SellOrder, when 3 bars in a row, have gone downwards in price and the RSI indicator is less than 30. This is translated as "the close price is less than(<) the open price" of a particular bar. You would just add in the following code, right after the "(RSI1<30)"...

&&(Close[1] < Open[1])&&(Close[2] < Open[2])&&(Close[3] < Open[3])

Your complete code would be:

Step 6: Take Profit - Stop Loss & Errors

The following code is not recommended to be changed, unless you know what you are doing. This code is here to calculate your TakeProfit levels and Stoploss levels, that you choose at the top of your code, where you have your 2 "extern int" for StopLoss and TakeProfit.

Below that, it is where your Error Messages come from, so you know how to fix any errors during trading, such as your StopLoss levels being to low.

It also corresponds to your MagicNumbers.

When your autotrader places an order, this first chunk of code, in the square Red Box in the picture below, tells the autotrader, how to modify your order properly, with the correct TakeProfit and StopLoss levels that you have provided it.

The Blue box, in the picture above, shows your Error Notification Code. You do not need to touch this code.


Hopefully this little run though, of our MQL4 code has helped you become more familiar with it and has helped you gain a better grasp on it.

It is one of those things that you will understand better as you get in there and tinker with it a bit. The sky is the limit for things you can do with an autotrader, so just know that there is almost always a way, and use your creativity to break through barriers.

Every single person can learn how to do this, but only the ones that break away from a rigid mindset can be successful at it

Come up with new ideas for trading strategies. Lay in bed and dream up ideas. Immerse yourself into trading to let your mind focus in on it fully.

There is a trading method available that can make you financially independent from any job. There is a trading method that can make you a millionaire. That method is INSIDE your OWN MIND. Go find it!

You may have to sift through thousands of ideas, but if you don't waste time holding onto ideas that aren't working, you will constantly be getting closer to the ones that will.

Test out your strategies until you run out of ways to lose! Once you're there, all you will have left is ways to WIN.

Be patient, Work Hard, Work Smart.

See you at the next chapter...

NEXT UP --->

How to add customizable variables into an Expert Advisor