Checking Candle Open - page 3

 
  1. The code was written pre-build 600. Can't use dots in variable names since Feb 2014. Just replace with underscores.
  2. Here's an example of direction independent code
    double DIR, OOP, OCP, ISL;  int OP;
    
    if(     Bid > High[1]){
       DIR = +1; OOP = Ask; OCP = Bid; OP = OP_BUY;
    }
    else if(Bid <  Low[1]){
       DIR = -1; OOP = Bid; OCP = Ask; OP = OP_BUY;
    }
    else return;
    
    ISL = OCP -DIR* pips_to_change( extISL_Pips );
    ... OrderSend(...);
    You just switch Ask/Bid for open/close prices and write everything else as if it was a buy: ISL is below OCP (OCP - ISL) and the -DIR* changes the sign for a sell.
    If you need a compare (A > B) use (A - B) *DIR> 0 to reverse the comparison for a sell.
 
GumRai:

Seems like you have the idea.

Modify and post your code and I or someone else will comment on it 

Hey GumRai,

 It's been a while since I posted an update here, but I have been working away at the code and finally finished it--painful when working 10 hr days. I have two main issues however. 1) No matter what I do, it generates an error code: "Unknown ticket XYZ for OrderCloseFunction" and 2) I did a save-as of the file, (Called one USDCAD, another EURUSD), with different magicnumbers etc, yet it still takes only a trade at a time--and doesn't treat the pairs independently. In fact, it then creates an "invalid ticket for OrderCloseFunction" error as well. 

I tried googling this but to no avail. Would really appreciate if you could guide me in the right direction with this. What am I doing wrong?

#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

//part with the extern int stating the terms of the MA removed to reduce space.

int MagicNumber = 1234;
int MagicNumber2 = 2345;
double Pips;
int BuyTicket;
int SellTicket;
int CloseTicket;
int CloseSellTicket;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   double Ticksize = MarketInfo(Symbol(), MODE_TICKSIZE);
   if (Ticksize == 0.00001 || Ticksize == 0.001)
   Pips = Ticksize*10;
   else Pips = Ticksize;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
int start()
  {
//---

   static datetime bar_time=0;
  if(bar_time!=Time[0])
     {
      bar_time=Time[0];
      double PreviousSlow=iMA(NULL,0,SlowMa,SlowMaShift,SlowMaMethod,SlowMaAppliedTo,1);
      double PreviousSlow2=iMA(NULL,0,SlowMa,SlowMaShift,SlowMaMethod,SlowMaAppliedTo,2);
      double PreviousPriceClose=iClose(NULL,0,1);
      double PreviousPriceClose2=iClose(NULL,0,2);
      if((iOpen(NULL,0,1)<PreviousSlow && PreviousPriceClose>=PreviousSlow && Bid>=(PreviousSlow+PipsBeforeEntry*Pips)))
        {
         if(OrdersTotal()==0)
            BuyTicket=OrderSend(Symbol(),OP_BUY,LotSize,Ask,Slippage,Ask-(StopLoss*Pips),Ask+(TakeProfit*Pips),"Main Entry EA",MagicNumber,0,clrLimeGreen);
        }
        
      else
      for(int i = OrdersTotal()-1; i >= 0; i--) 
         {
         if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(iClose(NULL, 0,0)<PreviousSlow)
        {
          CloseTicket=OrderClose(BuyTicket,LotSize,Bid,Slippage,clrPink);
         }
         }
      if((iOpen(NULL,0,1)>PreviousSlow && PreviousPriceClose<PreviousSlow && Bid<=(PreviousSlow-PipsBeforeEntry*Pips)))
        {
         if(OrdersTotal()==0)
            SellTicket=OrderSend(Symbol(),OP_SELL,LotSize,Bid,Slippage,Bid+(StopLoss*Pips),Bid-(TakeProfit*Pips),"Main Entry EA",MagicNumber2,0,clrLimeGreen);
        }
      else
      for(i = OrdersTotal()-1; i >= 0; i--) 
         {
         if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
          if(iClose(NULL, 0,1)>PreviousSlow)
        {
          CloseSellTicket=OrderClose(SellTicket,LotSize,Ask,Slippage,clrPink);
              }
     }
     }
    return(0);
    return(0); 
    }
//--------------

  

 Many thanks in advance!

 

Never use OrdersTotal()==0 as a condition to enter trades

It means that if a trade has been open manually or by another EA or the same EA attached to another chart symbol, only 1 trade can be opened.

You have Global variable BuyTicket, initialise it to -1

int BuyTicket=-1;

 

      if((iOpen(NULL,0,1)<PreviousSlow && PreviousPriceClose>=PreviousSlow && Bid>=(PreviousSlow+PipsBeforeEntry*Pips)))
        {
         if(BuyTicket==-1)
            BuyTicket=OrderSend(Symbol(),OP_BUY,LotSize,Ask,Slippage,Ask-(StopLoss*Pips),Ask+(TakeProfit*Pips),
                                "Main Entry EA",MagicNumber,0,clrLimeGreen);
        }

 Don't loop through orders before closing, it is unnecessary

else
if(OrderSelect(BuyTicket,SELECT_BY_TICKET))
  {
   if(OrderCloseTime()==0)
     {
      if(Close[0]<PreviousSlow)
        {
         bool CloseTicket=OrderClose(BuyTicket,LotSize,Bid,Slippage,clrPink);
         if(CloseTicket)
            BuyTicket=-1;
        }
     }
   else
      BuyTicket=-1;  //Order has closed so reset variable
  }

 Now, when using globally declared variables for ticket numbers there can be problems if the terminal is shut down and restarted for some reason

So declare a new global scope variable

 bool Recovery=true;

 

  
  if(Recovery)
     {
     //loop through open orders and check for magic number, symbol and type
     //if you find a buy order with the magic number and symbol
     BuyTicket=OrderTicket();
     //if you find a sell order with the magic number and symbol
     SellTicket=OrderTicket();
     Recovery=false;
     }

 I've typed this quickly, so I may have made errors, but is enough to give you the idea

 
GumRai:


Thanks a ton for this!  The reason I'd put the loop in there was because what I noticed was that when it closed the sell, it would not trigger the buy for some reason. 

I've gone ahead and made the necessary changes...but something still seems amiss. It's not taking any long trades now, and generates error code of invalid ticket, and OrderClose error 4051. Any suggestions on what is still wrong here?

 The strange part is, that both in the previous code, and the current one (for the sell only), it took the trades reasonably okay (if I only implemented it on one chart).

 I didn't think this would've been so hard haha! I suppose I was mistaken when I thought it was a very simple and straightforward thing...buy when candle crosses and opens above MA, close and sell when candle crosses and goes below MA.


 

if((iOpen(NULL,0,1)<PreviousSlow && PreviousPriceClose>=PreviousSlow && Bid>=(PreviousSlow+PipsBeforeEntry*Pips)))
        {
         if(BuyTicket==-1)
            BuyTicket=OrderSend(Symbol(),OP_BUY,LotSize,Ask,Slippage,Ask-(StopLoss*Pips),Ask+(TakeProfit*Pips),"Main Entry EA",MagicNumber,0,clrLimeGreen);
        }
        
      else
      if(OrderSelect(SELECT_BY_POS,MODE_TRADES))
      {
      if(OrderCloseTime()==0)
      {
       if(Close[0]<PreviousSlow)
        {
          bool CloseTicket=OrderClose(BuyTicket,LotSize,Bid,Slippage,clrPink);
          if(CloseTicket)
            BuyTicket=-1;
            }
         }
         else
            BuyTicket= -1;
            }
            
      if((iOpen(NULL,0,1)>PreviousSlow && PreviousPriceClose<PreviousSlow && Bid<=(PreviousSlow-PipsBeforeEntry*Pips)))
        {
         if(SellTicket==-1)
            SellTicket=OrderSend(Symbol(),OP_SELL,LotSize,Bid,Slippage,Bid+(StopLoss*Pips),Bid-(TakeProfit*Pips),"Main Entry EA",MagicNumber2,0,clrLimeGreen);
        }
      else
       if(OrderSelect(SELECT_BY_POS,MODE_TRADES))
       {
         if(Close[0]>PreviousSlow)
        {
        bool  CloseSellTicket=OrderClose(SellTicket,LotSize,Ask,Slippage,clrPink);
              if(CloseSellTicket)
                  SellTicket=-1;
                     }
         }
         else
            SellTicket= -1;
            }
            
    return(0);
    return(0); 
    }
 

I'm sorry, but I really don't know what you are trying to do

if(OrderSelect(SELECT_BY_POS,MODE_TRADES))

 Doesn't select any order. Does the code even compile?

      if(OrderCloseTime()==0)
      {
       if(Close[0]<PreviousSlow)
        {
          bool CloseTicket=OrderClose(BuyTicket,LotSize,Bid,Slippage,clrPink);
          if(CloseTicket)
            BuyTicket=-1;
            }
         }
         else
            BuyTicket= -1;

 Here the else applies if( OrderCloseTime()==0) is false

       if(OrderSelect(SELECT_BY_POS,MODE_TRADES))
       {
         if(Close[0]>PreviousSlow)
        {
        bool  CloseSellTicket=OrderClose(SellTicket,LotSize,Ask,Slippage,clrPink);
              if(CloseSellTicket)
                  SellTicket=-1;
                     }
         }
         else
            SellTicket= -1;

 Here it applies if the OrderSelect fails, which it certainly does

 
GumRai:

I'm sorry, but I really don't know what you are trying to do

 Doesn't select any order. Does the code even compile?

 Here the else applies if( OrderCloseTime()==0) is false

 Here it applies if the OrderSelect fails, which it certainly does

 

 

Sorry, totally my fault. I didn't read/apply your suggestions correctly; thanks a lot for pointing them out. I've done so correctly here. No errors generated at all in the report. The only thing is that now, it's entering multiple sell and buy orders at times, which prevents it from closing trades at the right times.

 

Edit: To be precise, it is only exiting at the SL and TP, not when the price crosses the other side of the MA. Does this have something to do with the bool? 

int start()
  {
   static datetime bar_time=0;
  if(bar_time!=Time[0])
     {
      bar_time=Time[0];
      double PreviousSlow=iMA(NULL,0,SlowMa,SlowMaShift,SlowMaMethod,SlowMaAppliedTo,1);
      double PreviousSlow2=iMA(NULL,0,SlowMa,SlowMaShift,SlowMaMethod,SlowMaAppliedTo,2);
      double PreviousPriceClose=iClose(NULL,0,1);   //You can just use Close[1]
      if((iOpen(NULL,0,1)<PreviousSlow && PreviousPriceClose>=PreviousSlow && Bid>=(PreviousSlow+PipsBeforeEntry*Pips)))
        {
         if(BuyTicket==-1)
            BuyTicket=OrderSend(Symbol(),OP_BUY,LotSize,Ask,Slippage,Ask-(StopLoss*Pips),Ask+(TakeProfit*Pips),"Main Entry EA",MagicNumber,0,clrLimeGreen);
        }
      else
      if(OrderSelect(BuyTicket,MODE_TRADES))
      {
         if(OrderCloseTime()==0)
         {
          if(Close[0]<PreviousSlow)
           {
             bool CloseTicket=OrderClose(BuyTicket,LotSize,Bid,Slippage,clrPink);
             if(CloseTicket)
               BuyTicket=-1;
               }
            }
            else
               BuyTicket= -1; //Order has closed so reset variable
               }
            
      if((iOpen(NULL,0,1)>PreviousSlow && PreviousPriceClose<PreviousSlow && Bid<=(PreviousSlow-PipsBeforeEntry*Pips)))
        {
         if(SellTicket==-1)
            SellTicket=OrderSend(Symbol(),OP_SELL,LotSize,Bid,Slippage,Bid+(StopLoss*Pips),Bid-(TakeProfit*Pips),"Main Entry EA",MagicNumber2,0,clrLimeGreen);
        }
      else
       if(OrderSelect(SellTicket,MODE_TRADES))
       {
         if(Close[0]>PreviousSlow)
        {
        bool CloseSellTicket=OrderClose(SellTicket,LotSize,Ask,Slippage,clrPink);
              if(CloseSellTicket)
                  SellTicket=-1;
                     }
         }
         else 
            SellTicket= -1; //Order has closed so reset variable
            }
    return(0);
    return(0); 
    }
 
if(OrderSelect(BuyTicket,MODE_TRADES))
This does not select a trade, please follow the example that I gave you and do it correctly
 
GumRai:
This does not select a trade, please follow the example that I gave you and do it correctly

I feel...really stupid. lol. Thanks for finding that!!

1) Two things left...it now creates an error code of OrderClose 4108. Shall I post the code again? It's the same as above with the correction you'd stated. It enters and exits as per rules though.

2) And it doesn't  enter short immediately as soon as it closes the long position as shown in the pic. The green down arrow shows where it should've gone short. It took a buy, and closed that at a loss once it closed below the yellow MA. Here, it should've gone short. How can I loop this?

 Thanks a lot GumRai. I honestly wouldn't have reached anywhere this close without your help. 

should have gone short here 

 
int start()
  {
   static datetime bar_time=0;
   if(bar_time!=Time[0])
     {
      bar_time=Time[0];
      double PreviousSlow=iMA(NULL,0,SlowMa,SlowMaShift,SlowMaMethod,SlowMaAppliedTo,1);
      double PreviousSlow2=iMA(NULL,0,SlowMa,SlowMaShift,SlowMaMethod,SlowMaAppliedTo,2);
      double PreviousPriceClose=iClose(NULL,0,1);   //You can just use Close[1]
      if(BuyTicket==-1)
        {
         if((iOpen(NULL,0,1)<PreviousSlow && PreviousPriceClose>=PreviousSlow && Bid>=(PreviousSlow+PipsBeforeEntry*Pips)))
           {
            BuyTicket=OrderSend(Symbol(),OP_BUY,LotSize,Ask,Slippage,Ask-(StopLoss*Pips),Ask+(TakeProfit*Pips),"Main Entry EA",MagicNumber,0,clrLimeGreen);
           }
        }
      else
      if(OrderSelect(BuyTicket,SELECT_BY_TICKET))
        {
         if(OrderCloseTime()==0)
           {
            if(Close[0]<PreviousSlow)
              {
               bool CloseTicket=OrderClose(BuyTicket,LotSize,Bid,Slippage,clrPink);
               if(CloseTicket)
                  BuyTicket=-1;
              }
           }
         else
            BuyTicket=-1; //Order has closed so reset variable
        }

      if(SellTicket==-1)
        {
         if((iOpen(NULL,0,1)>PreviousSlow && PreviousPriceClose<PreviousSlow && Bid<=(PreviousSlow-PipsBeforeEntry*Pips)))
           {
            SellTicket=OrderSend(Symbol(),OP_SELL,LotSize,Bid,Slippage,Bid+(StopLoss*Pips),Bid-(TakeProfit*Pips),"Main Entry EA",MagicNumber2,0,clrLimeGreen);
           }
        }
      else
      if(OrderSelect(SellTicket,SELECT_BY_TICKET))
        {
         if(OrderCloseTime()==0)
           {
            if(Close[0]>PreviousSlow)
              {
               bool CloseSellTicket=OrderClose(SellTicket,LotSize,Ask,Slippage,clrPink);
               if(CloseSellTicket)
                  SellTicket=-1;
              }
           }
         else
            SellTicket=-1; //Order has closed so reset variable
        }
     }
   return(0);
  }

Small change as it was checking to close an order when there wasn't one.

According to the code there is no reason for a sell to be opened immediately a buy closes.

The condition to exit a buy is not the same as the conditions to open a sell .

Remember that as you are only checking on the candle open, Close[0] will be the bid value of the first tick received for the candle.

 
GumRai:

Small change as it was checking to close an order when there wasn't one.

According to the code there is no reason for a sell to be opened immediately a buy closes.

The condition to exit a buy is not the same as the conditions to open a sell .

Remember that as you are only checking on the candle open, Close[0] will be the bid value of the first tick received for the candle.

 

Holy! You did it! Thanks again and again GumRai. You're the best.

Can't forward test now, but once markets open, I think I should be able to use this then, with the other pairs as long as I have different magic#s on the demo. 

Reason: