MT4 - mql4 function for close any opened sell position?

I'm not very familiar with mt4. I want to close any sell position that is available, and if it is not available open a new buy position every time that function is executed. any solution or idea. I would greatly appreciate it. I am trying doing by this code but not working.order not closing.

///////

bool deleteLastSell()
{
  bool success = true;
  int lastSellOrder = -1;
  for (int i = OrdersTotal() - 1; i >= 0; --i) 
  {  
    if (OrderSelect(i, SELECT_BY_POS))
    {
      if (OrderType() == OP_SELL)
      {
        lastSellOrder = i;
        break;
      }
    }
  }
  if (lastSellOrder != -1)
  {
    if (!OrderClose(OrderSelect(lastSellOrder, SELECT_BY_POS), OrderLots(), Bid, Slippage))
    {
      Alert("Order #", OrderTicket(), " was not closed");
      success = false;
    }
  }
  else
  {
    Alert("No sell orders to delete");
  }
  return success;
}


//////////

Upvotes: 0

Views: 66

Answers (2)

4xPip Official
4xPip Official

Reputation: 31

The below Function search for any open sell position and close it. This function opens the buy position if no sell position was found, and returns false. If sell positions were closed, the function will not open a new buy order and will return true.

       bool deleteSellOpenBuy()
       {
        int isSellClosed = false;
        int slippage=5;
        for(int i = OrdersTotal() - 1; i >= 0; --i) // Cycle searching in orders
          {
           if(OrderSelect(i,SELECT_BY_POS) == true)
             {
              if(OrderSymbol() == Symbol() && OrderType() == OP_SELL)
                {
                 if(OrderClose(OrderTicket(),OrderLots(),Ask,slippage,clrCyan) == true)
                   {
                    Print(OrderTicket(),": Sell Order closed");
                    isSellClosed=true;
                   }
                }
             }
          }
        if(!isSellClosed)
          {
           //Open new buy order if no sell trade was found and closed
           double lotSize=0.01;
           double sl = NormalizeDouble(Ask - 200 * _Point, Digits);
           double tp = NormalizeDouble(Ask + 200 * _Point, Digits);
           int magicNumber=0;
           if(OrderSend(Symbol(),OP_BUY,lotSize,Ask,slippage,sl,tp,"",magicNumber,0,clrBlue) < 0)
             {
              Print("Buy Order failed with error #",GetLastError());
             }
           else
             {
              Print("Buy Order placed successfully");
              return false;
             }
          }
        else
           return true;
       }

Upvotes: 0

Mark SdS
Mark SdS

Reputation: 119

I would not use the Bid price, but rather the OrderClosePrice() see MQL4 reference That's my first thought on this.

Let us know what happens.

Upvotes: 0

Related Questions