How to Close ALL Trades with a matching Magic Number

 

Good afternoon forum,

I have created a grid bot which trades in both directions (treated separately); the initial buy order and subsequent sell orders have their magic number set as: 1111. The initial sell order and subsequent buy orders have their magic number set as: 2222. 

Each time an opening trade is triggered, declaring whether it is a buy/sell and a magic number are both passed into the section of code below to execute a trade. When I want to close, I either have:

CloseOrdersByMagic(InpMagicNumber1); // 1111

or

CloseOrdersByMagic(InpMagicNumber1); // 2222

Can anybody please explain what I would need to type into void CloseOrdersByMagic to loop through all my open trades, identify all the ones with the corresponding magic number (will be a mix of buy/sell orders) and close these all in one go?

CPerry.

void PlaceOrder(ENUM_ORDER_TYPE orderType, int magicNumber)
{
    double lotSize = LotSize;
    double currentPrice = orderType == ORDER_TYPE_BUY ? SymbolInfoDouble(Symbol(), SYMBOL_ASK) : SymbolInfoDouble(Symbol(), SYMBOL_BID);
    double orderPrice = NormalizeDouble(currentPrice, _Digits);
    
    MqlTradeRequest request;
    ZeroMemory(request);
    
    request.action = TRADE_ACTION_DEAL;
    request.symbol = Symbol();
    request.volume = lotSize;
    request.type = orderType;
    request.magic = magicNumber;
    request.deviation = 5;
    request.type_filling = ORDER_FILLING_IOC;
    request.type_time = ORDER_TIME_GTC;
    request.price = orderPrice;
    
    MqlTradeResult result;
    ZeroMemory(result);
    
    int ticket = OrderSend(request, result);
}

void CloseOrdersByMagic(int magicNumber)
{
    
}

CPerry.

 

Put it in a for loop:

for(int i = 0; i < PositionsTotal(); i++)
{
   if (PositionGetSymbol(0) == _Symbol && PositionGetInteger(POSITION_MAGIC) == MagicNumber)
   {
       trade.PositionClose(PositionGetInteger(POSITION_TICKET));
   }
}

You'll need a CTrade object somewhere, and to include the Trade.mqh.

#include <Trade\Trade.mqh>
...
CTrade trade;
 
Scott Allen #:

Put it in a for loop:

You'll need a CTrade object somewhere, and to include the Trade.mqh.

Thank you very much!

 
Scott Allen #:

Put it in a for loop:

You'll need a CTrade object somewhere, and to include the Trade.mqh.

Sorry, I still consider myself a novice to EA creating and understanding the MQL5 language.

From what I understand, the CTrade Object is a class for easy access to the trade functions and Trade.mqh is a library of these functions that MT5 offer but why do I need them in particular for this problem? Is it not more efficient to take the function I need and place it directly into my code for efficiency purposes or am I not understanding?

When I press compile, my elapsed time went from around 800msec to 1500msec.

What is a good elapsed time I should aim for or does it just need to be below a certain value?