Help for only once ordersend per bar!

 

Could someone please help?

I want to ordersend only once per bar (no matter 5mins bar or 1hour bar) with max lots. It means only one order should be sent per bar and then another only one order should be sent per bar at least 10 bars later & the lower price than previous order opened with if condition satisfied.

But the orders have actually been sent within a minute until max lots. For example, 10 orders have been excuted within several seconds.

Could you please help sort out?

extern double Lots = 0.1;
extern double Maxlot = 10;
extern double dif = 500;

int cnt, ticket, total, duration;

   duration = TimeCurrent() - OrderOpenTime();
   total=OrdersTotal();
   if(total<=Maxlot) 
     {
       if(AccountFreeMargin()<(2000*Lots))
        {
         Print("We have no money. Free Margin = ", AccountFreeMargin());
         return(0);  
        }
      // check for long position (BUY) possibility
      if(Ma7Current>Ma11Current &&  Ma7Previous>Ma11Previous && Ma7Previous2<Ma11Previous2  && 
       Ma7Current>Ma7Previous)
        {
         { 
         if(total<1)
        
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,30,0,0,"ma",16384,0,Green);
       
         else
           { 
            if(OrderType()==OP_BUY && OrdersTotal()>=1 && OrdersTotal()<10 && (duration > 10 * 300) && 
                (Bid>OrderOpenPrice()-dif*Point))
      
         ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,30,0,0,"ma",16384,0,Green);
           }
         return(0);
         }
         if(ticket>0)
          {
            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
          }
         else Print("Error opening BUY order : ",GetLastError()); 
         return(0); 
        }
 
seungbaek:
I want to ordersend only once per bar
int start(){
   static datetime lastOrderSend;
   if (Time[0] == lastOrderSend) return(0); // Only send one per bar
   :
   int ticket = OrderSend(...);
   if (ticket < 0) Alert("OrderSend Failed: ", GetLastError());
   else            lastOrderSend = Time[0]; // Send no more this bar
 
danjp:

Send only once per bar (no matter 5mins bar or 1hour bar).

Only one order should be sent per bar at least 10 bars later & the lower price than previous order opened with if condition satisfied.

Until max lots has been reached or end of margin? Guessing this from your code?

Test this yourself, I did this quickly and it seems alright too me. If the above was not what you were looking :(


#include <stderror.mqh>
#include <stdlib.mqh>
extern double Lots = 0.1;
extern int  MaxLot = 10;
extern int NextTrade = 10; //<---- number of bars to wait
extern int dif = 500;

void init()
   {return;}
int deinit()
   {return(0);}
int start()
{
   CheckBuy();
   return(0);
}

void CheckBuy()
{
  int  ticket; 
  
   double Ma7Current    = iMA(NULL,0,7,0,MODE_SMA,PRICE_CLOSE,0);   //<--- wild guess for testing.
   double Ma7Previous   = iMA(NULL,0,7,0,MODE_SMA,PRICE_CLOSE,1);   //<--- wild guess for testing.
   double Ma7Previous2  = iMA(NULL,0,7,0,MODE_SMA,PRICE_CLOSE,2);   //<--- wild guess for testing.

   double Ma11Current   = iMA(NULL,0,11,0,MODE_SMA,PRICE_CLOSE,0);  //<--- wild guess for testing.
   double Ma11Previous  = iMA(NULL,0,11,0,MODE_SMA,PRICE_CLOSE,1);  //<--- wild guess for testing.
   double Ma11Previous2 = iMA(NULL,0,11,0,MODE_SMA,PRICE_CLOSE,2);  //<--- wild guess for testing.

  
    if(NewBar())                                                                //<---- new bar 
        if(!MaxOpenOrders())                                                    //<---- maxlot ok 
            if(!(AccountFreeMargin()<(2000*Lots)))                              //<---- margin ok        
                if((Ma7Current>Ma11Current) &&  (Ma7Previous>Ma11Previous) &&   //<---- trade setup ok
                   (Ma7Previous2<Ma11Previous2) && (Ma7Current>Ma7Previous))            
                    if((OrdersTotal()<1) && OkToTradeBar())                     //<---- first order ok to trade
                    {
                        ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,30,0,0,"#1",16384,0,Green);  //<---- execute trade
                        if(ticket>0)
                            if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
                                Print("BUY order opened : ",OrderOpenPrice());                 //<---- order ok
                         else
                             Print("Error opening BUY order : ",GetLastError());               //<---- order failed
                     }         
                      else if((OkToTradeBar()) && (Bid<OrderOpenPrice()-dif*Point))            //<---- open new orders after n bars have passed 
                      {                                                                        //<---- and the price is LESS THEN the prev order
                          ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,30,0,0,"#2",16384,0,Green); 
                          if(ticket > 0)                                  
                              if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) 
                                  Print("BUY order opened : ",OrderOpenPrice());               //<---- order ok
                          else                   
                              Print("Error opening BUY order : ",GetLastError());              //<---- order failed    
                    }                     
                    return(0);                                                    //<--- n bars have not passes yet
                return(0);                                                        //<----setup rules not met        
            Print("We have no money. Free Margin = ", AccountFreeMargin());       //<--- no margin left
            return(0);       
        Print("No More Orders Allowed, Maximum Lots = ",MaxLot);                  //<--- max lots opened
        return(0);  
    return(0);                                                                    //<---- not a newbar
}                                                                                 //<--- end function   
         
bool NewBar()
{
        static datetime OldTime = 0;

        if(OldTime < Time[0])
        {
                OldTime = Time[0];
                return(true);
        }
        else
        {
                return(false);
        }
}


bool OkToTradeBar(bool trade=True)
{
        static bool FirstTimeIn = true;
        static datetime NextTradeTime = 0;      
        
        if(FirstTimeIn)
        {
                NextTradeTime = Time[0]; //<--- first time in return true and set NextTimeTrade to True.
                FirstTimeIn = false;
                return(true);
        }       
   if(trade)
           if(Time[0]>=NextTradeTime) //<--- check to see if current time[0] is greater then our last trade time.
         return(true);
      else
         return(false);
   else
      {
        NextTradeTime = Time[0]+ 60*NextTrade*Period(); //<--- (extern NextTrade) = n bars to skip before more trade attemps
         return(false);                                 //<---- set new trade time foward after trade is made without errors should be put after ticket check
      }
   return(false); //<---- should never get here
}
             
bool MaxOpenOrders()                      
{
        if(OrdersTotal() >= MaxLot)                 //<------- Max open orders for ALL outstanding trades on this account (extern MaxLots)
                return(true);                            //<------- Hopefully prevent some type of catastrophe
        return(false);
}
 

wow, danjp, you must have had the same professor I did in your first programming course -

    if(NewBar())                                                                //<---- new bar 
        if(!MaxOpenOrders())                                                    //<---- maxlot ok 
            if(!(AccountFreeMargin()<(2000*Lots)))                              //<---- margin ok        
                if((Ma7Current>Ma11Current) &&  (Ma7Previous>Ma11Previous) &&   //<---- trade setup ok
                   (Ma7Previous2<Ma11Previous2) && (Ma7Current>Ma7Previous))            
                    if((OrdersTotal()<1) && OkToTradeBar())                     //<---- first order ok to trade

based on your style. It leads me to a question.

Does any one know which of these uses less CPU?

Assume NewBar has a CPU cost of 1 and MaxOpenOrders has a CPU cost of 2.

    if( NewBar() )                                                               
        if( !MaxOpenOrders() )                                                   

// or 

    if( NewBar() && !MaxOpenOrders() )                                    

// or 
         
    if( !MaxOpenOrders() && NewBar() )                                    
 
danjp: Test this yourself

Thanks Danjp and sorry for late thanks!!! I just tested your one and that was okay to process. However I want to put "Exit order" into this but it could not work properly.

The EA is the exactly same as your above one and only insert the exit order between those line.

return(0); //<--- n bars have not passes yet
return(0); //<----setup rules not met

exit entry //<-----exit entry

Print("We have no money. Free Margin = ", AccountFreeMargin()); //<--- no margin left
return(0);

When I tested this only buy order was generated but could not get any exit transaction.

Could you please help me?

                    return(0);                                                    //<--- n bars have not passes yet
                return(0);                                                        //<----setup rules not met        
     
   for(cnt=0;cnt<total;cnt++)                                                     // exit entry  
     {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderType()<=OP_SELL &&                                                 // check for opened position 
         OrderSymbol()==Symbol())                                                // check for symbol
        {
         if(OrderType()==OP_BUY)                                                 // long position is opened
           {
             if((Ma7Current<Ma11Current) &&  (Ma7Previous<Ma11Previous) &&   
                   (Ma7Previous2>Ma11Previous2) && (Ma7Current<Ma7Previous))  
                {
                 OrderClose(OrderTicket(),OrderLots(),Bid,30,Violet);           // close long position
                 return(0);                                                     // exit
                }
           }
         else                                                                   // go to short position
           {
             if((Ma7Current>Ma11Current) &&  (Ma7Previous>Ma11Previous) &&   
                   (Ma7Previous2<Ma11Previous2) && (Ma7Current>Ma7Previous))  
              {
               OrderClose(OrderTicket(),OrderLots(),Ask,30,Violet);             // close short position
               return(0);                                                       // exit
              }
           }
        }
     }

            Print("We have no money. Free Margin = ", AccountFreeMargin());       //<--- no margin left
            return(0);       
 
seungbaek:

Thanks Danjp and sorry for late thanks!!!

3 months late of thank you. No you are not, you should apologize.

BTW, did you createthis with EA Builder ? https://www.mql5.com/en/forum/139608/page2#636071

:D

 
serpentsnoir:

Does any one know which of these uses less CPU?

Assume NewBar has a CPU cost of 1 and MaxOpenOrders has a CPU cost of 2.

    if( NewBar() )                                                               
        if( !MaxOpenOrders() )                                                   

// or 

    if( NewBar() && !MaxOpenOrders() )                                    

// or 
         
    if( !MaxOpenOrders() && NewBar() )

The first version is computationally cheaper in MQL4 since the whole of a logic expression is calculated (in MQL4 but not C).

See this section ...

https://docs.mql4.com/basis/operations/bool

"logical expressions are calculated completely"

 
seungbaek:

Could you please help me?

You need to fix your loop: Loops and Closing or Deleting Orders
 
onewithzachy:

3 months late of thank you. No you are not, you should apologize.

BTW, did you createthis with EA Builder ? https://www.mql5.com/en/forum/139608/page2#636071

:D


Thanks for your comments and yes you are right. I should have apologized more sincerly as so late. Unfortunately I missed out to say thank at that time!!!

I don't get used to Meta yet and I will study your reference during this weekend.

 
RaptorUK:
You need to fix your loop: Loops and Closing or Deleting Orders


Hi RaptorUK,

Thanks for your answer and I will study over the weekend as I am having a little bit of difficulty when scanned your above reference.

 

seungbaek, if possible could you attach the whole EA, so we can figure it out an not just Danjp (Danjp probably maybe not here). kinda difficult to scroll up and down just to figure out the whole EA.

And can you elaborate/explain more on "Exit order", I'm not so sure what you want from that.

I'm not sure I can help you either. LOL.