Search code examples
mql4metatrader4

Trades doesn't close on the mql4 strategy


// Define input parameters
input int rsiLength = 10;
input int rsiHigh = 10;
input int rsiLow = 05;
input int stopLoss = 11;
input int trailPoints = 20;
input int trailOffset = 10;

// Define variables
int longCondition = 0;
int shortCondition = 0;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
   // Calculate RSI
   double rsiValue = iRSI(NULL, 0, rsiLength, PRICE_CLOSE, 0);

   // Check long condition
   if (rsiValue > rsiHigh)
      longCondition = 1;
   
   // Check short condition
   if (rsiValue < rsiLow)
      shortCondition = 1;

   // Execute long trade
   if (longCondition == 1)
   {
      OrderSend(Symbol(), OP_BUY, 1, Ask, 3, 0, 0, "Buy Order", 0, 0, Blue
      );
      longCondition = 0; // Reset condition after execution
   }

   // Execute short trade
   if (shortCondition == 1)
   {
      OrderSend(Symbol(), OP_SELL, 1, Bid, 3, 0, 0, "Sell Order", 0, 0, Red);
      shortCondition = 0; // Reset condition after execution
   }

   // Check and manage existing orders
   ManageOrders();
}
//+------------------------------------------------------------------+
//| Function to manage existing orders                               |
//+------------------------------------------------------------------+
void ManageOrders()
{
  for (int i = OrdersHistoryTotal() - 1; i >= 0; i--)
  {
    if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))
    {
      // Check for existing position in the same direction
      if (OrderSymbol() == Symbol() && OrderType() == OP_BUY) {
        continue; // Skip this order if there's an existing long position
      }
      if (OrderSymbol() == Symbol() && OrderType() == OP_SELL) {
        continue; // Skip this order if there's an existing short position
      }

      // Check for open long orders
      if (OrderSymbol() == Symbol() && OrderType() == OP_BUY)
      {
        // Check for stop loss
        double stopLossLevelBuy = OrderOpenPrice() - stopLoss * Point;
        Print("Buy Stop Loss Level: ", stopLossLevelBuy);
        if (OrderOpenPrice() - Bid >= stopLoss * Point)
        {
          Print("Closing Buy Order due to Stop Loss");
          OrderClose(OrderTicket(), OrderLots(), Bid, 3, Red);
        }
         
        // Check for trailing stop
        double trailStopLevelBuy = OrderOpenPrice() + trailPoints * Point - trailOffset * Point;
        Print("Buy Trailing Stop Level: ", trailStopLevelBuy);
        if (Bid <= trailStopLevelBuy)
        {
          Print("Closing Buy Order due to Trailing Stop");
          OrderClose(OrderTicket(), OrderLots(), Bid, 3, Blue);
        }
      }

      // Check for open short orders
      if (OrderSymbol() == Symbol() && OrderType() == OP_SELL)
      {
        // Check for stop loss
        double stopLossLevelSell = OrderOpenPrice() + stopLoss * Point;
        Print("Sell Stop Loss Level: ", stopLossLevelSell);
        if (Ask - OrderOpenPrice() >= stopLoss * Point)
        {
          Print("Closing Sell Order due to Stop Loss");
          OrderClose(OrderTicket(), OrderLots(), Ask, 3, Red);
        }
         
        // Check for trailing stop
        double trailStopLevelSell = OrderOpenPrice() - trailPoints * Point + trailOffset * Point;
        Print("Sell Trailing Stop Level: ", trailStopLevelSell);
        if (Ask >= trailStopLevelSell)
        {
          Print("Closing Sell Order due to Trailing Stop");
          OrderClose(OrderTicket(), OrderLots(), Ask, 3, Blue);
        }
      }
    }
  }
}

This is an RSI based expert defines a long condition based on the RSI crossing above the high level as defined. If this condition is true, it enters a long position. Short condition is based on the RSI crossing below the low level as defined.

Long Position Exit Logic: The long position exit condition is defined using stopLoss: This sets a fixed stop loss level for the long position. If the current price falls below this level, the long position is exited to limit potential losses. trailPoints: This sets the number of points by which the trailing stop follows the highest price reached since the position was opened. If the price retraces by this amount from the highest point, the position is closed. trailOffset: This sets an additional offset for the trailing stop. It helps in avoiding premature exits due to minor price fluctuations.

Short Position Exit Logic: The short position exit condition is also defined using stopLoss: This sets a fixed stop loss level for the short position. If the current price rises above this level, the short position is exited to limit potential losses. trailPoints: Similar to the long position, this sets the number of points by which the trailing stop follows the lowest price reached since the position was opened. If the price retraces by this amount from the lowest point, the position is closed. trailOffset: This sets an additional offset for the trailing stop, similar to the long position.

The trades doesn't seem to close at profit or at stop loss and even opens multiple trades in the same direction and closes them all once the equity reaches 0.

I am unable to troubleshoot the logic to close the logic.

Please help


Solution

  • I think you are examining the wrong pool of orders with this function:

    void ManageOrders()
      {
        for (int i = OrdersHistoryTotal() - 1; i >= 0; i--)
        {
          if (OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))
          { ... }
    

    You're checking history orders. Use MODE_TRADE instead?