trying to make a function but failing. prolly something small.

 

Hi all,

so I am new to MQL4 and not really great at programming overall. Anyway, I am trying to learn from a tutorial (this one: https://www.cashbackforex.com/school/mql4-programming/basic-expert-advisor-example-moving-average-cross/ ) and there seems to be some stuff there that doesn't work. I haven't completed all of it yet, as I am trying to figure stuff out bit by bit.

So what happens here, is that I am trying to make the function below work, but I keep getting this error: "'close' - function declarations are allowed on global, namespace or class scope only"

I have tried to remove "void" before "close" but then I get other errors like "type - unidentified identifier". Why is there a void there, I guess there should actually be "void" there, since the author put it there, but then, I don't know what is wrong...

Please help!

And thank you in advance!


***

MQL4 Expert Advisor Example
  • www.cashbackforex.com
Learn in this complete MQL4 Expert Advisor Example article how to code a fully functioning MA Expert Advisor to help you program your trading EA.
 
Dmitri Mikhalev:

Hi all,

so I am new to MQL4 and not really great at programming overall. Anyway, I am trying to learn from a tutorial (this one: https://www.cashbackforex.com/school/mql4-programming/basic-expert-advisor-example-moving-average-cross/ ) and there seems to be some stuff there that doesn't work. I haven't completed all of it yet, as I am trying to figure stuff out bit by bit.

So what happens here, is that I am trying to make the function below work, but I keep getting this error: "'close' - function declarations are allowed on global, namespace or class scope only"

I have tried to remove "void" before "close" but then I get other errors like "type - unidentified identifier". Why is there a void there, I guess there should actually be "void" there, since the author put it there, but then, I don't know what is wrong...

Please help!

And thank you in advance!


***

Try renaming the function to something other than "close", instead something like "closeOrders".  Modern MetaQuotes uses an array named "close" and might be confusing your function of "close" with that.

Also, make sure the function is entirely outside OnInit, OnDeinit, OnTick, and/or OnTimer functions.

 
Matthew Renner:

Try renaming the function to something other than "close", instead something like "closeOrders".  Modern MetaQuotes uses an array named "close" and might be confusing your function of "close" with that.

Also, make sure the function is entirely outside OnInit, OnDeinit, OnTick, and/or OnTimer functions.

Thank you!


The function wasn't actually outside OnInit, so I moved it outside and the errors are gone! :)

 

Hi guys i am trying to build a code that checks when my 8 ema crosses above the ema 60, and the close price of the crossed candle is lower than the closed the price of the candle 3 candle sticks ahead, to return "WON" and if the close price of the crossed candle is higher than the close price of the candle 3 candle sticks ahead it will return "LOSS". And then vise versa for if the 8 ema crosses the 60 ema below.

My code is the following:


***

 
jay698:


Please insert the code correctly: when editing a message, press the button      Codeand paste your code into the pop-up window.

 
Dmitri Mikhalev #:

Thank you!


The function wasn't actually outside OnInit, so I moved it outside and the errors are gone! :)

i am facing the same problem , can you tell me how i can outside my function : https://www.youtube.com/watch?v=w42y_a3qK8g , i use to watch this video , 

my code :

//+------------------------------------------------------------------+

//|                                                        test1.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

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

extern string  LOT_SETTING       = "MONEY MANAGMENT SETTINGS";//++++++++++++++++++

extern bool    mm                = true;  //AUTO LOT SIZE ON/OFF

extern double  risk              = 20;    //RISK LEVEL FOR AUTO LOT SIZA %

extern double  equityuse         = 80;    //USE OF EQUITY FOR TRADE IN %

extern string  LOT_SETTIN       = "LOTS SIZE SETTING"; //+++++++++++++++++++++++++

extern double  Lots              = 0.05;  //LOT SIZE MANUAL FOR FIRST TRADE

extern double  TakeProfit        = 100;   //TAKE PROFIT FOR TRADE IN PIPS

extern double  closevalue        = 10;    //CLOSE ALL WHEN PROFIT REACH 0=TP

extern int     MaxTradesPerChart = 15;    //MAXIMUM ALLOWED LOTS IN CHART

extern int     slipige           = 10;    //SLIPPIGE ALLOWED

extern string  TRAI              = "TIME SETTING"; //++++++++++++++++++++++++++++++

extern int     StartHour         = 0;     //TRADE STARTING TIME

extern int     StopHour          = 24;    //TRADE ENDING TIME

extern int     StTradeDay        = 0;     //TRADE STARTING TIME 0=Monday,5=Friday

extern int     EndingTradeDay    = 5;     //TRADE ENDING DAY    0=Monday,5=Friday

extern string  TRAIL             = "TRAIL SETTING"; //+++++++++++++++++++++++++++++

extern bool    trailling         = false; //TRALLING STOP ON/OFF TRAIL AUTO STOP

extern double  TraillingStop     = 20;    //TRAILLING START AFTER PIPS

extern double  TraillingStep     = 5;     //TRAILLING STEPS IN PIPS

extern string  DISPLAY_SE        = "MARTINGLE SETTINGS"; //++++++++++++++++++++++++

extern bool    martingle         = true;  //MARTINGLE ON/OFF TRAIL AUTO STOP

extern int     PipStarter        = 40;    //PIPS GAP BETWEEN LOTS

extern double  Booster           = 1.5;   //LOT INCRESSING RATIO

extern string  RSI_INDICATOR     = "RSI SETTING "; //++++++++++++++++++++++++++++++

extern int     rsiLow            = 40;    //START BUY WHEN RSI VALUE

extern int     rsiHigher         = 60;    //START SELL WHEN RSI VALUE

extern int     rsiPer            = 24;    //RSI PERIOD  

extern string  REAL_ACC_TRADING  = "MACD SETTING"; //++++++++++++++++++++++++++++++

extern int     fastema           = 12;    //FAST EMA VALUE

extern int     slowema           = 26;    //SLOW EMA VALUE

extern int     period            = 9;     //PERIOD

extern string  REAL_ACC_TRADIN   = "NEWS FILTER"; //+++++++++++++++++++++++++++++++


//==============================Global variable====================================

double      digit          =0.0;

double      pip_gap        =0.0;

int         Majic_no       =1000;

string      identif        ="Afaq Khan";

int         Real_account   =65089013;

long        CurAccount;    

double      Lot_size,macdvalue,rsivalue,vPoint;


//=================================================================================

int deinit()

   {

   string name_delete;

   for(int i=ObjectsTotal()-1; i>=0; i--)

      {

       name_delete=ObjectName(i);

       if(StringFind(name_delete,identif)!=-1)

         ObjectDelete(name_delete);

      }  //End removing market info labels from chart

   return(0);

   }

//==================================================================================

int init()

  {

   if(Point == 0.00001)

      {

      vPoint = 0.0001;

      }

      else

         {

          if(Point == 0.001)

            {

             vPoint = 0.01;

             }

          else

              vPoint = Point;   

   }

   

   if(Digits ==3)   

      {

       digit      = 10.0 * TakeProfit;

       pip_gap    = 10.0 * PipStarter;       

      }

   else

      {

      if(Digits == 5)

         {

          digit   =10.0* TakeProfit;

          pip_gap =10.0* PipStarter;

          }

       else

       {

        digit  = TakeProfit;

        pip_gap= PipStarter;

       }

      }

    CurAccount=AccountInfoInteger(ACCOUNT_LOGIN);

   return(0);

  }

//=======================================on every tick====================================

int start()

   {

    if(Bars<10)

      {

       Comment("Not enough bars");

       return(0);

       }

//=======================================checking for account type====================


    if(IsDemo());

      else

         if(CurAccount!=Real_account)

            {

             Comment ("FOR REAL ACCOUNT TRADE CONTACT WHATSAPP ONLY: 03149187588");

             return(0);

            }

     On_every_tick();

      return(0);

    } 

//=====================================================================================

int On_every_tick()

   {

    if (martingle==true)

      {

       trailling=false;

       ManageBuy();

       ManageSell();

       }

    if (martingle==false)

      {

       trailling=true;

       if(Count_Order() == 0 )

          {

          OpenBuy();

          OpenSell();

          }

      }

       

       closevalue= Lotsize()*500;

       if(CalculateProfit()>=closevalue)

         {

          CloseAllTrades();

         }

       

       ChartComment();

       

       

       return (0);

    }

//====================================================================================

double Lotsize1()

   {

      

      double Balance = AccountBalance();

      double PV = MarketInfo(Symbol(),MODE_TICKVALUE);

      double Risk = risk/100;

      double Equityuse = (AccountEquity()*Risk)/100;

      double Lot = (Balance*Risk)/(Equityuse*PV)/10;

      

      return(NormalizeDouble(Lot,2));

      } 

//***********************************************************************************

double Lotsize()

{

   int prec=2;

   double minlot,

          maxlot;

   minlot=MarketInfo(Symbol(),MODE_MINLOT); //get brokers minimal lot size

   maxlot=MarketInfo(Symbol(),MODE_MAXLOT); //get brokers maximal lot size

   if(minlot==0.01) prec=2;

   if (maxlot==0.1)  prec=1;

double lot;

double alot;

alot= NormalizeDouble(AccountBalance()/1000/10,prec);

if(mm == true)lot = alot; else lot = Lots;

if(lot> MarketInfo(Symbol(),MODE_MAXLOT))lot = MarketInfo(Symbol(),MODE_MAXLOT);

if(lot> MarketInfo(Symbol(),MODE_MINLOT))lot = MarketInfo(Symbol(),MODE_MINLOT);

return(NormalizeDouble(lot,2));

}

   

   

//********************************************************************************

void OpenBuy()

   {

    if(IsTradeTime()==1 && DayOfWeek() >= StTradeDay && DayOfWeek() <= EndingTradeDay && check_Buy())

    {

     //if (mm=true) (Lot_size=Lotsize(); ) else (Lot_size= Lots;)

     int A=OrderSend(Symbol(),OP_BUY,Lot_size,Ask,3,0,Ask+digit*Point,"Afaq",Majic_no,Green);

     {

     

     }

    } 

    return;

   }

//======================================================================================

void OpenSell()

   {

    if (IsTradeTime()==1 && DayOfWeek() >= StTradeDay && DayOfWeek()<= EndingTradeDay && check_Sell())

    

      {

       //if (mm=true) (Lot_size=Lotsize(); ) else (Lot_size= Lots;)

       int A=OrderSend(Symbol(),OP_SELL,Lot_size,Bid,3,0,Bid-digit*Point,"Afaq",Majic_no,0,Pink);

       {

      

       }

      } return;

   }

//========================================================================================

int IsTradeTime()

   {

    if ((StartHour < StopHour && TimeHour(TimeCurrent()) < StartHour)||TimeHour(TimeCurrent())>=StopHour)

      return(0);

    if (StartHour > StopHour && (TimeHour(TimeCurrent()) < StartHour && TimeHour(TimeCurrent())>=StopHour))

      return(0);

    if (StartHour == 0)

        StopHour = 24;

    if (Hour() == StopHour -1 && Minute() >=55)

      return(0);

    return(1);

   }

   

//===================================================================================

bool check_Sell()

   {

    bool Putorder=false;

      {

       rsivalue=iRSI (_Symbol,_Period,rsiPer,PRICE_CLOSE,0);

       macdvalue=iMACD(NULL,0,fastema,slowema,period,PRICE_CLOSE,MODE_MAIN,0);

       if ((rsivalue>=rsiHigher) && (macdvalue>0))

         Putorder=true;

      }

     return(Putorder);

   }

//====================================================================================

bool check_Buy()

    {

    bool Putorder=false;

      {

       rsivalue=iRSI (_Symbol,_Period,rsiPer,PRICE_CLOSE,0);

       macdvalue=iMACD(NULL,0,fastema,slowema,period,PRICE_CLOSE,MODE_MAIN,0);

       if ((rsivalue>=rsiLow) && (macdvalue>0))

         Putorder=true;

      }

     return(Putorder);

   }

//================================================================================

void ManageBuy()

   {

    double Lot_open_price  =0;

    double Lots_total      =0;

    double Lot_tp          =0;

    int cnt                =0;

    double lott            =0;

    for (cnt =0; cnt <OrdersTotal(); cnt++)

      {

       int a=OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

       if(OrderMagicNumber() != Majic_no || OrderType() != OP_BUY)

         continue;

       if(OrderOpenTime()>0)

         {

          Lot_open_price   = OrderOpenPrice();

          Lot_tp           = OrderTakeProfit();

         }

        if(OrderLots() > Lots_total)

            Lots_total = OrderLots();

      }

    double Get_lot = MathRound(MathLog(Lots_total / Lots) / MathLog(Booster)) + 1.0;

    if (Get_lot<0)

       Get_lot =0;

       //if (mm=true) (lott=Lotsize(); ) else (lott= Lots;)

    Lot_size=NormalizeDouble(Lots * MathPow(Booster,Get_lot),2);

    if ((Get_lot==0 && DayOfWeek() <5)|| Get_lot==0 && DayOfWeek() >=0 && DayOfWeek()<=5)

      OpenBuy();

    if(Lot_open_price - Ask > pip_gap * Point && Get_lot < MaxTradesPerChart)

      {

       OpenBuy();

       return;

      }

      for (cnt = 0; cnt < OrdersTotal(); cnt++)

         {

          int b=OrderSelect(cnt, SELECT_BY_POS,MODE_TRADES);

          if(OrderMagicNumber() != Majic_no || OrderType() != OP_BUY || OrderTakeProfit() == Lot_tp || Lot_tp == 0.0)

            continue;

          int c=OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),Lot_tp,0,Pink);           

         }

   }

//===============================================================================================

void ManageSell()

   {

    double Lot_open_price  =0;

    double Lots_total      =0;

    double Lot_tp          =0;

    int cnt                =0;

    double lott            =0;

    for (cnt =0; cnt <OrdersTotal(); cnt++)

      {

       int d=OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

       if(OrderMagicNumber() != Majic_no || OrderType() != OP_SELL)

         continue;

       if(OrderOpenTime()>0)

         {

          Lot_open_price   = OrderOpenPrice();

          Lot_tp           = OrderTakeProfit();

         }

       if(OrderLots() > Lots_total)

            Lots_total = OrderLots();

      }

    double Get_lot = MathRound(MathLog(Lots_total / Lots) / MathLog(Booster)) + 1.0;

    if (Get_lot<0)

       Get_lot =0;

       //if (mm=true) (lott=Lotsize(); ) else (lott= Lots;)

    Lot_size=NormalizeDouble(Lots * MathPow(Booster,Get_lot),2);

    if ((Get_lot==0 && DayOfWeek() <5)|| Get_lot==0 && DayOfWeek() >=0 && DayOfWeek()<=5)

      OpenSell();

    if(Bid - Lot_open_price > pip_gap * Point && Lot_open_price > 0.0 && Get_lot < MaxTradesPerChart)

      {

       OpenSell();

       return;

      }

      for (cnt = 0; cnt < OrdersTotal(); cnt++)

         {

          int e=OrderSelect(cnt, SELECT_BY_POS,MODE_TRADES);

          if(OrderMagicNumber() != Majic_no || OrderType() != OP_SELL || OrderTakeProfit() == Lot_tp || Lot_tp == 0.0)

            continue;

          int f=OrderModify(OrderTicket(),OrderOpenPrice(),OrderStopLoss(),Lot_tp,0,Pink);

            }        

         }

 //=======================================================================================

 void ChartComment()

   {

    string drawdown= DoubleToStr(Calculate_draw_down(2),2);

    Comment("\nMy Ea RESULT = 03149187588",

            "\n______________________________________________ =",

            "\nLot PROFIT =",CalculateProfit(),

            "\nSERVER TIME =",TimeToStr(TimeCurrent(), TIME_SECONDS),

            "\nACCOUNT EQUITY =",AccountEquity(),

            "\nACCOUNT BALANCE =",AccountBalance(),

            "\nFREE MARFR=IN =",AccountFreeMargin(),

            "\nDRAWDOWN =",drawdown,

            "\n_______________________________________________ ="

           )

}


//======================================================================================


double Calculate_draw_down (int a)

   {

    double Draw_down;

    if(a==2)

      {

       Draw_down= (AccountEquity()/AccountBalance() - 1.0) / (-0.01);

       if (Draw_down > 0.0)

         return(0);

      }

     if(a==1)

      {

       Draw_down = 100.0 * (AccountEquity() / AccountBalance() - 1.0);

       if (Draw_down > 0.0)

         return (Draw_down);

       return(0);

      }

     return(0.0);

   }

//===============================================================================================

double CalculateProfit()

   {

    double profit = 0;

    for(int cnt = OrdersTotal() - 1 ; cnt >= 0; cnt--)

      {

       int x= OrderSelect (cnt, SELECT_BY_POS,MODE_TRADES);

       if (OrderSymbol() != Symbol() || (OrderMagicNumber()) != Majic_no)

         continue;

       if(OrderSymbol() == Symbol() && (OrderMagicNumber())== Majic_no)

         if ((OrderType()==OP_BUY) || (OrderType()==OP_SELL))

            profit += OrderProfit();

      }

    return(profit);

   }

//=================================================================================

void CloseAllTrades()

   {

    int total=OrdersTotal();

    for(int y= OrdersTotal()-1; y>=0; y--)

      {

       if(OrderSelect(y, SELECT_BY_POS,MODE_TRADES))

         if((OrderSymbol()==Symbol()) && (OrderMagicNumber()== Majic_no))

            {

             int ticket=OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),5,Aqua);

            }

      }

     return;

   }

//========================================================================================

void Trail_sl()

   {

    if ((OrdersTotal()>0) && (TraillingStop !=0))

      {

       for (int cnt=OrdersTotal();cnt>=0;cnt--)

       {

       int myoder=OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);

       if(OrderSymbol()==Symbol())

         {

          if(OrderType()==OP_BUY)

            {

             

             if(Bid-OrderOpenPrice()>((TraillingStop+TraillingStep)*vPoint))

               {

                if ((OrderStopLoss()<(Bid - (TraillingStop+TraillingStep)*vPoint)) || OrderStopLoss()==0)

                  int ticket=OrderModify(OrderTicket(),OrderOpenPrice(),Bid-vPoint*TraillingStop,0,0,Green);

               }

            }

         }

        if(OrderType()==OP_SELL)

         {

          if ((OrderOpenPrice()-Ask)> ((TraillingStop+TraillingStep)*vPoint))

            {

             if ((OrderStopLoss()>(Ask + (TraillingStop+TraillingStep)*vPoint)) || OrderStopLoss()==0)

               int k=OrderModify(OrderTicket(),OrderOpenPrice(),Ask+vPoint*TraillingStop,0,0,Red);

            }

         }

       }

       return;

      }

   }

//***********************************************************************************************

double Count_Order()

   {

    int CurTrades=0;

    for (int i=OrdersTotal()-1; i >=0; i--)

      {

       if (OrderSelect(i, SELECT_BY_POS,MODE_TRADES))

         if(OrderSymbol() != Symbol() || OrderMagicNumber() != Majic_no)

         continue;

       if(OrderSymbol()== Symbol() && OrderMagicNumber() == Majic_no)

         if ((OrderType()==OP_BUY) || (OrderType()==OP_SELL))

            CurTrades++;

      }

     return(CurTrades);

 }


//******************************************************************************************************

MQL4 Expert Advisor Example
  • www.cashbackforex.com
Learn in this complete MQL4 Expert Advisor Example article how to code a fully functioning MA Expert Advisor to help you program your trading EA.
 
Dmitri Mikhalev #:

Thank you!


The function wasn't actually outside OnInit, so I moved it outside and the errors are gone! :)

the attach file have my code , i use to watch videos and then type all the code but i have an error this "  "'close' - function declarations are allowed on global, namespace or class scope only" "
Files:
test1.mq4  17 kb
 
  1. Just above your pasted code was:
    Vladimir Karputov #: Please insert the code correctly: when editing a message, press the button  Code     and paste your code into the pop-up window.

    Why didn't you use the code button?

    Please edit your (original) post and use the CODE button (or Alt+S)! Or delete it since you then attached the file.
              General rules and best pratices of the Forum. - General - MQL5 programming forum (2019)
              Messages Editor

  2. si46idrees #: i have an error this "  "'close' - function declarations are allowed on global, namespace or class scope only" "

    You have no "close" function in your posted code. The error message is "'CloseAllTrades' - function declarations are allowed on global, namespace or class scope only    test1.mq4    385    6"
         How To Ask Questions The Smart Way. (2004)
              Be precise and informative about your problem


  3. Start by fixing the first error first. "'}' - semicolon expected    test1.mq4    348    1"

                "\n_______________________________________________ ="
               )   
    }