When we close a market order, we are exiting the trade at the current market price, which would be the current Bid price for buy orders and the current Ask price for sell orders.
We close market orders using the OrderClose() function, which has the following syntax:
The table below describes each of these parameters:
The example below closes a buy market order, borrowed from the MACD Sample:
Here the close code starts with the for operator, continuously looping through the block of code to calculate the closing conditions.
The function OrderSelect() is used to examine the pool of opened orders, looking for the matching symbol, as well as the order types (OP_BUY or OP_SELL).
The last, and most important condition for this block of code, is to watch for the strategy conditions for exiting, which in the example above is the MACD exit conditions.
Once the open position symbol and order types are identified, and the MACD exit conditions are met, then the OrderClose() function can be deployed, the parameters of which are discussed in the table above.
It is can be useful to work with a custom close function because then you can can invoke it easily from within your Start() function whenever you have the need to close an order by a any set of conditions. Your custom close function should examine the pool of currently open orders, identifying your order types along with their magic numbers.
We have chosen close() as the name of our custom close function, and whenever we want to invoke it, we simply have to insert that one word after our close conditions, as in the usage example above.
The second line initiates the function if there is more than zero total open positions. The third line examines the pool of currently open orders, counting them. The fourth line invoke the OrderSelect() function in order to select these counted orders for further processing.
We have constructed only one parameter for the custom close function, and that is the variable int type in parenthesis (). This parameter is going to be the identifier of our order type. In the custom function, we indicate that type will equal (==) either OP_BUY or OP_SELL, and so we when we invoke close(), we must indicate if close() is close (OP_BUY) or close (OP_SELL), as in the usage example above. In the function, we associate type==OP_BUY and OrderType==OP_BUY together with the ampersand (&&).
We also want to make sure that we are selecting buy orders of the correct symbol and magic number, as you can in line 6:
Refresh Rates() is a function that refreshes the rates of the currency pair, so at to get filled at the most current rates.
Lastly, we deploy the OrderClose() function, the parameters of which can be found in the table above.