Unable to Select order after partial close

 

Good day all,

I have some issue with my EA when trying to close an order partially and then work on the remaining order. More clearly, what I want to achieve with my EA is the following:


1 - Buy a Short or Long position if there is no position already open from the same EA and the condition to Sell or Buy is true:

void OnTick()
  {
  
   if(!CheckIfOpenOrdersByMagicNB(magicNB))//if no open orders try to enter new position
   {
      if(ConditionToShort() == true) //shorting if condition to short is true.
      {
         openOrderID = OrderSend(NULL,OP_SELL,lotSize,Bid,10,StopLossShort,0,NULL,magicNB);
         if(openOrderID < 0) Alert("order rejected. Order error: " + GetLastError());
      }
      else if(ConditionToBuy() == true)//buying if condition to buy is true.
      {           
          openOrderID = OrderSend(NULL,OP_BUY,lotSize,Ask,10,StopLossLong,1000,NULL,magicNB);
          if(openOrderID < 0) Alert("order rejected. Order error: " + GetLastError());
      }
   }


2 - If there is already a position open, I want to either close the position completely or close half of the position:

else if(OrderSelect(openOrderID,SELECT_BY_TICKET)==true) //else already have a position open, update orders if need too.
   {
         int orderType = OrderType();// Short = 1, Long = 0

         double TakeProfitLong; 
         double TakeProfitShort;
            
         if (OrderType == 1)//short position
         {
            if (ConditionToCloseShort() == true)//Close Short position fully
            {
                CloseShortOrder = OrderClose(openOrderID,OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK),10);
            }
            else if (Condition1ToCloseShortHalfLot() == true)//Close half of the Short position.
            {
                ModifyOrderID = OrderModify(openOrderID,OrderOpenPrice(),NewStopLossShort,0,0);
                double NewLots = NormalizeDouble((OrderLots()*0.5),2);
                CloseShortHalfLot1 = OrderClose(openOrderID,NewLots,TakeProfitShort,10);
            }
         } 
         else//long position
         {
            if (ConditionToCloseLong() == true)//Close Long position fully
            {
                CloseLongOrder = OrderClose(openOrderID,OrderLots(), MarketInfo(OrderSymbol(), MODE_BID),10);
            }
            else if (Condition1ToCloseLongHalfLot() == true)//Close half of the Long position.
            {
                ModifyOrderID = OrderModify(openOrderID,OrderOpenPrice(),NewStopLossLong,9999999,0);
                double NewLots = NormalizeDouble((OrderLots()*0.5),2);
                CloseLongHalfLot1 = OrderClose(openOrderID,NewLots,TakeProfitLong,10); 
            }     
         } 
    }

3 - Finally, and here is where my problem comes, if after the EA closed half of the position the other half is still open, I want to close the remaining half position if a condition (same condition which was used in step 2 to close the position in full) is met. My issue is not related to the conditions, but to how to manipulate the remaining partial condition. When closing half of the position I understand the EA closes the position in full and then opens a new one with a new ticket number, and I don't know how to make the EA handle the order with the new ticket number. The last part of my code is as follows:

else if (OrderSelect(OrdersTotal(),SELECT_BY_POS) == true)//If partial order remains open set a new condition on when to close it. 
    {
        int orderType = OrderType();

        if (orderType == 1 && ConditionToCloseShort() == true)//short position
        {
            CloseShortHalfLot2 = OrderClose(OrdersTotal(),OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK),10);
        }
        else if(orderType == 0 && ConditionToCloseLong() == true)//long position
        {
            CloseLongHalfLot2 = OrderClose(OrdersTotal(),OrderLots(), MarketInfo(OrderSymbol(), MODE_BID),10); 
        }     
    }    
  }  


I cannot get my EA to close the partial position, and it keeps running and running until it touches the Stop Loss set in stage 2 above in my "ModifyOrderID". These are the errors I get in my journal when backtesting my EA:


"unknown ticket 2 for OrderClose function"

"OrderClose error 4108"

"unknown ticket 2 for OrderModify function"

'OrderModify error 4108"


Please see if someone can help me with this.

Thanks!!

 
  1. Why did you post your MT4 question in the Root / MT5 EA section instead of the MQL4 section, (bottom of the Root page?)
              General rules and best pratices of the Forum. - General - MQL5 programming forum
    Next time post in the correct place. The moderators will likely move this thread there soon.

  2. ModifyOrderID = OrderModify(openOrderID,OrderOpenPrice(),NewStopLossShort,0,0);
    double NewLots = NormalizeDouble((OrderLots()*0.5),2);
    CloseShortHalfLot1 = OrderClose(openOrderID,NewLots,TakeProfitShort,10);
    Perhaps you should read the manual. Modify and Close returns a bool.
  3. Lots must be normalized to lotStep and the close amount and the remaining amount must both be at least minlot.

  4. else if (OrderSelect(OrdersTotal(),SELECT_BY_POS) == tru
    If there are n orders, their indexes are [0 … n-1]
  5. Magic number only allows an EA to identify its trades from all others. Using OrdersTotal/OrdersHistoryTotal (MT4) or PositionsTotal (MT5), directly and/or no Magic number filtering on your OrderSelect / Position select loop means your code is incompatible with every EA (including itself on other charts and manual trading.)
              Symbol Doesn't equal Ordersymbol when another currency is added to another seperate chart . - MQL4 programming forum
              PositionClose is not working - MQL5 programming forum
              MagicNumber: "Magic" Identifier of the Order - MQL4 Articles
              Orders, Positions and Deals in MetaTrader 5 - MQL5 Articles

  6. CloseShortHalfLot2 = OrderClose(OrdersTotal(),OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK),10)
    The first parameter to Close is a ticket number, not a count.
  7. MI is unnecessary, just use OrderClosePrice()
 

Hi William, thanks for your response.

Please see my comments:

1. Noted and sorry about it.

2. Indeed I did declared both as bool. This part of the code seems to be working fine, the order does get closed partially.

3. Yes both points are ok in my code.

4. Noted. I have amended my code as follows, using one function you shared in a previous topic to get the ticket number from last order:

else if (OrderSelect(LastOpenTicket(),SELECT_BY_TICKET) == true)//If partial order remains open set a new condition on when to close it. 
    {

        if (OrderType() == 1 && ConditionToCloseShort() == true)//short position
        {
            CloseShortHalfLot2 = OrderClose(LastOpenTicket(),OrderLots(), OrderClosePrice(),10);
        }
        else if(OrderType() == 0 && ConditionToCloseLong() == true)//long position
        {
            CloseLongHalfLot2 = OrderClose(LastOpenTicket(),OrderLots(), OrderClosePrice(), MODE_BID),10); 
        }     
    }    
  }   
//+------------------------------------------------------------------+

int LastOpenTicket(){
    datetime lastTime  = 0;
    int      lastTicket = -1; // None open.
    for(int pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
        OrderSelect(pos, SELECT_BY_POS)                 // Only my orders w/
    &&  OrderMagicNumber()  == 22222             // my magic number
    &&  OrderSymbol()       == Symbol()                 // and my pair.
    &&  OrderOpenTime()     >=  lastTime
    &&  OrderTicket()       >   lastTicket
    ){
      lastTime   = OrderOpenTime();
      lastTicket = OrderTicket();
    }
    return(lastTicket);
}

5. Noted. I do have a function to filter by magic number, this is working fine, is not my concern.

6.  and 7. Both noted, I amended my code accordingly as per my point 4.


However I still get the same issue, my EA does not seem able to manipulate the order that is left open after the partial closure. Any thought of what could be the issue??

 
In future please post in the correct section
I will move this topic to the MQL4 and Metatrader 4 section.
 
Keith Watford:
In future please post in the correct section
I will move this topic to the MQL4 and Metatrader 4 section.

Noted Keith, sorry about it I didn't realize.

 
Juanito8620: my EA does not seem able to manipulate the order that is left open after the partial closure. Any thought of what could be the issue??
  1. "Doesn't work" is meaningless — just like saying the car doesn't work. Doesn't start, won't go in gear, no electrical, missing the key, flat tires — meaningless.

  2. Do you really expect an answer? There are no mind readers here and our crystal balls are cracked.

  3. We can't see your broken code.

  4. How can we know what it's doing and what you want it to do?

  5. With the information you've provided — we can only guess. And you haven't provided any information for that. Do you get LastOpenTicketafter the partial close?

  6. Whether you used strict or not. Always use strict. Fixing the warnings will save you hours of debugging, but you must understand the differences.


Reason: