SL and TP system - page 5

 
Keith Watford:

There is not even a single Print in your code!

They were not printing I took them out

 
Tiberious:

They were not printing I took them out

So instead of investigating why they are not printing, you took the Prints out of the code??!!

That makes no sense at all!

 

You wrote the code so you should know what it is supposed to do.

When it doesn't execute as you expect, check your code carefully.

As I said before...

Keith Watford:

Then, as a coder you should be asking yourself "Why doesn't it print the error??"

The obvious answer is because there was no error!

If there was no error, then it can only be because there was no attempt to close any trade (or because a trade was closed).

What are the possible reasons for  there being no attempt to close any trade?

Only possible answers.......

There was not a trade open with the symbol.

The OrderSelect() failed.

The function was not called.

Add prints in your code to find the correct answer.

Did you check all the above?

      if (GetTotalOpenTrades() < MaxTrades) {
      //
   }
      
      else if (GetTotalOpenTrades() < MaxTrades) {
      //No code within these braces will be executed!
 }

I have removed the actual code from the above and an error is obvious.

Now lets take a look at the first block...

      if (GetTotalOpenTrades() < MaxTrades) {      //What if Open trades does = MaxTrades?? None of the block will be executed
      
         if ( (TimeCurrent() - LastTradePlacedTimeStamp) < TradeDelayTimeSeconds ) return;
      
          if ((LastFastEMA < LastSlowEMA)
                   &&(FastEMA > SlowEMA)) {
                   
            LongSetup = True;                       //LongSetup = True,(FastEMA > SlowEMA), so a trade is placed
      }
      
      if (LongSetup == True){
            
            Comment ("Buy");
            int OrderResultLong = OrderSend(Symbol(), OP_BUY, LotsToTrade, Ask, 0, 0, 0, "Buy Order", Magic, 0, clrGreen);
      }
      
      if (LongSetup == True && FastEMA < SlowEMA) CloseAllTrades();  //If LongSetup = True,(FastEMA > SlowEMA), so CloseAllTrades() will not be executed
         
         LongSetup = False;                           //LongSetup = False so the next time the above if is called, CloseAllTrades() will not be executed
         LastTradePlacedTimeStamp = TimeCurrent();
   }
 
Keith Watford:

You wrote the code so you should know what it is supposed to do.

When it doesn't execute as you expect, check your code carefully.

As I said before...

Did you check all the above?

I have removed the actual code from the above and an error is obvious.

Now lets take a look at the first block...

Im not sure what you mean with this comment

if (LongSetup == True && FastEMA < SlowEMA) CloseAllTrades();  //If LongSetup = True,(FastEMA > SlowEMA), so CloseAllTrades() will not be executed
 
          if ((LastFastEMA < LastSlowEMA)
                   &&(FastEMA > SlowEMA)) {
                   
            LongSetup = True;                       //LongSetup = True,(FastEMA > SlowEMA), so a trade is placed

Look at the ema condition for LongSetup to be true

if (LongSetup == True && FastEMA < SlowEMA) CloseAllTrades(); 

So here, if  LongSetup  is true the ema condition cannot be true so this if will always be false.

 
Keith Watford:

Look at the ema condition for LongSetup to be true

So here, if  LongSetup  is true the ema condition cannot be true so this if will always be false.

I did that on purpose since I want the trade to close when the EMA crosses in a long position. So in this case since it is already true I can get rid of the true statement

 
This is my code so far. But trades still do not close when the opposite signal occurs. What do you think the problem is?
//+------------------------------------------------------------------+
//|                                                  EMA Cross 2.mq4 |
//|                                                        Tiberious |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Tiberious"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

datetime expiryDate = D'2021.03.20 00:00';

double LotsToTrade = 0.05;     //Lot Size
extern int Stoploss = 0; // StopLoss in Pips
 int Takeprofit = 0; // 
int Magic = 500;
int MaxTrades = 1;
int MaxCloseSpreadPips = 7;

//Trade Time Delay
int TradeDelayTimeSeconds = (1 * 1 * 1 * 0);   // 0 second/minute delay
datetime LastTradePlacedTimeStamp = 0;

bool LongSetup = False;
bool ShortSetup = False;
double PipValue=1;

int OnInit()
  {
  if(TimeCurrent() > expiryDate)
     {
      Alert("Expired copy EMA Cross 2. Please contact vendor.");
      ExpertRemove();
      return(INIT_FAILED);
     }
PipValue = 1;
    if (Digits == 3 || Digits == 5) PipValue = 10;
   return(INIT_SUCCEEDED);
  }

void OnDeinit(const int reason)
  {

   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
      double SlowEMA = iMA(NULL, 0, 50, 0, MODE_SMA, PRICE_CLOSE, 0);
      double LastSlowEMA = iMA(NULL, 0, 50, 0, MODE_SMA, PRICE_CLOSE, 1);
      
      double FastEMA = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_CLOSE, 0);
      double LastFastEMA = iMA(NULL, 0, 1, 0, MODE_SMA, PRICE_CLOSE, 1);
      double SL,TP;
      
      if (GetTotalOpenTrades() < MaxTrades) {
      
         if ( (TimeCurrent() - LastTradePlacedTimeStamp) < TradeDelayTimeSeconds ) return;
      
          if (FastEMA > SlowEMA) /*&& (LastFastEMA <= LastSlowEMA))*/ {
                   
            LongSetup = True;
      }
      
      if (LongSetup == True){
            
            Comment ("Buy");
            CloseAllTrades(OP_SELL);
             SL = Ask - Stoploss*PipValue*Point;
            if (Stoploss == 0) SL = 0;
             TP = Ask + Takeprofit*PipValue*Point;
            if (Takeprofit == 0) TP = 0;
            int OrderResultLong = OrderSend(Symbol(), OP_BUY, LotsToTrade, Ask, 10, SL, TP, "Buy Order", Magic, 0, clrGreen);
      }
      
      
         
         LongSetup = False;
         LastTradePlacedTimeStamp = TimeCurrent();
      
      
   }
 
      
      if (GetTotalOpenTrades() < MaxTrades) {
      
         if ( (TimeCurrent() - LastTradePlacedTimeStamp) < TradeDelayTimeSeconds ) return;
            
       if (FastEMA < SlowEMA) /*&& (LastFastEMA >= LastSlowEMA))*/ {
               
          ShortSetup = True;
       }
       
       if (ShortSetup == True) {
            
            Comment ("Sell");
            CloseAllTrades(OP_BUY);
            SL = Bid + Stoploss*PipValue*Point;
            if (Stoploss == 0) SL = 0;
             TP = Bid - Takeprofit*PipValue*Point;
            if (Takeprofit == 0) TP = 0;
            int OrderResultShort=-1;
            OrderResultShort = OrderSend(Symbol(), OP_SELL, LotsToTrade, Bid, 10, SL, TP, "Buy Order", Magic, 0, clrRed); 
            
      }
      
      
      
         ShortSetup = False;
         LastTradePlacedTimeStamp = TimeCurrent();
 }
 
}

// Return total number of open trades
int GetTotalOpenTrades() {
      
      int TotalTrades = 0;
      
      //Loop through open orders and add them to TotalTrades
      for (int t=OrdersTotal()-1; t>=0; t--) {
      
         if(OrderSelect(t, SELECT_BY_POS, MODE_TRADES)) {
            
            if(OrderSymbol() != Symbol()) continue;
            if(OrderMagicNumber() != Magic) continue;
            if(OrderCloseTime() !=0) continue;
            
            TotalTrades = (TotalTrades + 1);
      }
   }
      return TotalTrades;
 }



int Tickets[];

void CloseAllTrades(int type)
{
    int orderstotal = OrdersTotal();
    int orders = 0;
    int ordticket[90][2];
    for (int i = 0; i < orderstotal; i++)
    {
        OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
        if (OrderType() != type || OrderSymbol() != Symbol() || OrderMagicNumber() != Magic)
        {
            continue;
        }
        ordticket[orders][0] = OrderOpenTime();
        ordticket[orders][1] = OrderTicket();
        orders++;
    }
    if (orders > 1)
    {
        ArrayResize(ordticket,orders);
        ArraySort(ordticket);
    }
    for (int i = 0; i < orders; i++)
    {
        if (OrderSelect(ordticket[i][1], SELECT_BY_TICKET) == true)
        {
            bool ret = OrderClose(OrderTicket(), OrderLots(), OrderClosePrice(), 4, Red);
            if (ret == false)
            Print("OrderClose() error - ", GetLastError());
            else
            ArrayInitialize(Tickets,0);
            
        }
    }
    
}
 
Tiberious:
This is my code so far. But trades still do not close when the opposite signal occurs. What do you think the problem is?

In my post #43 I included

if (GetTotalOpenTrades() < MaxTrades) {      //What if Open trades does = MaxTrades?? None of the block will be executed

You have completely ignored it!!

Reason: