metatrader closing trade before close signal and opening the trade again

 

Good Afternoon


I've just started an EA, and I coded the Stochastic Oscillator aspect of it. Upon running it and checking results, i found that metatrader has closed the trade before the close signal and the opened a new trade.

All the trades of this nature all seem to close at approximately the same value.

This is the stochastic code: 

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2018, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
input int k = 21;
input int d = 14;
input int slowing = 14;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Stochastic(bool &stoch_buy, bool &stoch_sell)
  {
   stoch_buy = False;
   stoch_sell = False;
   double stoch_overbought = 80;
   double stoch_oversold = 20;

   for(int i = 1; i < lookback; i++)
     {
      double stochastic = iStochastic(Symbol(), PERIOD_M5, k, d, slowing, MODE_SMA, 0, MODE_MAIN, i);
      double signal = iStochastic(Symbol(), PERIOD_M5, k, d, slowing, MODE_SMA, 0, MODE_SIGNAL, i);
      double prev_stochastic = iStochastic(Symbol(), PERIOD_M5, k, d, slowing, MODE_SMA, 0, MODE_MAIN, i+1);
      double prev_signal = iStochastic(Symbol(), PERIOD_M5, k, d, slowing, MODE_SMA, 0, MODE_SIGNAL, i+1);

      if((prev_stochastic < prev_signal) && (stochastic > signal) && (prev_stochastic < stoch_oversold) && (prev_signal < stoch_oversold))
        {
         stoch_buy = True;
        }

      if((prev_stochastic > prev_signal) && (stochastic < signal) && (prev_stochastic > stoch_overbought) && (prev_signal > stoch_overbought))
        {
         stoch_sell= True;
        }
     }
  }


This is the trade taking code:

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2018, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#import "Indicators/Stochastic.mq4"
#import "TakeProfit.mq4"
#import

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Trade()
  {
   bool stoch_buy = False;
   bool stoch_sell = False;

   Stochastic(stoch_buy, stoch_sell);

   if(OrdersTotal() == 0)
     {
      if(stoch_buy == True)
        {
         int buy = OrderSend(Symbol(), OP_BUY, 1.0, Ask, 5, 0, 0);
        }

      if(stoch_sell == True)
        {
         int Sell = OrderSend(Symbol(), OP_SELL, 1.0, Bid, 5, 0, 0);
        }
     }

   TakeProfit();
  }
//+------------------------------------------------------------------+

This is the take profit code:

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2018, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#import "Indicators/Stochastic.mq4"
#import "CloseTrades.mq4"
#import

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void TakeProfit()
  {
   bool stoch_buy = False;
   bool stoch_sell = False;

   Stochastic(stoch_buy, stoch_sell);

   if((OrderType() == OP_BUY) && (stoch_sell == True))
     {
      CloseTrades();
     }

   if((OrderType() == OP_SELL) && (stoch_buy == True))
     {
      CloseTrades();
     }
  }
//+------------------------------------------------------------------+

And this is the code to close the trade:

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void CloseTrades()
  {
// Update the exchange rates before closing the orders.
   RefreshRates();
// Log in the terminal the total of orders, current and past.
   Print(OrdersTotal());

// Start a loop to scan all the orders.
// The loop starts from the last order, proceeding backwards; Otherwise it would skip some orders.
   for(int i = (OrdersTotal() - 1); i >= 0; i--)
     {
      // If the order cannot be selected, throw and log an error.
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false)
        {
         Print("ERROR - Unable to select the order - ", GetLastError());
         break;
        }

      // Create the required variables.
      // Result variable - to check if the operation is successful or not.
      bool res = false;

      // Allowed Slippage - the difference between current price and close price.
      int Slippage = 0;

      // Bid and Ask prices for the instrument of the order.
      double BidPrice = MarketInfo(OrderSymbol(), MODE_BID);
      double AskPrice = MarketInfo(OrderSymbol(), MODE_ASK);

      // Closing the order using the correct price depending on the type of order.
      if(OrderType() == OP_BUY)
        {
         res = OrderClose(OrderTicket(), OrderLots(), BidPrice, Slippage);
        }
      else
         if(OrderType() == OP_SELL)
           {
            res = OrderClose(OrderTicket(), OrderLots(), AskPrice, Slippage);
           }

      // If there was an error, log it.
      if(res == false)
         Print("ERROR - Unable to close the order - ", OrderTicket(), " - ", GetLastError());
     }
  }
//+------------------------------------------------------------------+


Has anyone had this issue before or can see an error in the code. I just can't it.


Any help will be appreciated.

Kind Regards

 
  1.       double stochastic = iStochastic(Symbol(), PERIOD_M5, k, d, slowing, MODE_SMA, 0, MODE_MAIN, i);
          double signal = iStochastic(Symbol(), PERIOD_M5, k, d, slowing, MODE_SMA, 0, MODE_SIGNAL, i);
             int buy = OrderSend(Symbol(), OP_BUY, 1.0, Ask, 5, 0, 0);

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


  2. void TakeProfit(){
       
       if((OrderType() == OP_BUY)

    MT4: You can not use any Trade Functions until you first select an order.

  3.       double BidPrice = MarketInfo(OrderSymbol(), MODE_BID);
          double AskPrice = MarketInfo(OrderSymbol(), MODE_ASK);
    
          if(     OrderType() == OP_BUY ) res = OrderClose(OrderTicket(), OrderLots(), BidPrice, Slippage);
          else if(OrderType() == OP_SELL) res = OrderClose(OrderTicket(), OrderLots(), AskPrice, Slippage);

    MT4: You can use OrderClosePrice() instead of Bid/Ask and be direction independent — no need to check order type to get the close price.

  4.    for(int i = (OrdersTotal() - 1); i >= 0; i--){
          if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) == false)

    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/symbol 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 (2013)
              PositionClose is not working - MQL5 programming forum (2020)
              MagicNumber: "Magic" Identifier of the Order - MQL4 Articles (2006)
              Orders, Positions and Deals in MetaTrader 5 - MQL5 Articles (2011)
              Limit one open buy/sell position at a time - General - MQL5 programming forum (2022)

    You need one Magic Number for each symbol/timeframe/strategy. Trade current timeframe, one strategy, and filter by symbol requires one MN.