Download MetaTrader 5

Help needed with ordersend error and macd indicator not

To add comments, please log in or register
tonyming
18
tonyming  

Hi Guys,


Can someone help me to go through my macd ea and advice me on how to perfect the following?

1. The macd indicator is not indicating when the line crossed

2. The ordersend failed with error #3


Thanks and appreciate your help.

//+------------------------------------------------------------------+
//|                                                      |
//|                                                   Copyright 2017 |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017"

//--- input parameters
extern double lotsize      = 0.1;
extern int slippage        = 3;
extern int maxorders       = 1;
extern int lastbar         = 1;
extern int entry_per_day   = 3;
extern double stoploss     = 5;
extern double takeprofit   = 5;

//time event
extern int starthour    = 10;
extern int startminute  = 33;
extern int endhour      = 17;
extern int endminute    = 50;

//indicator
extern int FAST_EMA_PERIOD= 12;
extern int SLOW_EMA_PERIOD= 26;
extern int MACD_SIGNAL_PERIOD= 9;
extern int macdbarinterval = 10;
extern int tpbarinterval = 20;

#include <tradinghours.mqh>

//mgc 10 bar
//tp 20 bar

int start()
   {
   
   GlobalVariablesDeleteAll();          // Deleting of all GVs
      
   double ema = iMA(NULL,0,60,0,MODE_EMA,PRICE_MEDIAN,lastbar);
   double close=iClose(NULL,0,lastbar);
   double past20macd=iMACD(Symbol(), 0, FAST_EMA_PERIOD, SLOW_EMA_PERIOD, MACD_SIGNAL_PERIOD, PRICE_TYPICAL, MODE_MAIN, macdbarinterval+1);
   
   int macdsignal                   =  0;                          //signal,buy=1,sell=2,nothing=0
   int emasignal                    =  0;
   int entrytoday                   =  0;
   
   bool enableopen                  =  true;                      //for entry per day
   bool enableopentime              =  true;
   
//---------------------------------------------------------------------------------------------------------------------
//MACD signal
   double macd[2];   
   double signal[2];
   double macdzone;
   int i;
   
   for(i=0;i<2;i++)
   {
   macd[i]= iMACD(Symbol(), 0, FAST_EMA_PERIOD, SLOW_EMA_PERIOD, MACD_SIGNAL_PERIOD, PRICE_TYPICAL, MODE_MAIN, i+1);
   signal[i]= iMACD(Symbol(), 0, FAST_EMA_PERIOD, SLOW_EMA_PERIOD, MACD_SIGNAL_PERIOD, PRICE_TYPICAL, MODE_SIGNAL, i+1);
   }
   
      {
      if(macd[0]>signal[0] && macd[1]<=signal[1])
         {
         macdsignal=1;
         }
      if(macd[0]<signal[0] && macd[1]>=signal[1])
         {
         macdsignal=2;
         }   
      else macdsignal=0;
      }
      
//---------------------------------------------------------------------------------------------------------------------
//save macd signal and to cancel the macd signal after 20 bar
int handle1,handle2,handle3,handle4,write;                               // File descriptor
string File_Name="macdzone.csv";                          // File name
string File_Name2="macd.csv";
string Erray[2,1];                                       // Array 
string read;
Erray[0,0]=macdsignal;
Erray[1,0]=macd[1];
//static datetime lastbartime;   
       {
       if(macdsignal != 0)                                             //writing macdsignal 1,2,0, macdzone
         {
         handle1=FileOpen(File_Name,FILE_CSV|FILE_WRITE,";");     //File opening
         FileWrite(handle1,Erray[0,0]);                           //Writing to the file
            if(write < 0)                                         // If failed
               {
               FileClose(handle1);                                // File closing
               return(macdsignal);                                            // Exit start()      
               }
         FileClose(handle1);
         }
       }
       {
       if(macdsignal != 0)                                             //writing macd value for reset in 20 bar
         {
         handle3=FileOpen(File_Name2,FILE_CSV|FILE_WRITE,";");     //File opening
         FileWrite(handle3,Erray[1,0]);                           //Writing to the file
            if(write < 0)                                         // If failed
               {
               FileClose(handle3);                                // File closing
               return(macdsignal);                                            // Exit start()      
               }
         FileClose(handle3);
         }
       }
//------------------------------------------------------------------------
//To read macdzone
      {
      handle2=FileOpen(File_Name,FILE_CSV|FILE_READ,";");         //File opening
      read=FileReadString(handle2);
      macdzone=StrToDouble(read);
      FileClose(handle2);
      }
//To read lastmacd      
      {
      handle4=FileOpen(File_Name2,FILE_CSV|FILE_READ,";");         //File opening
      read=FileReadString(handle4);
      double lastmacd=StrToDouble(read);
      FileClose(handle4);
      }
//---------------------------------------------------------------------------------------------------------------------
//recalculate the macd if more than 20 bars
      if (past20macd==lastmacd)
         {
         macdzone=0;
         handle3=FileOpen(File_Name,FILE_CSV|FILE_WRITE,";");     //File opening
         FileWrite(handle1,Erray[0,0]);                           //Writing to the file
            if(write < 0)                                         // If failed
               {
               FileClose(handle1);                                // File closing
               return(macdsignal);                                            // Exit start()      
               }
         FileClose(handle1);
         }
    
//---------------------------------------------------------------------------------------------------------------------
//EMA signal
      {
      if(close>ema)
      {emasignal=1;}
      
      if(close<ema)
      {emasignal=2;}
      }
//---------------------------------------------------------------------------------------------------------------------
//signal
bool buysignal;
bool sellsignal;
   
   if(macdzone==1&&emasignal==1)
      {buysignal=true;}
   if(macdzone==2&&emasignal==2)
      {sellsignal=true;}
      
//---------------------------------------------------------------------------------------------------------------------
//other conditions
//no opposite signal and max open order
int ticket;
int PositionIndex; 
int TotalNumberOfOrders          =  OrdersTotal();
int Magic                        = 111;

   if (ticket>0)
      {
      for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --)
         {
         if(OrderSelect(PositionIndex,SELECT_BY_POS,MODE_TRADES))
            {
            if(OrderType()==OP_BUY)
               {            
               sellsignal=false;
               }
            if(OrderType()==OP_SELL)
               {
               buysignal=false;
               }
            }
         }
     }
     
//---------------------------------------------------------------------------------------------------------------------
//timing
   if (!istradinghours(starthour,endhour,startminute,endminute))
      {
      enableopentime = false;
      }


//entry per day capped-----------------------------------------------------
   if (entrytoday >= entry_per_day) 
      {
      enableopen = false;
      Comment("max entries reached\n");
      }
   else enableopen= true;

if(enableopentime == false)
{entrytoday=0;}

//---------------------------------------------------------------------------------------------------------------------
//comment


Comment
      (
      "timetrading",enableopentime,"\n",  //opentime
      "macdsignal",macdsignal,"\n",       //signal buy or sell
      "macdzone",macdzone,"\n",           //zone
      "lastmacd",lastmacd,"\n",           //savedmacd when crossed
      "past20macd",past20macd,"\n",       //if past20macd matched then macdzone = 0 
      "emasignal",emasignal,"\n",         //signal buy or sell
      "entrytoday",entrytoday,"\n",
      "enableopen",enableopen,"\n",
      "symbol",Symbol());

//---------------------------------------------------------------------------------------------------------------------
//position entry(should change to limitbuy/sell in real time)
//macdzone + emasignal
//less than max order
//open time
//not buying within same bar
static datetime Time0Buy;

if (buysignal==true && TotalNumberOfOrders<maxorders && enableopen == true && enableopentime == true && Time0Buy != Time[0])
      {
      ticket=OrderSend(Symbol(),OP_BUYLIMIT,lotsize,close,slippage,0,0,NULL,NULL,Magic,Green);
      if(ticket<0)
         {
         Print("OrderSend failed with error #",GetLastError());
         }
      else Time0Buy = Time[0];                //reset global variable to 0 and prevent further signal in bar
         // If there are order then modify position for sl and tp
         {
         entrytoday++;
         bool res = OrderModify(ticket, 0, close-stoploss, close+takeprofit, 0);
         if(!res) 
            {  
            Alert("OrderModify Error: ", GetLastError());
            Alert("IMPORTANT: ORDER #", ticket, " HAS NO STOPLOSS AND TAKEPROFIT");
            }
         }
      return(ticket);
      }

   if(sellsignal==true && TotalNumberOfOrders<maxorders && enableopen == true && enableopentime == true && Time0Buy != Time[0])                                                                   //condition 
      {
      ticket=OrderSend(Symbol(),OP_SELLLIMIT,lotsize,close,slippage,0,0,NULL,NULL,Magic,Red);          //entry market sell
      if(ticket<0)
         {
         Print("OrderSend failed with error #",GetLastError());
         }
      else Time0Buy = Time[0];
         {
         entrytoday++;
         OrderModify(ticket, 0, close+stoploss, close-takeprofit, 0);
         if(!res) 
            {  
            Alert("OrderModify Error: ", GetLastError());
            Alert("IMPORTANT: ORDER #", ticket, " HAS NO STOPLOSS AND TAKEPROFIT");
            }
         }
      return(ticket);
      }
//---------------------------------------------------------------------------------------------------------------------
//close within 20 bars
int opentimedifference   =  (Time[0]-OrderOpenTime());
int opentimeintervals    =  (Period()*60*tpbarinterval);//1min=60

for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --)
   {
   if(!(OrderSelect(PositionIndex,SELECT_BY_POS,MODE_TRADES)))continue;
      {
      if(opentimedifference>=opentimeintervals)
      if(OrderType()==OP_BUY)
         {
         OrderClose(OrderTicket(),lotsize,Bid,slippage,CLR_NONE);
         }
      if(OrderType()==OP_SELL)
         {
         OrderClose(OrderTicket(),lotsize,Ask,slippage,CLR_NONE);
         }
      }
   }

//---------------------------------------------------------------------------------------------------------------------



  return(0);
}
Roberto Jacobs
48616
Roberto Jacobs  
tonyming:

Hi Guys,


Can someone help me to go through my macd ea and advice me on how to perfect the following?

1. The macd indicator is not indicating when the line crossed

2. The ordersend failed with error #3


Thanks and appreciate your help.

The ordersend failed with error #3 :

3

ERR_INVALID_TRADE_PARAMETERS

Invalid trade parameters


For pending orders, should not use expiration = NULL.
it should be 0 (zero).

tonyming
18
tonyming  
Roberto Jacobs:

The ordersend failed with error #3 :

3

ERR_INVALID_TRADE_PARAMETERS

Invalid trade parameters


For pending orders, should not use expiration = NULL.
it should be 0 (zero).


Thank you. Roberto

Do you know anything about the MACD, why the cross over didnt work out?

Roberto Jacobs
48616
Roberto Jacobs  
tonyming:


Thank you. Roberto

Do you know anything about the MACD, why the cross over didnt work out?

I see your code is old code with syntax MQL4 obsolete that you've modified into 2017.
And I can see, that's something easy like MACD indicator, you make it difficult and complicated in your EA code.
To learn about EA base on MACD indicator, you can see in the folder MQL4/Experts/MACD Sample.mq4 (this is
a very good example made by MQL)

Your code is complicated, example:

int start()
   {
   
   GlobalVariablesDeleteAll();          // Deleting of all GVs

   // GlobalVariablesDeleteAll() is the function for Deletes global variables of the client terminal.
   // by calling this function: You've deleted all the variables used by the indicator in the input parameters.
   // then, how the indicators will provide value in your EA code below?
      
   double ema = iMA(NULL,0,60,0,MODE_EMA,PRICE_MEDIAN,lastbar);
   double close=iClose(NULL,0,lastbar);
   double past20macd=iMACD(Symbol(), 0, FAST_EMA_PERIOD, SLOW_EMA_PERIOD, MACD_SIGNAL_PERIOD, PRICE_TYPICAL, MODE_MAIN, macdbarinterval+1);

tonyming
18
tonyming  
Roberto Jacobs:

I see your code is old code with syntax MQL4 obsolete that you've modified into 2017.
And I can see, that's something easy like MACD indicator, you make it difficult and complicated in your EA code.
To learn about EA base on MACD indicator, you can see in the folder MQL4/Experts/MACD Sample.mq4 (this is
a very good example made by MQL)

Your code is complicated, example:


Yes, you are right. I had deleted the code Global variable delete.

I still have 2 questions,

1. do you have the macd 2 line indicator or place to look for it?

I used a macd indicator as attached, the indicator lines crossed, but not in iMACD, it might be due to the indicator is wrong or my coding is wrong.

2. How do i use the buylimit, the limit was deleted once it created.

Or can you show me a sample of BuyLimit with Close[1] as entry, then take profit and stoploss modification.

static datetime Time0Buy;

if (buysignal==true && TotalNumberOfOrders<maxorders && enableopen == true && enableopentime == true && Time0Buy != Time[0])
      {
      ticket=OrderSend(Symbol(),OP_BUYLIMIT,lotsize,close,slippage,0,0,NULL,Magic,0,Green);
      if(ticket<0)
         {
         Print("OrderSend failed with error #",GetLastError());
         }
      else Time0Buy = Time[0];                //reset global variable to 0 and prevent further signal in bar
         // If there are order then modify position for sl and tp
         {
         entrytoday++;
         bool res = OrderModify(ticket, 0, close-stoploss, close+takeprofit, 0);
         if(!res) 
            {  
            Alert("OrderModify Error: ", GetLastError());
            Alert("IMPORTANT: ORDER #", ticket, " HAS NO STOPLOSS AND TAKEPROFIT");
            }
         }
      return(ticket);
      }
Roberto Jacobs
48616
Roberto Jacobs  

tonyming:

I still have 2 questions,

1. do you have the macd 2 line indicator or place to look for it?

== in CodeBase I've MACD_2ToneColor - indicator for MetaTrader 4

I used a macd indicator as attached, the indicator lines crossed, but not in iMACD, it might be due to the indicator is wrong or my coding is wrong.

== you code is wrong

2. How do i use the buylimit, the limit was deleted once it created.

== buy_limit is the pending order, price for buy_limit pending onder should be further away below from the market price at the closest distance is the distance stop_level. (example = 15 Point)

Or can you show me a sample of BuyLimit with Close[1] as entry, then take profit and stoploss modification.

== pending orders should have expiration time, for example for 1hour = 1x60x60, if 0, means it will never expiration.

== buy_limit price must be below the market price (NOT at Close[1] as entry), take profit = buy_limit price + (your tp value x Point), and stop loss = buy_limit price - (your sl value x Point).

whroeder1
17122
whroeder1  
      ticket=OrderSend(Symbol(),OP_SELLLIMIT,lotsize,close,slippage,0,0,NULL,NULL,Magic,Red);          //entry market sell

You can use NULL in place of _Symbol only in those calls that the documentation specially says you can. iHigh does, MarketInfo does not. OrderSend does not.

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.

Zero is the same as PERIOD_CURRENT which means _Period.

No need for a function call with iHigh(NULL,0,s) just use the predefined arrays, i.e. High[]

tonyming
18
tonyming  
Roberto Jacobs:

tonyming:

I still have 2 questions,

1. do you have the macd 2 line indicator or place to look for it?

== in CodeBase I've MACD_2ToneColor - indicator for MetaTrader 4

I used a macd indicator as attached, the indicator lines crossed, but not in iMACD, it might be due to the indicator is wrong or my coding is wrong.

== you code is wrong

2. How do i use the buylimit, the limit was deleted once it created.

== buy_limit is the pending order, price for buy_limit pending onder should be further away below from the market price at the closest distance is the distance stop_level. (example = 15 Point)

Or can you show me a sample of BuyLimit with Close[1] as entry, then take profit and stoploss modification.

== pending orders should have expiration time, for example for 1hour = 1x60x60, if 0, means it will never expiration.

== buy_limit price must be below the market price (NOT at Close[1] as entry), take profit = buy_limit price + (your tp value x Point), and stop loss = buy_limit price - (your sl value x Point).


Hi Roberto,

I had use the code from macd sample. But I still cant find what is wrong in my macd crossing, it is still not functioning well.

My crossing is actually the crossing between the macd line and signal line. I found out that they didnt work is because the value is actually not crossing while in the graph they do crossed over as ex4 attached.

Or is it the lines in the indicator is wrong?

//MACD signal
   double MacdCurrent,MacdPrevious;
   double SignalCurrent,SignalPrevious;
   double macdzone;
   
   MacdCurrent=iMACD(NULL,0,FAST_EMA_PERIOD, SLOW_EMA_PERIOD, MACD_SIGNAL_PERIOD,PRICE_CLOSE,MODE_MAIN,0);
   MacdPrevious=iMACD(NULL,0,FAST_EMA_PERIOD, SLOW_EMA_PERIOD, MACD_SIGNAL_PERIOD,PRICE_CLOSE,MODE_MAIN,1);
   SignalCurrent=iMACD(NULL,0,FAST_EMA_PERIOD, SLOW_EMA_PERIOD, MACD_SIGNAL_PERIOD,PRICE_CLOSE,MODE_SIGNAL,0);
   SignalPrevious=iMACD(NULL,0,FAST_EMA_PERIOD, SLOW_EMA_PERIOD, MACD_SIGNAL_PERIOD,PRICE_CLOSE,MODE_SIGNAL,1);
   
      {
      if(MacdCurrent>SignalCurrent && MacdPrevious<=SignalPrevious)
         {
         macdsignal=1;
         }
      if(MacdCurrent<SignalCurrent && MacdPrevious>=SignalPrevious)
         {
         macdsignal=2;
         }   
      else macdsignal=0;
      }

Secondly, since what i actually want is to buy at the close of previous bar, and limit didnt allow me to do it.(must be 15 pip further)

Is there any function that i can make it continue to retry ordersend at the price until it execute, or until no signal?Sample?

To add comments, please log in or register