How to add closing conditions into an expert advisor

Now you are going to learn how to use closing conditions to close your trades, instead of just mere stoploss and takeprofit settings.

Let's pretend you want to close all open sell trades, when the last 3 bars in a row have gone up in price... How would we code this?

What if you want to close all open buy trades, when the last bar was higher than 71 on the RSI indicator... How would you code that?

This is what you will learn in this chapter of the beginners MQL4 Tutorial.

Step 1: How to close a trade

The first thing you need to know is how to close an open trade

Using MagicNumber as an ID reference.

It is extremely easy to close a trade. You just need to identify the trade you want to close, using the MagicNumber is the easiest way.

To do this always include the magicnumber of the trade you have open, that you want to close.

For example, if you have a buy trade opened under MagicNumber1, you will write, as a part of your condition, that if the open trade has MagicNumber1 connected to it, continue on to close the trade.

Like so:

if((OrderMagicNumber()==MagicNumber1)&&(MORE CONDITIONS HERE) {CLOSE TRADE CODE HERE}

The code that closes an open trade

Do perform the actual function of closing a trade, you simply call upon the OrderCLose function. Just like with the OrderSend function, the MetaEditor will autofill what you need. We will show you a code snippet anyway though.

For example, to close a buy trade that uses MagicNumber1:

if((OrderMagicNumber()==MagicNumber1)&&(MORE CONDITIONS HERE))

{int BuyClose=OrderClose(OrderTicket(),Lots,Bid,Slip,Red);}

If you were closing a sell trade, you would replace Bid, with Ask and give the int "BuyClose" a different name like "SellClose".

You can connect Lots to an extern double as well as slip to an extern int.

If you don't know what this is, you need to read the chapter on creating customizable variables.

Closing Conditions

Closing conditions work exactly the same as opening conditions as explained fully in the previous chapter How to add in buying and selling conditions

Please refer here to learn how to create many types of different conditions, using bars, indicators and price changes.

NEXT UP --->

How to prevent an expert advisor from entering more than one trade at a time