//+------------------------------------------------------------------+
//|                                             Better_Volume_EA.mq4 |
//|                      Copyright © 2009, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+

#property copyright "Copyright ? 2008, ForexArea.com"
#property link      "geoffb59@gmail.com"

extern double  dLots      = 0.1;
int     iMagicNumber      = 12790402;
double Poin;
extern double iStopLoss   = 15 ; 
extern double iTakeProfit1 = 20 ;
extern bool   useTrailing = false;
extern double iTrailingStop = 10;
extern int GMToffset=2;
extern int Start_Time= 1;
extern int End_Time= 6;
extern int     NumberOfBars = 0;   // zero means show all bars
extern string  Note = "0";
extern int     MAPeriod = 100;
extern int     LookBack = 20;
extern bool   Show_Settings  = true;
extern int Pip_Buffer= 20;
extern bool Show_Arrows=true;


double highest_high, lowest_low, high_price, low_price;
double last_high, last_low ;
int   iTicket, iTotalOrders,trend,Status,direction,signal;
   double vol_now =0.0; 


//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----
iMagicNumber    = subGenerateMagicNumber( iMagicNumber, Symbol(), Period() );

if ( Show_Settings )
       PrintDetails();

  watermark(); 
//----
//Checking for unconventional Point digits number
if (Point == 0.00001) Poin = 0.0001; //6 digits
else if (Point == 0.001) Poin = 0.01; //3 digits (for Yen based pairs)
else Poin = Point; //Normal 
   

   return(0);
  }
   
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {

//----
   int  iCrossed, xCrossed;
   
   // get total number of orders 
   iTotalOrders = OrdersTotal();
   
   // see if we have a new cross
   iCrossed  = CheckForCross();
   
  if(iTotalOrders != 0 && useTrailing == true) TrailingStop(iTotalOrders);
//----
   return(0);
  }
//+------------------------------------------------------------------+

void TrailingStop(int iTotal){

   int iCount;
   
   if(iTrailingStop < 1)return(-1); // error
   
   for(iCount=0;iCount<iTotal;iCount++){

      OrderSelect(iCount, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()==Symbol() && OrderMagicNumber() == iMagicNumber)
         switch(OrderType()){
            case OP_BUY:
               if(Bid-OrderOpenPrice()>Poin*iTrailingStop){
                  if(OrderStopLoss()<Bid-Poin*iTrailingStop){
                     OrderModify(OrderTicket(),OrderOpenPrice(),Bid-Poin*iTrailingStop,OrderTakeProfit(),0,Green);
                  }
               }
               break;
            case OP_SELL:
               if((OrderOpenPrice()-Ask)>(Poin*iTrailingStop)){
                  if((OrderStopLoss()>(Ask+Poin*iTrailingStop)) || (OrderStopLoss()==0)){
                     OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Poin*iTrailingStop,OrderTakeProfit(),0,Red);
                  }
               }
               break;
         }
      }
   
      return(0);
}

   
 //+---------------------------------------------------------+
 // check if volume has crossed
      
   int CheckForCross(){
   int i, cnt  ;
   int buyorder=0;
   int sellorder=0;
   int sellstop = 0;
   int buystop = 0;
   int dir=0;

  int total = OrdersTotal();
  
      //Calculate expiry time for unused Buy and Sell Stops, close daily at Close_Time pm GMT:
      double expire =StrToTime(TimeYear(Time[0]) + "." + TimeMonth(Time[0]) + "." + TimeDay(Time[0]) + " 08:00")+(GMToffset*3600);

      int order = 0;

      vol_now = iCustom(Symbol(),NULL, "BetterVolume 1.4",NumberOfBars,Note,MAPeriod,LookBack,1,1);
      double ma_now = iCustom(Symbol(),NULL, "BetterVolume 1.4",NumberOfBars,Note,MAPeriod,LookBack,6,1);
      Print (vol_now,ma_now);

      if(Show_Arrows==true && vol_now > 100) ObjectCreate("UP"+Time[1],OBJ_ARROW,0,Time[1],Low[1]-5*Poin);
      if(vol_now > 100){
            high_price = High[1];
            low_price = Low[1];
            order =1;
     }
     
      i= 0;
      for (i = 0; i < total; i++) 
      {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == iMagicNumber) 
         {
         if (OrderType()==OP_BUYSTOP) {buystop = buystop +1;}
         else if (OrderType()==OP_SELLSTOP) {sellstop = sellstop +1;}
         else if (OrderType()==OP_BUY) {buyorder = buyorder +1;}
         else if (OrderType()==OP_SELL) {sellorder = sellorder +1;}
         } 
     }
      
      int day_day = 0;
      int day_time = 0;
      bool trade = false;
      if(DayOfWeek()==1 || DayOfWeek()==2 || DayOfWeek()==3 || DayOfWeek()==4 || DayOfWeek()==5) day_day=1;
      if(Hour() >= Start_Time+GMToffset && Hour() <= End_Time+GMToffset) day_time = 1;//trade between 6 am and 6 pm.
      if(day_day == 1 && day_time == 1) trade = true;
      
      double Ticket=0;
      high_price=high_price+Pip_Buffer*Poin;//pip buffer
      low_price=low_price-Pip_Buffer*Poin;
 //     if (buyorder==0 && sellorder==0 ){
      RefreshRates();
      if (order==1 && trade==true && buystop==0 && buyorder==0){ 
      Ticket=OrderSend(Symbol(),OP_BUYSTOP,dLots,high_price,3,high_price-iStopLoss*Poin,high_price+iTakeProfit1*Poin,"Better Volume",iMagicNumber,expire,Green);
      if(Ticket<0){Print("Buy OrderSend 2 failed with error #",GetLastError());}
      }
       
      else if (order==1 && trade==true && sellstop==0 && sellorder==0){   
      Ticket=OrderSend(Symbol(),OP_SELLSTOP,dLots,low_price,3,low_price+iStopLoss*Poin,low_price-iTakeProfit1*Poin,"Better Volume",iMagicNumber,expire,Red);
      if(Ticket<0){Print("Sell OrderSend 2 failed with error #",GetLastError());}
     }

   return(0);
} 

//+-----------------------------------------------------------------------+

void watermark()
  {
   ObjectCreate("AI", OBJ_LABEL, 0, 0, 0);
   ObjectSetText("AI","BETTER VOLUME EA",12, "Verdana", RoyalBlue);
   ObjectSet("AI", OBJPROP_CORNER, 2);
   ObjectSet("AI", OBJPROP_XDISTANCE, 5);
   ObjectSet("AI", OBJPROP_YDISTANCE, 10);
   return(0);
  }
  //----------------------- GENERATE MAGIC NUMBER BASE ON SYMBOL AND TIME FRAME FUNCTION
//----------------------- SOURCE   : PENGIE
//----------------------- MODIFIED : FIREDAVE
int subGenerateMagicNumber(int iMagicNumber, string symbol, int timeFrame)
{
   int isymbol = 0;
   if (symbol == "EURUSD")       isymbol = 1;
   else if (symbol == "GBPUSD")  isymbol = 2;
   else if (symbol == "USDJPY")  isymbol = 3;
   else if (symbol == "USDCHF")  isymbol = 4;
   else if (symbol == "AUDUSD")  isymbol = 5;
   else if (symbol == "USDCAD")  isymbol = 6;
   else if (symbol == "EURGBP")  isymbol = 7;
   else if (symbol == "EURJPY")  isymbol = 8;
   else if (symbol == "EURCHF")  isymbol = 9;
   else if (symbol == "EURAUD")  isymbol = 10;
   else if (symbol == "EURCAD")  isymbol = 11;
   else if (symbol == "GBPUSD")  isymbol = 12;
   else if (symbol == "GBPJPY")  isymbol = 13;
   else if (symbol == "GBPCHF")  isymbol = 14;
   else if (symbol == "GBPAUD")  isymbol = 15;
   else if (symbol == "GBPCAD")  isymbol = 16;
   else                          isymbol = 17;
   if(isymbol<10) iMagicNumber = iMagicNumber * 10;
   return (StrToInteger(StringConcatenate(iMagicNumber, isymbol, timeFrame)));
}
void PrintDetails()
{
   string sComment   = "";
   string sp         = "----------------------------------------\n";
   string NL         = "\n";
   
   sComment = sp;
   sComment = sComment + "BETTER VOLUME EA"+ NL;
   sComment = sComment + "TakeProfit 1=" + DoubleToStr(iTakeProfit1,0) + " | ";
   sComment = sComment + "StopLoss=" + DoubleToStr(iStopLoss,0) + NL;
   sComment = sComment + "TrailingStop=" + DoubleToStr(iTrailingStop,0) + " | ";
   sComment = sComment + "OrderLots=" +DoubleToStr(dLots,2) +NL;
   sComment = sComment + "Symbols: "+Symbol()+ NL;
   sComment = sComment + sp;
   //---- 10 seconds wait
   Sleep(10000);
   //---- refresh data
   RefreshRates();

   Comment(sComment);
}

