New coder can anyone see anything obviously wrong with this code, its is opening and closing trades on every candle but does seem to be loading the indicators. Thanks.

 
//+------------------------------------------------------------------+
//|                                               CorkedBehindMZ.mq4 |
//|                        Copyright 2022, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict


//General EA inputs
int magicNB = 55555;
int openOrderID;

// Zerolag MACD parameters
input    int  fastEMA   =  12;
input    int  slowEMA   =  24;
input    int  signal    =  9;
const string   ZLAG  =  "ZeroLag MACD";

//EMA
input    int  MoneyZone   =  174;

//TMA Inputs
input int    HalfLength      = 56;
input ENUM_APPLIED_PRICE  Price   =   PRICE_CLOSE;        
extern double BandsDeviations = 2.5;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   Alert("");
   Alert("Starting EA Corked Behind MZ");
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
    Alert("Stopping EA Corked Behind MZ");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---

//Indicator Variables
double currMacdHisto;
double TMA_UB;
double TMA_LB;
double EMA_MZ;

//Getting Indicator values
currMacdHisto = iCustom(NULL,0,ZLAG,fastEMA,slowEMA,signal,0,0);
TMA_UB = iCustom(NULL,0,"TMA+CG",0,HalfLength,Price,BandsDeviations,1,0);
TMA_LB = iCustom(NULL,0,"TMA+CG",9,HalfLength,Price,BandsDeviations,2,0);
EMA_MZ =iMA(NULL, 0, MoneyZone, 0, 1, 0, 0);

 
   if (!IsNewBar())  return;  
   
   if(!CheckIfOpenOrdersByMagicNB(magicNB))//if no open orders try to enter new position
       {
         if (Ask < TMA_LB && currMacdHisto>0 && Ask<EMA_MZ) // Buying
            Print("Price is below TMA Lower Band and ZLAG is above zero - Sending buy order");
            //double stopLossPrice = StopLoss;
            //double takeProfitPrice = TakeProfit;
            //Print("Entry Price = " + Ask);
         
         
         openOrderID = OrderSend(NULL,OP_BUY,0.01,Ask,10,0,0,NULL,magicNB);
         if(openOrderID < 0) Alert("order rejected. Order error: " + GetLastError());
      }
   else if(Bid > TMA_UB && currMacdHisto<0 && Bid<EMA_MZ)//shorting
      {
         Print("Price is above TMA Upper Band and ZLAG is below zero - Sending sell order");;
           // double stopLossPrice = StopLoss;
           // double takeProfitPrice = TakeProfit;
           // Print("Entry Price = " + Bid);

      openOrderID = OrderSend(NULL,OP_SELL,0.01,Bid,10,0,0,NULL,magicNB);
      if(openOrderID < 0) Alert("order rejected. Order error: " + GetLastError());
      }
      
     else //else if you already have a position, update orders if need too.
   {
      if(OrderSelect(openOrderID,SELECT_BY_TICKET)==true)
      {
            int orderType = OrderType();// Short = 1, Long = 0

            
            if(orderType == 0)//long position
            {
               if (Bid > TMA_UB || currMacdHisto <0)
                     OrderClose(OrderTicket(),0.01,Bid,5,Red);
               
           
            else //if short
               {
               if (Ask < TMA_LB || currMacdHisto >0)
                     OrderClose(OrderTicket(),0.01,Ask,5,Green);
                }
            }
  
      }
    }

          
    

    }  
    
  
bool  IsNewBar()  {
      //open time for current bar
      datetime    currentBarTime =  iTime(Symbol(),   Period(),   0);
      //Intialise on first use
      static   datetime    prevBarTime =  currentBarTime;
      
      if (prevBarTime<currentBarTime){  //New bar opened
         prevBarTime =  currentBarTime; //Update Prev Time and exit
         return(true);
      }
      
      return(false);
 }
      
 bool CheckIfOpenOrdersByMagicNB(int magicNB)
{
   int openOrders = OrdersTotal();
   
   for(int i = 0; i < openOrders; i++)
   {
      if(OrderSelect(i,SELECT_BY_POS)==true)
      {
         if(OrderMagicNumber() == magicNB) 
         {
            return true;
         }  
      }
   }
   return false;
}    
   
        
 
Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2023.02.05
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
 
  1. Why did you post your MT4 question in the MT5 EA section instead of the MQL4 section, (bottom of the Root page)?
              General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
    Next time, post in the correct place. The moderators will likely move this thread there soon.

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

  3. Chad Michael:

    New coder can anyone see anything obviously wrong with this code, its is opening and closing trades on every candle but does seem to be loading the indicators. Thanks.

    A title should be short. Post your question in the post.

  4. openOrderID = OrderSend(NULL,OP_SELL,0.01,Bid,10,0,0,NULL,magicNB); 

    Be careful with NULL.

    1. On MT4, you can use NULL in place of _Symbol only in those calls that the documentation specially says you can. iHigh does, iCustom does, MarketInfo does not, OrderSend does not.
    2. Don't use NULL (except for pointers where you explicitly check for it.) Use _Symbol and _Period, that is minimalist as possible and more efficient.
    3. Zero is the same as PERIOD_CURRENT which means _Period. Don't hard code numbers.
    4. MT4: No need for a function call with iHigh(NULL,0,s) just use the predefined arrays, i.e. High[].
    5. Cloud Protector Bug? - MQL4 programming forum (2020)

  5.        if(OrderSelect(openOrderID,SELECT_BY_TICKET)==true)
          { 

    You select by ticket. You don't check if the ticket has already closed.

  6. 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 / Position select loop on the first tick, or persistent storage (GV+flush or files) of ticket numbers required.

    On a network disconnection you might get ERR_NO_RESULT or ERR_TRADE_TIMEOUT. There is nothing to be done, but log the error, return and wait for a reconnection and a new tick. Then reevaluate. Was an order opened or is the condition still valid.

Reason: