I need help with a code - page 4

 
diamstar:
I saw d name of d e a at the top right corner with an x in front of it not a smiley after attaching the e a . I did input the time in gmt.


Hi diamstar,

First of all you need to understand that the code you get here is for learning purposes.

That means that you test, modify or use the code in any way you like at your own risk.

Back to your problem, if you don't get a smiley face, check the Expert Advisers button.

If it's red, press it.

Also, you may need to check the settings on MT4 .

Go to Tools and select Options (last one on the bottom).

If it doesn't look like this :

make it look like this.

It should work now. Remember, if you want to stop the EA, just press the Expert Adviser button.

Did you run any back testing yet?

The time should be in server time.

 
Thank you. I am now seeing the smiley. I will update you after testing it this week. Thanks once again.
 
diamstar:
Thank you. I am now seeing the smiley. I will update you after testing it this week. Thanks once again.


Do you know how to run a back test in strategy tester, visual or not, and the optimization feature ?

Or are you just happy to test on demo ? Finding the best settings may be faster an easier with the strategy tester.

Good luck

 
I am seeing the smiley but the order is still not activated. I checked the journal of the strategy tester and I am seeing ordersend error 130
 
diamstar:
I am seeing the smiley but the order is still not activated. I checked the journal of the strategy tester and I am seeing ordersend error 130


Can you please post your settings and chart time frame that you're using?

If you need clarifications for settings, just ask, no problem.

Here is a slightly improved version, again for learning purposes as usual.

//+------------------------------------------------------------------+
//|                                               News_Trader_v1.mq4 |
//|                                            Copyright © 2013 _3DE |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2013 _3DE"
#property link      "http://www.metaquotes.net"
extern string  Note1       ="Set parameters in Pips not points !";
extern string  Note5       ="Set PeriodSignal in minutes!";
extern string  Note6       ="1=M1;5=M5;15=M15;30=M30;60=H1;240=H4;1440=D1!";
extern int     PeriodForSignal=15;
extern int     TakeProfit  =25;// Take profit pips
extern int     StopLoss    =0;// Stop loss pips (manual trading)
extern string  Note4       ="Leave SetDistance to zero if trading news !";
extern int     SetDistance=10;// Distance for BuyStop and SellStop from price at news time
extern string  Note2       ="Set day of the month for the news !";
extern string  Note3       ="Set to zero to trade every day at the same time !";
extern int     DayOfNews   = 0;// Day of the month of news
extern int     NewsHour    = 0;// Hour of news
extern int     NewsMin     = 1;// Minute of news
extern int     Expiration= 600;// Expiration of pending orderes
extern int     BEPips      =0;// Move to break even after BEPips
extern int     TrailingStop= 0;// What distance to keep trailing
extern int     Slip        = 5;// Slippage
extern int     MagicNumber=2210;// Must be unique for every chart
extern double  Lots=0.1;
extern bool    WriteLog=false;// Write a log file 
extern string  TradeLog    ="MI_Log";
input  string  EaComment   ="NewsTrader_EA";

double high_M1,low_M1,openPriceBuyStop,openPriceSellStop,slOpenBuyStop,slSellStop,tpOpenBuyStop,tpSellStop,spread,price;

string filename;
int pointMultiply=10;
double minDist=0;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
   if(SetDistance==0)pointMultiply=10;
   else {pointMultiply=SetDistance;}
   if(Digits==3 || Digits==5)
     {
      pointMultiply  *=10;
      TakeProfit     *=10;
      StopLoss       *=10;
      BEPips         *=10;
      TrailingStop   *=10;
      SetDistance    *=10;
     }
   minDist=MarketInfo(NULL,MODE_STOPLEVEL)*Point;
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
   int i;
   int OrdersCondition,minofday,minofnews;

   filename=Symbol()+TradeLog+"-"+Month()+"-"+Day()+".txt";

   if(BEPips>0) DoBE(BEPips);

   if(TrailingStop>0) DoTrail();

   OrdersCondition=CheckOrdersCondition();
   if(Day()==DayOfNews || DayOfNews==0)
     {
      minofday=Hour()*60+Minute();
      minofnews=NewsHour*60+NewsMin;

      if((minofday==minofnews-2) || (minofday==minofnews-1))
        {
         high_M1=iHigh(NULL,PeriodForSignal,0);
         low_M1=iLow(NULL,PeriodForSignal,0);
         //--- Get the highest high and lowest low for the last 3 bars on 1 minute

         for(i=1;i<=3;i++) if(iHigh(NULL,PeriodForSignal,i)>high_M1) high_M1=iHigh(NULL,PeriodForSignal,i);
         for(i=1;i<=3;i++) if(iLow(NULL,PeriodForSignal,i)<low_M1) low_M1=iLow(NULL,PeriodForSignal,i);

         spread=Ask-Bid;
         openPriceBuyStop=NormalizeDouble((high_M1+spread+(pointMultiply*Point)),Digits);
         slOpenBuyStop=NormalizeDouble(high_M1,Digits);
         tpOpenBuyStop=NormalizeDouble((openPriceBuyStop+(TakeProfit*Point)+spread),Digits);
         if((openPriceBuyStop-slOpenBuyStop)<minDist)
           {
            slOpenBuyStop=NormalizeDouble(openPriceBuyStop-minDist-spread,Digits);
           }
         //---
         openPriceSellStop=NormalizeDouble(low_M1-(pointMultiply*Point),Digits);
         slSellStop=NormalizeDouble(low_M1,Digits);
         tpSellStop=NormalizeDouble((openPriceSellStop-(TakeProfit*Point)-spread),Digits);
         if((slSellStop-openPriceSellStop)<minDist)
           {
            slSellStop=NormalizeDouble(openPriceSellStop+minDist+spread,Digits);
           }
         //---
         if(StopLoss>0&&SetDistance>0)
           {
            price=(Ask+Bid)/2;
            high_M1=price+(SetDistance*Point);
            low_M1=price-(SetDistance*Point);
            openPriceBuyStop=NormalizeDouble(high_M1+spread,Digits);
            slOpenBuyStop=NormalizeDouble(openPriceBuyStop-(StopLoss*Point),Digits);
            tpOpenBuyStop=NormalizeDouble(openPriceBuyStop+(TakeProfit*Point),Digits);

            if((openPriceBuyStop-slOpenBuyStop)<minDist)
              {
               slOpenBuyStop=NormalizeDouble(openPriceBuyStop-minDist-(StopLoss*Point),Digits);
               Alert("Stop too close ! Check your StopLoss settitngs !!!");
              }
            openPriceSellStop=NormalizeDouble(low_M1-spread,Digits);
            slSellStop=NormalizeDouble(openPriceSellStop+(StopLoss*Point),Digits);

            if((slSellStop-openPriceSellStop)<minDist)
              {
               slSellStop=NormalizeDouble(openPriceSellStop+minDist+(StopLoss*Point),Digits);
               Alert("Stop too close ! Check your StopLoss settitngs !!!");
              }
            tpSellStop=NormalizeDouble(openPriceSellStop-(TakeProfit*Point),Digits);
           }
         if(OrdersCondition==0)
           {
            if(WriteLog)Write("Opening BuyStop & SellStop, OrdersCondition="+OrdersCondition+" MinOfDay="+minofday);
            OpenBuyStop();
            OpenSellStop();
           }

         if(OrdersCondition==10)
           {
            if(WriteLog)Write("Opening SellStop, OrdersCondition="+OrdersCondition+" MinOfDay="+minofday);
            OpenSellStop();
           }

         if(OrdersCondition==1)
           {
            if(WriteLog)Write("Opening BuyStop , OrdersCondition="+OrdersCondition+" MinOfDay="+minofday);
            OpenBuyStop();
           }
        }
     }
   if((minofday>=minofnews) && (minofday<=minofnews+Expiration-1))
     {

      if(OrdersCondition==1001)
        {
         if(WriteLog)Write("Deleting SellStop Because of BuyStop Hit, OrdersCondition="+OrdersCondition+" MinOfDay="+minofday);
         DeleteSellStop();
        }

      if(OrdersCondition==110)
        {
         if(WriteLog)Write("Deleting BuyStop Because of SellStop Hit, OrdersCondition="+OrdersCondition+" MinOfDay="+minofday);
         DeleteBuyStop();
        }
     }

   if(minofday>=minofnews+Expiration)
     {
      if(OrdersCondition==11)
        {
         if(WriteLog)Write("Deleting BuyStop and SellStop Because 5 min expired, OrdersCondition="+OrdersCondition+" MinOfDay="+minofday);
         DeleteBuyStop();
         DeleteSellStop();
        }

      if((OrdersCondition==10) || (OrdersCondition==110))
        {
         if(WriteLog)Write("Deleting BuyStop Because 5 min expired, OrdersCondition="+OrdersCondition+" MinOfDay="+minofday);
         DeleteBuyStop();
        }

      if((OrdersCondition==1) || (OrdersCondition==1001))
        {
         if(WriteLog)Write("Deleting SellStop Because 5 min expired, OrdersCondition="+OrdersCondition+" MinOfDay="+minofday);
         DeleteSellStop();
        }
     }

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| int CheckOrdersCondition()                                       |
//+------------------------------------------------------------------+

int CheckOrdersCondition()
  {
   int result=0;
   for(int i=0;i<OrdersTotal();i++)
     {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if((OrderType()==OP_BUY) && (OrderSymbol()==Symbol()) && (OrderMagicNumber()==MagicNumber))
        {
         result+=1000;
        }
      if((OrderType()==OP_SELL) && (OrderSymbol()==Symbol()) && (OrderMagicNumber()==MagicNumber))
        {
         result+=100;
        }
      if((OrderType()==OP_BUYSTOP) && (OrderSymbol()==Symbol()) && (OrderMagicNumber()==MagicNumber))
        {
         result+=10;
        }
      if((OrderType()==OP_SELLSTOP) && (OrderSymbol()==Symbol()) && (OrderMagicNumber()==MagicNumber))
        {
         result+=1;
        }

     }
   return(result); // 0 means we have no trades
  }
// OrdersCondition Result Pattern
//    1    1    1    1
//    b    s    bs   ss
//  
//+------------------------------------------------------------------+
//|void OpenBuyStop()                                                |
//+------------------------------------------------------------------+

void OpenBuyStop()
  {
   int ticket,tries;
   tries=0;
   if(!GlobalVariableCheck("InTrade"))
     {
      while(tries<3)
        {
         GlobalVariableSet("InTrade",TimeCurrent());  // set lock indicator
         ticket=OrderSend(Symbol(),OP_BUYSTOP,Lots,openPriceBuyStop,Slip,slOpenBuyStop,tpOpenBuyStop,EaComment,MagicNumber,0,Red);
         if(WriteLog)Write("in function OpenBuyStop OrderSend Executed , ticket ="+ticket);
         GlobalVariableDel("InTrade");   // clear lock indicator
         if(ticket<=0)
           {
            tries++;
           }
         else tries=3;
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OpenSellStop()
  {
   int ticket,tries;
   tries=0;
   if(!GlobalVariableCheck("InTrade"))
     {
      while(tries<3)
        {
         GlobalVariableSet("InTrade",TimeCurrent());  // set lock indicator
         ticket=OrderSend(Symbol(),OP_SELLSTOP,Lots,openPriceSellStop,Slip,slSellStop,tpSellStop,EaComment,MagicNumber,0,Red);
         if(WriteLog)Write("in function OpenSellStop OrderSend Executed , ticket ="+ticket);
         GlobalVariableDel("InTrade");   // clear lock indicator
         if(ticket<=0)
           {
            tries++;
           }
         else tries=3;
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DoBE(int byPips)
  {
   for(int i=0; i<OrdersTotal(); i++)
     {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()==Symbol() && (OrderMagicNumber()==MagicNumber)) // only look if mygrid and symbol...
        {
         if(OrderType()==OP_BUY) if(Bid-OrderOpenPrice()>byPips*Point) if(OrderStopLoss()<OrderOpenPrice())
           {
            if(WriteLog)Write("Movine StopLoss of Buy Order to BE+1");
            OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+Point,OrderTakeProfit(),Red);
           }
         if(OrderType()==OP_SELL) if(OrderOpenPrice()-Ask>byPips*Point) if(OrderStopLoss()>OrderOpenPrice())
           {
            if(WriteLog)Write("Movine StopLoss of Buy Order to BE+1");
            OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-Point,OrderTakeProfit(),Red);
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DoTrail()
  {
   for(int i=0; i<OrdersTotal(); i++)
     {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()==Symbol() && (OrderMagicNumber()==MagicNumber)) // only look if mygrid and symbol...
        {

         if(OrderType()==OP_BUY)
           {
            if(Bid-OrderOpenPrice()>Point*TrailingStop)
              {
               if(OrderStopLoss()<Bid-Point*TrailingStop)
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Point*TrailingStop,OrderTakeProfit(),0,Green);
                  return;
                 }
              }
           }

         if(OrderType()==OP_SELL)
           {
            if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
              {
               if((OrderStopLoss()>(Ask+Point*TrailingStop)) || (OrderStopLoss()==0))
                 {
                  OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,OrderTakeProfit(),0,Red);
                  return;
                 }
              }
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DeleteBuyStop()
  {
   for(int i=0; i<OrdersTotal(); i++)
     {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()==Symbol() && (OrderMagicNumber()==MagicNumber) && (OrderType()==OP_BUYSTOP))
        {
         OrderDelete(OrderTicket());
         if(WriteLog)Write("in function DeleteBuyStopOrderDelete Executed");
        }

     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DeleteSellStop()
  {
   for(int i=0; i<OrdersTotal(); i++)
     {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()==Symbol() && (OrderMagicNumber()==MagicNumber) && (OrderType()==OP_SELLSTOP))
        {
         OrderDelete(OrderTicket());
         if(WriteLog)Write("in function DeleteSellStopOrderDelete Executed");
        }

     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void Write(string str)
  {
   int handle;

   handle=FileOpen(filename,FILE_READ|FILE_WRITE|FILE_CSV,"/t");
   FileSeek(handle,0,SEEK_END);
   FileWrite(handle,str+" Time "+TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS));
   FileClose(handle);
  }
//+------------------------------------------------------------------+

I've added the PeriodForSgnal parameter since the previous was taking signals only of 1 minute time frame, now you can set it to 5, 15, 60 minute, whatever you want if trading news.

When StopLoss=0 it will calculate a stop loss for you. If SetDistance=0, it will calculate a distance for pending orders.

 
It worked!!! I am able to run some back testing today, I made a mistake in one of the inputs. I will still try out some testing on a demo account. Thanks a million times.
 
diamstar:
It worked!!! I am able to run some back testing today, I made a mistake in one of the inputs. I will still try out some testing on a demo account. Thanks a million times.


You're welcome.

Glad to here you're learning.

And you're welcome to ask if you have any other questions.

 
hello the e a is working fine in backtesting but not working on demo. The articles I have seen online are showing something like the order send and the order modify wouldhave to be sent differently. I do not really understand this. Thanks
 
diamstar:
hello the e a is working fine in back testing but not working on demo. The articles I have seen online are showing something like the order send and the order modify wouldhave to be sent differently. I do not really understand this. Thanks


Hi diamstar,

Glad to hear that you're learning . Now, are you sure you are talking about demo and not live account ?

I'm aware that some brokers don't allow EA's to place orders with stop loss and take profit on live accounts so

the work around is to modify the EA to send the orders with zero stop loss and zero take profit and then use another function to modify

the stop loss and take profit to whatever value you want, but again, that is for live accounts not demo.

If what you say happens on demo, you need to press Terminal button and check the Experts tab and the Journal tab and see if you get any errors in there.

If you do get any error messages, let me know what they are.

It's hard to guess on such little details what you're trying to do and what goes wrong. Let me know how you use it, what your stop is, take profit, etc.

I'm working on improving this EA as it shows potential for good results with the right parameters and the right time for the orders.

I will keep you updated as long as you're interested.

 
thank you, the book has been a great help in understanding the code. It even worked perfectly on a demo when I changed the input values. And of course I am more than willing to learn.
Reason: