I need some corrections to this breakout EA

 
Guys I tried coding a breakout EA and I have been having difficulty no errors but it's not working and it's giving me some OrderModify and OrderSelect warnings.  Basically I want this EA to trade the breakout of every candle depending on the timeframe its attached to. And apply appropriate money management parameters maybe probably for a buy signal it buys when a candle breaks out of the high a the previous candle and place it's stop loss at the low of that previous candle. And it takes profits when the candle closes of course it should have a fixed stop loss parameters too and take profits. Please anyone coder here who can modify this will greatly appreciate thanks guys.



#include <stderror.mqh>
#include <stdlib.mqh>

extern double accountb = 500;     // STARTING ACCOUNT BALANCE

extern int gapdistance = 200,
           opendistance = 200,  // HOW FAR IN PIPS THE OPEN PRICE TO YESTERDAY HIGH/LOW TO NOT ALLOW TRADING UNTILL THE RETRACE IS MADE?
           retrace = 300,     // HOW FAR IN PIPS SHOULD IT RETRACE FROM THE HIGH/LOW OF YESTERDAY TO ACTIVATE BUYING OR SELLING?
           profit_lock = 91,  //  THIS IS A PERCENTAGE OF WHEN TO LOCK IN PROFIT
           be_lock = 59,      // THIS IS A PERCENTAGE OF WHEN TO MOVE SL TO B/E OR SMALL PROFIT
           profit_amount = 500,  // THIS IS THE PROFIT AMOUNT YOU WANT LOCKED IN (PIPS) 
           be_amount = 150,      // THIS IS THE PROFIT AMOUNT YOU WANT TO LOCK IN AT B/E (PIPS)
           TP = 590,  // TAKE PROFIT
           SL = 500;  // STOP LOSS
           
int time_candle=0;
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int init()
{
  Comment("");
  return(ERR_NO_ERROR);
}
int deinit()
{
  Comment("");
  return(ERR_NO_ERROR);
}
int start()
  {
   //  ------  TAKE PROFIT AND STOP LOSS SET TO BROKER THAT USES 5 DECIMAL PLACES  ------  //
   double tp = TP*Point;
   double sl = SL*Point;
   
   double order_open;
   
   double lots=NormalizeDouble((((AccountFreeMargin()*AccountLeverage())/Ask)/1000000),1);
   // GLOBAL VARIABLE TO MAKE EA PLACE ONLY ONE TRADE PER DAY  //
   time_candle =GlobalVariableGet("time_candle");
   
   // GLOBAL VARIABLE TO MAKE EA OPEN A TRADE FOR TODAY IF YESTERDAY TRADE IS STILL OPEN  //
   order_open = GlobalVariableGet("buy_open");
   int buylocked = GlobalVariableGet("buylocked"),
   selllocked = GlobalVariableGet("selllocked");
   
   int cnt, ticket, total=OrdersTotal();

   // FIND HIGH AND LOW FOR THE PREVIOUS DAY //
   double high = iHigh(Symbol(),PERIOD_D1,1),
          low = iLow(Symbol(),PERIOD_D1,1);
          
   //  DONT TRADE IF A GAP UP/DOWN OCCURS  //
   double close = iClose(Symbol(),PERIOD_D1,1);
   double open = iOpen(Symbol(),PERIOD_D1,0);
   
   bool gapup = false, gapdown = false, allowbuy = true, allowsell = true;
   
   if(open >= close + (gapdistance * Point))
   {
     gapup = true; 
   }
   if(open <= close - (gapdistance * Point))
   {
     gapdown = true; 
   }
   
   //  TRY TO STOP TRADING IN EARLY HOURS OF DAY IF PRICE HAS OPENED NEAR THE HIGH OR LOW OF PREVIOUS DAY  //
   // IS A BUY ALLOWED? //
   if(open >= high - (opendistance * Point))
   {
     if(Bid <= open - (retrace * Point))
     {
       allowbuy = true;
     }
     else
     {
       allowbuy = false;
     }
   }
   
   // IS A SELL ALLOWED? //
   if(open <= low + (opendistance * Point))
   {
     if(Ask >= open + (retrace * Point))
     {
       allowsell = true;
     }
     else
     {
       allowsell = false;
     }
   }
   
   
          
      if(time_candle!=iTime(Symbol(),PERIOD_D1,0) )
      {
        if(total<1 || order_open <= 1) 
        {
          //  SELL ORDER IF PRICE GOES 1 PIP LOWER THAN YESTERDAY'S LOW  //
          if(Bid <= low -(10*Point) && gapdown == false && allowsell == true)
          {
            ticket=OrderSend(Symbol(),OP_SELL,lots,Bid,3,Ask+sl,Bid-tp,"day break",16384,0,Red);
            time_candle = iTime(Symbol(),PERIOD_D1,0);
            
            GlobalVariableSet("order_open", order_open + 1);
            GlobalVariableSet("time_candle", time_candle);
            GlobalVariableSet("selllocked",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(ERR_NO_ERROR); 
          }
          
          //  BUY ORDER IF PRICE GOES 1 PIP HIGHER THAN YESTERDAY'S HIGH  //
          if(Ask >= high +(10*Point) && gapup == false && allowbuy == true)

{
            ticket=OrderSend(Symbol(),OP_BUY,lots,Ask,3,Bid-sl,Ask+tp,"day break",16384,0,Green);
            time_candle = iTime(Symbol(),PERIOD_D1,0);
            
            GlobalVariableSet("order_open", order_open + 1);
            GlobalVariableSet("time_candle", time_candle);
            GlobalVariableSet("buylocked",0);
            if(ticket>0)
            {
              if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
            }
            else Print("Error opening SELL order : ",GetLastError()); 
            return(ERR_NO_ERROR); 
          }
        }
        return(ERR_NO_ERROR);
      }
      
      
      //  MODIFY ORDER IF PRICE GOES IN OUR FAVOUR BY SET PERCENTAGE THAN PLACE STOP LOSS TO B/E AND THEN TO PROFIT. (SIMILAIR TO A TRAIL STOP)  //
      for(cnt=0;cnt<total;cnt++)
      {
        OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
        if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
        {
         if(OrderType()==OP_BUY)
         {
           //  BUY TRADE  //
           //  IF PRICE GOES IN OUR FAVOUR BY 59% SET STOP LOSS TO B/E  //
           if(Bid-OrderOpenPrice() >= tp/100 * be_lock && buylocked <= 0)  
           {                 
             OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+0.00011,OrderTakeProfit(),0,Green);
             
             //  IF PRICE CARRIES ON IN OUR FAVOUR BY 91% LOCK IN PROFIT  //
             if(Bid-OrderOpenPrice() >= tp/100 * profit_lock)  
             {                 
               OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+0.0045,OrderTakeProfit(),0,Green);
               GlobalVariableSet("buylocked",1);
               return(ERR_NO_ERROR);
             }
             return(ERR_NO_ERROR);
           }
         }
         else
         {
           //  SELL TRADE  //
           //  IF PRICE GOES IN OUR FAVOUR BY 59% SET STOP LOSS TO B/E  //
           if(OrderOpenPrice()- Ask >= tp/100 * be_lock && selllocked <= 0)
           {
             OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-be_amount*Point,OrderTakeProfit(),0,Red);
             
             //  IF PRICE CARRIES ON IN OUR FAVOUR BY 91% LOCK IN PROFIT  //
             if(OrderOpenPrice()- Ask >= tp/100 * profit_lock)
             {
               OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-profit_amount*Point,OrderTakeProfit(),0,Red);
               GlobalVariableSet("selllocked",1);
               return(ERR_NO_ERROR);
             }
             return(ERR_NO_ERROR);
             }  
           }
        }
     }
     
   return(ERR_NO_ERROR);
  }
 

Forum on trading, automated trading systems and testing trading strategies

When you post code please use the CODE button (Alt-S)!

Use the CODE button



 
  1. Why did you post your MT4 question in the Root / MT5 General section instead of the MQL4 section, (bottom of the Root page?)
              General rules and best pratices of the Forum. - General - MQL5 programming forum
    Next time post in the correct place. The moderators will likely move this thread there soon.

  2.    double lots=NormalizeDouble((((AccountFreeMargin()*AccountLeverage())/Ask)/1000000),1);
    
    Never risk more than a small percentage of your account, certainly less than 2% per trade, 6% total to the account.

    Risk depends on your initial stop loss, lot size, and the value of the pair. It does not depend on margin and leverage. No SL means you have infinite risk.

    1. You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce the stop goes below the support.
    2. AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/pip but it takes account of the exchange rates of the pair vs. your account currency.)
    3. Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
                MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum 2017.10.10
                Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum 2018.02.11
                Lot value calculation off by a factor of 100 - MQL5 programming forum 2019.07.19
    4. You must normalize lots properly and check against min and max.
    5. You must also check FreeMargin to avoid stop out

    Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.

  3. Your code
         if(Bid <= open - (retrace * Point))
         {
           allowbuy = true;
         }
         else
         {
           allowbuy = false;
         }
    Simplified
    allowbuy = Bid <= open - (retrace * Point);
              Why this always returns false? - MQL4 programming forum

  4.             ticket=OrderSend(Symbol(),OP_BUY,lots,Ask,3,Bid-sl,Ask+tp,"day break",16384,0,Green);
                time_candle = iTime(Symbol(),PERIOD_D1,0);
                
                GlobalVariableSet("order_open", order_open + 1);
                GlobalVariableSet("time_candle", time_candle);
                GlobalVariableSet("buylocked",0);
                if(ticket>0)
                {
                  if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
                }
                else Print("Error opening SELL order : ",GetLastError()); 
    By the time you call GetLastError, you've already callled four other functions and have lost any real error. Check immediately!
  5. Why are you calling those other functions if the OrderSend fails?
  6. You buy at the Ask and sell at the Bid. So for buy orders you pay the spread on open. For sell orders you pay the spread on close.
    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid reaches it. Not the Ask. Your SL is shorter by the spread and your TP would be longer. Don't you want the same/specified amount for either direction?
    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask reaches it. To trigger at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25
    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

  7.              OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+0.00011,OrderTakeProfit(),0,Green);
    If you had checked your return codes for errors, and reported them including GLE/LE, your variable values and the market, we would know that at least you are calling your code.
  8. Code breaks on JPY pairs and metals. PIP, Point, or Tick are all different in general.
              What is a TICK? - MQL4 programming forum

    Unless you manually adjust your SL/TP for each separate symbol, using Point means code breaks on 4 digit brokers, exotics (e.g. USDZAR where spread is over 500 points,) and metals. Compute what a PIP is and use it, not points.
              How to manage JPY pairs with parameters? - MQL4 programming forum
              Slippage defined in index points - Currency Pairs - Expert Advisors and Automated Trading - MQL5 programming forum

  9. objemmanuel1997: Please anyone coder here who can modify this will greatly appreciate
    Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?

Reason: