How to add closing conditions into an expert advisorNow 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 Buy trades for a certain symbol, 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 on this page. |
Step 1: How to close a tradeThe first thing you need to know is how to select an open trade It is extremely easy to close a trade, but first you need to select it using the following code:
You just need to identify the trade you want to close... If you are using magic numbers, you can narrow it down even more, if not then by symbol, like in the above code is enough. For example, if you have a buy trade opened under the name MagicNumber1, you will write, as a part of your condition, that if the open trade has MagicNumber1 connected to it and is a buy trade, continue on to close the trade. Like so:
The code that closes an open tradeTo 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 and closes after 3 bullish candles close in a row:
If you were closing a sell trade, you would replace Bid, with Ask and give the int "BuyClose" a different name like "SellClose" and search for sell trades using "OrderType() == OP_SELL". If you don't have a magicnumber in use and just want to close a trade based on its symbol matching the open chart, you would replace the OrderMagicNumber()==MagicNumber1 with: OrderSymbol()==Symbol() . Closing Conditions Closing conditions work exactly the same as opening conditions as explained fully in 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 opening more than one trade at a time |