Close all positions doesn't work here...

 

Hi,

I am a newbie on MQL5 and would need a bit of help on that code (hereafter).

The principle of this EA is quite simple. It is a buy only, conditionned at the entry by a SHORT RSI level AND a LONG RSI level AND a positive slope of SMA. If this happens on bar (n-1), the systems BUYS at the open of bar (n), with defined TP and SL levels.

My problem is that I defined both a time condition OR a SHORT RSI condition to exit the trade if one of them happens before SL or TP is reached. (Call of a CloseAllPositions function).

But none of these 2 conditions are working, and system only exits based on TP and SL...

If somebody could help and tell me why, that would be nice.

Thanks in advance.

BR,


#include <Trade\Trade.mqh>
#include <Tools\DateTime.mqh>
CTrade trade;

bool mySlope = false;
bool myRSIShort = false;
bool myRSILong = false;
bool myRSIShortOUT = false;
bool ACHAT = false;
bool VENTE = false;

int prev_total=0;

int myBar = 0;
bool NotTheSameBar = true;

double MyStartTime = 10.0;
double MyLastTime = 17.917;
double MyStopTime = 22.983;
bool TimeToTrade = false;
bool TimeToStop = false;

void OnTick()
  {

//+------------------------------------------------------------------+
//| Condition horaire        |
//+------------------------------------------------------------------+
 
   // Get the local time
   datetime time=TimeLocal();
  
   // Format the time and create a string
   string hoursAndMinutes = TimeToString(time,TIME_MINUTES);
  
   // Convert to string
   string HeureWord = StringSubstr(hoursAndMinutes,0,2);
   string MinuteWord = StringSubstr(hoursAndMinutes,3,2);
  
   // Convert to integer
   string HeureFigure = StringToInteger(HeureWord);
   string MinuteFigure = StringToInteger(MinuteWord);
  
   long Heure = StringToInteger(HeureWord);
   long Minute = StringToInteger(MinuteWord);
  
   double MyTime = Heure + Minute/60;
  
   if(MyTime >= MyStartTime && MyTime < MyLastTime)
      TimeToTrade = true;
      else
        {
         TimeToTrade = false;
        }
       
   if(MyTime >= MyStopTime)
      TimeToStop = true;
      else
        {
         TimeToStop = false;
        }
 
 //+------------------------------------------------------------------+
//| Status Positions        |
//+------------------------------------------------------------------+
   //--- declare and initialize the trade request and result of trade request
   MqlTradeRequest request;
   MqlTradeResult result;
   int total=PositionsTotal(); // number of open positions
   prev_total=total;

 //+------------------------------------------------------------------+
//| COndition de non répétition dans la même barre horaire        |
//+------------------------------------------------------------------+
   int bars = Bars(_Symbol,_Period);
  
   if (total<prev_total)
      NotTheSameBar=false;
     
   if (NotTheSameBar==false);
      if(myBar==bars)
         NotTheSameBar=false;
         else
           {
            NotTheSameBar=true;
           }
  
   myBar = bars;
 
//+------------------------------------------------------------------+
//| Checks Weighted Moving Average             |
//+------------------------------------------------------------------+
      // create an Array for several prices
      double myMovingAverageArray[];
     
      //define the properties of the Moving Average
      int movingAverageDefinition = iMA(_Symbol,_Period, 22, 0, MODE_SMA, PRICE_CLOSE);
     
      //sort the price array from the current candle downwards
      ArraySetAsSeries(myMovingAverageArray,true);
     
      // Defined MA, one line, current candle, 3 candles, store result
      CopyBuffer(movingAverageDefinition,0,0,3,myMovingAverageArray);
     
      // calculate MA for the current candle
      double myMovingAverageValue_1 = myMovingAverageArray[1];
      double myMovingAverageValue_2 = myMovingAverageArray[2];
     
      double Slope = (myMovingAverageValue_1 / myMovingAverageValue_2) - 1;
     
      if(Slope > 0)
         mySlope = true;
         else
           {
            mySlope=false;
           }

//+------------------------------------------------------------------+
//| Checks RSI             |
//+------------------------------------------------------------------+
      double myRSIShortArray[]; // Array to store RSI informations
      double myRSILongArray[]; // Array to store RSI informations
     
      int myRSIShortDefinition = iRSI (_Symbol,_Period,2,PRICE_CLOSE);
      int myRSILongDefinition = iRSI (_Symbol,_Period,22,PRICE_CLOSE);
     
     
      ArraySetAsSeries(myRSIShortArray,true);
      ArraySetAsSeries(myRSILongArray,true);
  
      //Calculate RSI for the current candle
      CopyBuffer(myRSIShortDefinition,0,0,2,myRSIShortArray);//Fill it
      CopyBuffer(myRSILongDefinition,0,0,2,myRSILongArray);//Fill it
     
      double myRSIShortValue = NormalizeDouble(myRSIShortArray[1],2);//Calcul
      double myRSILongValue = NormalizeDouble(myRSILongArray[1],2);//Calcul
     
      if(myRSIShortValue<15)
         myRSIShort = true;
         else
           {
            myRSIShort=false;
           }
          
      if(myRSILongValue>50)
         myRSILong = true;
         else
           {
            myRSILong=false;
           }
          
      if(myRSIShortValue>60)
         myRSIShortOUT = true;
         else
           {
            myRSIShortOUT=false;
           } 

//+------------------------------------------------------------------+
//| Synthèse : Condition ACHAT        |
//+------------------------------------------------------------------+
  
   if(TimeToTrade==true && NotTheSameBar==true && total == 0 && mySlope == true && myRSIShort == true && myRSILong == true)
      ACHAT = true;
         else
           {
            ACHAT=false;
           }      
  
//+------------------------------------------------------------------+
//| Order  IN          |
//+------------------------------------------------------------------+
  
   //Obtain the Ask/Bid Price
   double Ask = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_ASK),_Digits);
   double Bid = NormalizeDouble(SymbolInfoDouble(_Symbol,SYMBOL_BID),_Digits);
  
   if(ACHAT == true)
      trade.Buy(1,NULL,Ask,Bid-82,Ask+28,NULL);
      else
        {
        
        }



//+------------------------------------------------------------------+
//| Synthèse : Conditions VENTE        |
//+------------------------------------------------------------------+
  
   if(myRSIShortOUT == true || TimeToStop == true)
      VENTE = true;
         else
           {
            VENTE=false;
           }
      

//+------------------------------------------------------------------+
//| Order   OUT         |
//+------------------------------------------------------------------+
 
 
   if(VENTE == true)
   CloseAllPositions();
   else
        {
        
        }
     
  }
 
void CloseAllPositions()
{
   // from the number of positions count down to zero
   for(int i=PositionsTotal()-1;i>=0;i--) //look at all positions
   {
      //get the ticket number for the current position
      int ticket = PositionGetTicket(i);
     
      //close the current position
      trade.PositionClose(i);
   }
}  
  
//+------------------------------------------------------------------+

 

Forum on trading, automated trading systems and testing trading strategies

Closing Multiple Trades at once

fxsaber, 2017.12.07 09:01

I re-wrote the code slightly

// MQL4&5-code
#include <MT4Orders.mqh> // https://www.mql5.com/en/code/16006

#property strict

string CorrectSymbol( string &Symb )
{
  return(Symb = ((Symb == NULL) || (Symb == "")) ? _Symbol: Symb);
}

bool PlaceHedge( const string Symb )
{
  double Lots = 0;
    
  for (int i = OrdersTotal() - 1; i >= 0; i--)
    if (OrderSelect(i, SELECT_BY_POS) && (OrderType() <= OP_SELL) && (OrderSymbol() == Symb))
      Lots += OrderType() ? OrderLots() : -OrderLots();
      
  Lots = NormalizeDouble(Lots, 2);    
      
  return(((Lots > 0) && (OrderSend(Symb, OP_BUY, Lots, SymbolInfoDouble(Symb, SYMBOL_ASK), 100, 0, 0, "HEDGE") > 0)) ||
         ((Lots < 0) && (OrderSend(Symb, OP_SELL, -Lots, SymbolInfoDouble(Symb, SYMBOL_BID), 100, 0, 0, "HEDGE") > 0)) || !Lots);
}

bool CloseAll( string Symb = NULL )
{
  int Type = 0;
  long Ticket = 0;
  
  bool Res = PlaceHedge(CorrectSymbol(Symb));
  
  for (int i = OrdersTotal() - 1; !IsStopped() && Res && (i >= 0); i--)
    if (OrderSelect(i, SELECT_BY_POS) && (OrderType() <= OP_SELL) && (OrderSymbol() == Symb))
    {
      if (!Ticket)
      {
        Ticket = OrderTicket();
        Type = OrderType();
      }
      else if ((OrderType() != Type) && (Res = OrderCloseBy(Ticket, OrderTicket()) && PlaceHedge(Symb)))
      {
        Ticket = 0;       
        
        i = OrdersTotal();
      }
    }

  return(Res);
}

void OnStart()
{
  CloseAll();
}
 
guignath: If somebody could help and tell me why, that would be nice.
  1. When you post code please use the SRC button! Please edit your post.
              General rules and best pratices of the Forum. - General - MQL5 programming forum

  2.    if(MyTime >= MyStartTime && MyTime < MyLastTime)
          TimeToTrade = true;
          else
            {
             TimeToTrade = false;
            }
    Simplify your code. Increase Order after stoploss - MQL4 and MetaTrader 4 - MQL4 programming forum № 3

  3.    if(TimeToTrade==true && NotTheSameBar==true && total == 0 && mySlope == true && myRSIShort == true && myRSILong == true)
    
    
    You should be able to read your code out loud and have it make sense. You would never write if( (2+2 == 4) == true) would you? if(2+2 == 4) is sufficient. So don't write if(bool == true), just use if(bool) or if(!bool). Code becomes self documenting when you use meaningful variable names, like bool isLongEnabled where as Long_Entry sounds like a trigger price or a ticket number and "if long entry" is an incomplete sentence.

  4.    int total=PositionsTotal(); // number of open positions
       prev_total=total;
       if (total<prev_total)
    When can that condition ever be true?

  5. trade.Buy(1,NULL,Ask,Bid-82,Ask+28,NULL);
    Check your return codes for errors and report them.
              What are Function return values ? How do I use them ? - MQL4 and MetaTrader 4 - MQL4 programming forum
              Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles

 

Tx a lot Fxsaber !

On MT5, code is correctly compiled. But then it does not start on Strategy Tester... Any idea why ?

Tx again and in advance.

BR,

Reason: