//+------------------- DO NOT REMOVE THIS HEADER --------------------+
//|                                                                  |
//|                        Peak Trader V5_SELL                        |
//|                     System developed by JWentro                  |
//|                                                                  |
//|                Special Thanks to Zen_leow & Hayseed              |
//|              for their programming input. Without them           |
//|                       this EA would not exist                    |
//|                                                                  |
//| In no event will the author be liable for any damages whatsoever |
//|                      Use at your own risk.                       |
//|                ONLY USE THIS EA ON EURUSD 1M CHARTS!!!           |
//|                                                                  |
//+------------------- DO NOT REMOVE THIS HEADER --------------------+

#define SIGNAL_NONE 0
#define SIGNAL_BUY   1
#define SIGNAL_SELL  2
#define SIGNAL_CLOSEBUY 3
#define SIGNAL_CLOSESELL 4

#property copyright "Peak Trader V5_SELL"
#property link      "http://www.forexfactory.com"

extern int MagicNumber = 001;
extern bool SignalMail = False;
extern bool EachTickMode = True;
extern bool PlaySounds = True;
extern double Lotslvl1 = 0.01;
extern double Lotslvl2 = 0.03;
extern double Lotslvl3 = 0.15;
extern double Lotslvl4 = 0.57;
extern int Slippage = 1;
extern bool UseStopLoss = True;
extern int StopLoss = 15;
extern bool UseTakeProfit = True;
extern int TakeProfit = 10;
extern int TakeProfit2 = 6;
extern int TakeProfit3 = 4;
extern bool DelayEntry = true;
extern int Delay = 5;
extern bool UseTrailingStop = True;
extern int TrailingStop = 4;
extern double interval=5;  // minutes between trades
extern double Pips = 15;   // Pips Between Close(-2) and Close(0) neccessary for trade to take place

bool trade_allowed=true;
double minutes = 0;
int BarCount;
int Current;
bool TickCheck = False;

datetime      CheckTime;
datetime      CheckEntryTime;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init() {
   BarCount = Bars;

   if (EachTickMode) Current = 0; else Current = 1;

   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit() {
   return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start() {
   int Order = SIGNAL_NONE;
   int Total, Ticket;
   double StopLossLevel, TakeProfitLevel;
   double interval2 = interval*60;
   if (TimeCurrent()<minutes) trade_allowed=false;
   if (TimeCurrent()>minutes) trade_allowed=true;
   if(LastOrderProfit(MagicNumber) > 0 && CountOrders(MagicNumber) == 0) {DeletePending(MagicNumber);}



   if (EachTickMode && Bars != BarCount) TickCheck = False;
   Total = OrdersTotal();
   Order = SIGNAL_NONE;

   //+------------------------------------------------------------------+
   //| Variable Begin                                                   |
   //+------------------------------------------------------------------+

double Var1 = iClose(NULL, 0, Current + 2);
double Var2 = iClose(NULL, 0, Current + 0);
double Var3 = iLow(NULL, 0, Current + 0);
double Var4 = iHigh(NULL, 0, Current + 0);

double Sell1_1 =  Var2  -  Var1 ;
double Sell1_2 = Pips/10000;
double Sell2_1 =  Var2 - 0.0002;
double Sell2_2 = Bid;
double Sell3_1 =  Var2 ;
double Sell3_2 =  Var3 ;


   
   //+------------------------------------------------------------------+
   //| Variable End                                                     |
   //+------------------------------------------------------------------+

   //Check position
   bool IsTrade = False;

   for (int i = 0; i < Total; i ++) {
      OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
      if(OrderType() <= OP_SELL &&  OrderSymbol() == Symbol()) {
         IsTrade = True;
         if(OrderType() == OP_BUY) {
            //Close

            //+------------------------------------------------------------------+
            //| Signal Begin(Exit Buy)                                           |
            //+------------------------------------------------------------------+

            

            //+------------------------------------------------------------------+
            //| Signal End(Exit Buy)                                             |
            //+------------------------------------------------------------------+

            if (Order == SIGNAL_CLOSEBUY && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
               OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, MediumSeaGreen);
               if (SignalMail) SendMail("[Signal Alert]", "[" + Symbol() + "] " + DoubleToStr(Bid, Digits) + " Close Buy");
               if (!EachTickMode) BarCount = Bars;
               IsTrade = False;
               continue;
            }
            //Trailing stop
            if(UseTrailingStop && TrailingStop > 0) {
            if(OrderLots() < Lotslvl2){                 
               if(Bid - OrderOpenPrice() > Point * TrailingStop) {
                  if(OrderStopLoss() < Bid - Point * TrailingStop) {
                     OrderModify(OrderTicket(), OrderOpenPrice(), Bid - Point * TrailingStop, OrderTakeProfit(), 0, MediumSeaGreen);
                     if (!EachTickMode) BarCount = Bars;
                     continue;
                  }
               }
            }
         }
         } else {

                  }
               }
            }
         


   //+------------------------------------------------------------------+
   //| Signal Begin(Entry)                                              |
   //+------------------------------------------------------------------+

   if (Sell1_1 > Sell1_2 && Sell2_1 <= Sell2_2 && Sell3_1 != Sell3_2 && trade_allowed && CountOrders(MagicNumber) == 0) Order = SIGNAL_SELL;
      {
      if(DelayEntry)
      {
      if(CountOrders(MagicNumber) != 0 && CheckEntryTime > (TimeCurrent() - Delay*60)) return(0); else CheckEntryTime = iTime(NULL,0,0);                  //--->iTime(NULL,0,Delay)
      }}

   //+------------------------------------------------------------------+
   //| Signal End                                                       |
   //+------------------------------------------------------------------+

   //sell

   
   if (Order == SIGNAL_SELL && ((EachTickMode && !TickCheck) || (!EachTickMode && (Bars != BarCount)))) {
      if(!IsTrade) {
         //Check free margin
         if (AccountFreeMargin() < (1000 * Lotslvl1)) {
            Print("We have no money. Free Margin = ", AccountFreeMargin());
            return(0);
         }

         if (UseStopLoss) StopLossLevel = Bid + StopLoss * Point; else StopLossLevel = 0.0;
         if (UseTakeProfit) TakeProfitLevel = Bid - TakeProfit * Point; else TakeProfitLevel = 0.0;

                

OrderSend(Symbol(), OP_SELL,      Lotslvl1, Bid,            Slippage, StopLossLevel,             TakeProfitLevel,          "Sell", MagicNumber, 0, Red);
minutes=TimeCurrent()+interval2;
OrderSend(Symbol(), OP_SELLLIMIT, Lotslvl2, Bid+(14*Point), Slippage, StopLossLevel +(14*Point), TakeProfitLevel+0.0018, "Sell", MagicNumber, 0, Red);
OrderSend(Symbol(), OP_SELLLIMIT, Lotslvl3, Bid+(28*Point), Slippage, StopLossLevel +(28*Point), TakeProfitLevel+0.0034, "Sell", MagicNumber, 0, Red);
OrderSend(Symbol(), OP_SELLLIMIT, Lotslvl4, Bid+(42*Point), Slippage, StopLossLevel +(47*Point), TakeProfitLevel+0.0047, "Sell", MagicNumber, 0, Red);
   
if (PlaySounds) PlaySound("alert.wav");
         }       
         return(0);
      }
   }

  
//+------------------------------------------------------------------+
   
void DeletePending(int MagicNumber)
{

 int total = OrdersTotal();
 
 
  for(int i=total-1;i>=0;i--)
  {
    OrderSelect(i, SELECT_BY_POS);
    
   if(OrderSymbol()!=Symbol() || OrderMagicNumber() != MagicNumber)
   continue;
 
    int type   = OrderType();

    bool result = false;
    
    switch(type)
    {
     
      case OP_BUYLIMIT  :
      case OP_BUYSTOP   :
      case OP_SELLLIMIT :
      case OP_SELLSTOP  : result = OrderDelete( OrderTicket() );
    }
    }
    }
    
    


    
int LastOrderProfit(int MagicNumber) 
{
  int profit =  0;
  datetime dt = 0;
  
  int cnt = HistoryTotal();
  for (int i=0; i < cnt; i++) {
    if (!OrderSelect(i, SELECT_BY_POS, MODE_HISTORY)) continue;
    
    if (OrderSymbol() != Symbol()) continue;
    if (OrderMagicNumber() != MagicNumber) continue;
        
    if (OrderCloseTime() > dt) {
      dt = OrderCloseTime();
      profit = OrderProfit()*100;
      
    }
    }  
  return (profit);
}


//-----------------------------
int CountOrders(int MagicNumber)
{
 int count=0;
 int i;
 int total=OrdersTotal();
 for(i=0;i<total;i++)
 {
  OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
  
  if(OrderSymbol()!=Symbol() || OrderMagicNumber() != MagicNumber )
   continue;
   
  if(OrderType()>OP_BUY)continue;
  count++;
 }
 return(count);
}

