I am trying to code my EA where if my close conditions are met, I want my EA to close all the open trades ( there are potentially more than 1 open trades ).
Here is my code for the closing trade section and when I run it through the Strategy Tester, I noticed it doesn't close my trades.
Total=0; // Amount of orders
for(int i=1; i<=OrdersTotal(); i++) // Loop through orders
{
if (OrderSelect(i-1,SELECT_BY_POS)==true) // If there is the next one
{ // Analyzing orders:
if (OrderSymbol()!=Symb)continue; // Another security
Total++; // Counter of market orders
}
}
while(true) // Loop of closing orders
{
if (OrderType()==0 && Close_Buy_Condition==true) // Order Buy is opened & Close Buy Condition is true
{
for (c=Total-1; c>=0; c--)
{
RefreshRates(); // Refresh rates
Ans=OrderClose(OrderTicket(),Lot,Bid,Slippage); // Closing Buy
}
}
if (OrderType()==1 && Close_Sell_Condition==true) // Order Sell is opened & Close Sell Condition is true
{
for (d=Total-1; d>=0; d--)
{
RefreshRates(); // Refresh rates
Ans=OrderClose(OrderTicket(),Lot,Ask,Slippage); // Closing Sell
}
}
break; // Exit while
}
I don't know where do you set value for Ask
, Bid
and Lot
variables. But they've to change when you loop through your open positions.
You can try this function to close all positions:
bool CloseAllPositions()
{
double total;
int cnt;
while(OrdersTotal()>0)
{
// Close pending orders first, you can remove this section if you don't want pending orders to be deleted
total=OrdersTotal();
for(cnt=total-1; cnt>=0; cnt--)
{
if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
{
switch(OrderType())
{
case OP_BUYLIMIT :OrderDelete(OrderTicket()); break;
case OP_SELLLIMIT :OrderDelete(OrderTicket()); break;
case OP_BUYSTOP :OrderDelete(OrderTicket()); break;
case OP_SELLSTOP :OrderDelete(OrderTicket()); break;
}
}
}
// then close opened orders
total=OrdersTotal();
for(cnt=total-1; cnt>=0; cnt--)
{
if(OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))
{
switch(OrderType())
{
case OP_BUY:
if (Close_Buy_Condition==true) {
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_BID),3,Violet);
}
break;
case OP_SELL:
if (Close_Sell_Condition==true) {
OrderClose(OrderTicket(),OrderLots(),MarketInfo(OrderSymbol(),MODE_ASK),3,Violet);
}
break;
}
}
}
}
return true;
}
Edit:
if you don't want to deal with pending orders at all, use this code instead of OrdersTotal()
:
int GetNumOpenPositions() {
int total = OrdersTotal();
double OpenBuyOrders = 0, OpenSellOrders = 0, PendBuys =0, PendSells =0;
for( i=0;i<total;i++)
{
OrderSelect(i, SELECT_BY_POS );
if ( OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
{
int type = OrderType();
if (type == OP_BUY ) {OpenBuyOrders=OpenBuyOrders+1;}
if (type == OP_SELL ) {OpenSellOrders=OpenSellOrders+1;}
if (type == OP_BUYSTOP ) {PendBuys=PendBuys+1;}
if (type == OP_SELLSTOP ) {PendSells=PendSells+1;}
}
}
return (OpenBuyOrders + OpenSellOrders);
}
Then total orders would be