Please help!!!!!

 
Guys please help me with the above code. I am trying to write an EA that will set trades on the open of every candle. 
1. Problem is its not closing the open trades before it opens a new trade. 
2. The stoploss and take profit dont always get set.
Any help will be appreciated.
Thanx.


</>extern double     TakeProfit   = 200;
extern double     StopLoss     = 100;
extern double     Lots         = 0.03;
static int        ticket       = 0;
static datetime   lastbar;
int init()
{

lastbar=Time[1];

return (0);
}

int start ()
{
   {
      static bool IsFirstTick = true;

      if(IsFirstTick == true)
         {
         IsFirstTick = false;
         
         bool res;
         res = OrderSelect(ticket, SELECT_BY_TICKET);
         if(res == true)
         {
            if(OrderCloseTime() == 0)
            {
               bool res2;
               res2 = OrderClose(ticket, Lots, OrderClosePrice(), 10);
               
               if(res2 == false)
               {
                  Alert("Error Clossing Order #", ticket);
               }
            }
         }
         }
   }
   if (IsNewBar())
{
         //Sell Conditions
         
            if(Close[1] < Open[1])
         {
            ticket = OrderSend(Symbol(),OP_SELL, Lots, Bid, 0, 0, 0, "Set by Open Close System"); 
            if(ticket < 0)
            Alert("Error Sending Buy Order!");
         }
         else
         {
            Alert("Your ticket # is" + string(ticket));
                        Sleep(5000);
            
            Alert("Modifiying the Order...");
            
            bool res1;
            res1 = OrderModify(ticket, 0,Ask+StopLoss*Point,Ask-TakeProfit*Point,0);
            if(res1 == false) 
            {
               Alert("Error modifiying order!");
            }
            else
            {
               Alert("Order modifiying successfully");
            }
         }
  
                  //Buy Conditions
          
        if(Close[1] > Open[1])
         {
            ticket = OrderSend(Symbol(),OP_BUY, Lots, Ask, 0, 0, 0, "Set by Open Close System"); 
            if(ticket < 0)
            Alert("Error Sending Buy Order!");
         }
         else
         {
            Alert("Your ticket # is" + string(ticket));
                        Sleep(5000);
            
            Alert("Modifiying the Order...");
            
            bool res1;
            res1 = OrderModify(ticket, 0,Bid-StopLoss*Point,Bid+TakeProfit*Point,0);
            if(res1 == false) 
            {
               Alert("Error modifiying order!");
            }
            else
            {
               Alert("Order modifiying successfully");
            }
         }
        }

return (0);
}



bool IsNewBar() 
datetime curbar = Time[0]; // Open time of current bar

if (lastbar!=curbar) 
   { 
    lastbar=curbar; 
    return (true); 
   } 

  return(false); 

}</>

 
format code with the </> code button in the editor menu
 
lippmaje:
format code with the </> code button in the editor menu
Here is the file 
Files:
NewBar2.mq4  4 kb
 
Mzantsi:
Here is the file 

Use the code styler tool in your MetaEditor. Tools->Styler

It will indent your code to improve readability. You have some misarranged braces '{...}' so that order is modified/closed under wrong conditions.

Also you don't need to check 'if(res==true)' or 'if(res==false)' - just put 'if(res)' or 'if(!res)'.

 
I Take it you want the orders to close on the first tick of a new bar, correct ? 
 
Lorentzos Roussos:
I Take it you want the orders to close on the first tick of a new bar, correct ? 
Yes

 
  1. Please edit your (original) post and use the CODE button (Alt-S)! (For large amounts of code, attach it.)
              General rules and best pratices of the Forum. - General - MQL5 programming forum
              Messages Editor

  2. 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.

  3. static int        ticket       = 0;
    int start (){
       {
          static bool IsFirstTick = true;
    
          if(IsFirstTick == true)
             {
             IsFirstTick = false;
             
             bool res;
             res = OrderSelect(ticket, SELECT_BY_TICKET);
    On the first tick, ticket is zero. When will this OrderSelect ever be true? EAs must be coded to recover. If the power fails, OS crashes, terminal or chart is accidentally closed, on the next tick, any static/global ticket variables will have been lost. You will have an open order but don't know it, so the EA will never try to close it, trail SL, etc. How are you going to recover? Use a OrderSelect loop to recover, or persistent storage (GV+flush or files) of ticket numbers required.

  4. ticket = OrderSend(Symbol(),OP_BUY, Lots, Ask, 0, 0, 0, "Set by Open Close System"); 
    ⋮
    res1 = OrderModify(ticket, 0,Bid-StopLoss*Point,Bid+TakeProfit*Point,0);
    There is no need to open an order and then set the stops. Simplify your code - do it in one step. TP/SL on OrderSend has been fine for years.
              Build 500 № 9 2013.05.09
              Need help me mql4 guru add take profit to this EA - Take Profit - MQL4 programming forum 2017.09.27

  5. int init(){
       lastbar=Time[1];
    Global and static variables work exactly the same way in MT4/MT5/C/C++.
    1. They are initialized once on program load.
    2. They don't update unless you assign to them.
    3. In C/C++ you can only initialize them with constants, and they default to zero.
    4. In MTx you should only initialize them with constants. There is no default in MT5 (or MT4 with strict which you should always use.)

      MT4/MT5 actually compiles with non-constants, but the order that they are initialized is unspecified and don't try to use any price or server related functions in OnInit (or on load,) as there may be no connection/chart yet:

      1. Terminal starts.
      2. Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
      3. OnInit is called.
      4. For indicators OnCalculate is called with any existing history.
      5. Human may have to enter password, connection to server begins.
      6. New history is received, OnCalculate called again.
      7. New tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
    5. Unlike indicators, EAs are not reloaded on chart change so you must reinitialize them, if necessary.
                external static variable - Inflation - MQL4 programming forum

 

There's several issues with your code. Also it's unclear what you want to achieve and this would mean not only fix the obvious errors but also make a guess on your strategy.

I suggest to get someone fix it according to your needs. https://www.mql5.com/en/job

If you place a topic like "help!!!!!!!!!" and then turn away from it for three months, how serious is this going to be the next time?
Trading applications for MetaTrader 5 to order
Trading applications for MetaTrader 5 to order
  • www.mql5.com
Dear Developer, I Need Non–Repainting Indicator with Push Notification as am attaching the picture. As this job is already done by the developer please check the link am posting. Please communicate the DEVELOPER who has done this job Sorry i dont know the name. I Need Exact same Indicator and i don't have the source file. Please Note: please...