//+------------------------------------------------------------------+
//|                                         PivotPointBreakoutEA.mq4 |
//|                                                    Matthew Purdy |
//|                                      mailto:mpurdy1973@yahoo.com |
//+------------------------------------------------------------------+
#property copyright "Matthew Purdy"
#property link      "mailto:mpurdy1973@yahoo.com"

#define MAGICMA 1234567890

#define MODE_DAILY_HIGH  0
#define MODE_DAILY_LOW   1
#define MODE_PIVOT_POINT 2
#define MODE_DAILY_CLOSE 3

extern bool ExtOneTradeAtATime = true;
extern int ExtLots   = 1;
extern int ExtStop   = 100;
extern int ExtTarget = 150;
extern bool ExtExitWhenReversal = true;

bool glob_bInTrade = false;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{

   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
{

   return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
   if(Volume[0] == 1)
   {
      double pivotPoint = iCustom(NULL, NULL, "mpurdy_PivotPointBreakoutIndicator", MODE_PIVOT_POINT, 1);
 
      double open   = Open[1];
      double close  = Close[1];
      double stop   = 0.0;
      double target = 0.0;
      int error = 0;
      
      if(countCurrentOrders(Symbol()) == 0)
         glob_bInTrade = false;
//Print("orderCurrentCount = ", countCurrentOrders(Symbol()) );      
      if(!ExtOneTradeAtATime || (ExtOneTradeAtATime && !glob_bInTrade))
      {
         int result = -1;

//Print(Time[0] + "." + TimeMonth(Time[0]) + "." + TimeDay(Time[0]) + " " + TimeHour(Time[0]) + ":" + TimeDay(Time[0]) + ":" + TimeMinute(Time[0]), ", close = ", close , ", open = ", open, ", pivot = ", pivotPoint, ", bullPivot = ", (open < close && open < pivotPoint && close > pivotPoint && Open[0] > pivotPoint) , ", bearPivot = ", (close < open && close < pivotPoint && open > pivotPoint && Open[0] < pivotPoint));
         if(open < close && open < pivotPoint && close > pivotPoint && Open[0] > pivotPoint)//go long
         {
//writeToFile("test.txt", TimeYear(Time[0]) + "." + TimeMonth(Time[0]) + "." + TimeDay(Time[0]) + " " + TimeHour(Time[0]) + ":"+ TimeDay(Time[0]) + ":" + TimeMinute(Time[0]) + ", close = " + close + ", open = " + open + ", pivot = " + pivotPoint + ", bullPivot = " + (open < close && open < pivotPoint && close > pivotPoint && Open[0] > pivotPoint) + ", bearPivot = " + (close < open && close < pivotPoint && open > pivotPoint && Open[0] < pivotPoint));

            //stop all short orders
            if(ExtExitWhenReversal)
            {
               closeOrders(0);
         
            }//end if stop reverse 
            
            stop   = Ask - (ExtStop * Point);
            target = Ask + (ExtTarget * Point);
            result = OrderSend(Symbol(), OP_BUY, ExtLots, Ask, 3, stop, target, "", MAGICMA, 0, Blue);
            glob_bInTrade = true;
            
            if(result == -1)
            {
               error = GetLastError();
               Print("error creating order: ", error);
               Alert("error creating order: ", error);
         
            }//end if there was an error sending order             
      
         }//end if go long
         else if(close < open && close < pivotPoint && open > pivotPoint && Open[0] < pivotPoint)//go short
         {
            //stop all long orders
            if(ExtExitWhenReversal)
            {
               closeOrders(1);
         
            }//end if stop reverse         
         
            stop   = Bid + (ExtStop * Point);
            target = Bid - (ExtTarget * Point);         
            result = OrderSend(Symbol(), OP_SELL, ExtLots, Bid, 3, stop, target, "", MAGICMA, 0, Red);
            glob_bInTrade = true;
            
            if(result == -1)
            {
               error = GetLastError();
               Print("error creating order: ", error);
               Alert("error creating order: ", error);
         
            }//end if there was an error sending order  
      
         }//end else go short
      
      }//end if time to trade   
      
   }//end if first tick of new bar

   return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| calculate open positions                                         |
//+------------------------------------------------------------------+
int countCurrentOrders(string symbol)
{
   int buys=0,sells=0;
   //----
   for(int i=0;i<OrdersTotal();i++)
   {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
      {
//Print("magic number = ", OrderMagicNumber(), ", MAGICMA = ", MAGICMA, "test = ", (OrderMagicNumber() == MAGICMA));      
         if(OrderType()==OP_BUY)  buys++;
         if(OrderType()==OP_SELL) sells++;
      }
      
   }//end for
   //---- return orders volume
   if(buys>0) return(buys);
   else       return(-sells);
}
//--------------------------------------------------------------------
//+------------------------------------------------------------------+
//| function writeToFile                                             |
//+------------------------------------------------------------------+

void writeToFile(string filename, string sData)
{
  int handle;
  datetime orderOpen=OrderOpenTime();
  handle = FileOpen(filename, FILE_CSV | FILE_READ | FILE_WRITE, ';');
  if(handle > 0)
  {
     FileSeek(handle, 0, SEEK_END);
     FileWrite(handle, sData);
     FileFlush(handle);
     FileClose(handle);
     handle = 0;
     
  }//end if file opened
  else
  {
     Print("Error opening file " + filename + ": error code: " + GetLastError() );
     
  }//end else failed to open
    
}//end function writeToFile

void closeOrders(int magicNumber)
{
   
   int iOrders=OrdersTotal() - 1, i;
  
   for(i = iOrders; i >= 0; i--)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && (OrderMagicNumber() == magicNumber))
      {
         if(OrderType() == OP_SELL)
            OrderClose(OrderTicket(), OrderLots(), Ask, 5);
         else if(OrderType() == OP_BUY)
            OrderClose(OrderTicket(), OrderLots(), Bid, 5);
         
      }//end if found an order to close
      
   }//end for all the orders


   return;
   
}//end function closeOrders


