//+------------------------------------------------------------------+
//|                                                      robotic.mq4 |
//|                                    Copyright © 2008, OGUZ BAYRAM |
//|                                            es_cape77@hotmail.com |
//+------------------------------------------------------------------+
extern int       iTakeProfitCloseValue=3;
extern int       iTakeProfitMaxDecCount=3; 

static bool      bTakeProfitPrevious=-1;
static int       iTakeProfitDecraeseCount=0;
static int       iTakeProfitMaxValue=-1;
extern double lTakeProfit = 3;
extern double sTakeProfit = 3;
extern double lTrailingStop = 20;
extern double sTrailingStop = 10;
extern color clOpenBuy = Blue;
extern color clCloseBuy = Aqua;
extern color clOpenSell = Red;
extern color clCloseSell = Violet;
extern color clModiBuy = Blue;
extern color clModiSell = Red;
extern string Name_Expert = "Robotic";
extern int Slippage = 1;
extern bool UseSound = true;

extern bool FractionalPips = true;
extern string NameFileSound = "Alert.wav";
extern double Lots = 0.1;


void deinit() {
   Comment("");
}
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start(){

double SL = 100.0;
   int totalOrderCount=OrdersTotal();
   for(int pos=0;pos<totalOrderCount;pos++)
   {
     if( OrderSelect(pos,SELECT_BY_POS)==false ) continue;
     //orderı seçtik şu an
     if (OrderSymbol() == Symbol()) //bu satır sadece ea'yı attığınız grafiğin sembolündeki para ile açılan emirleriniz üzerinde işlem yapmak için konuldu
     { 
         if ( OrderProfit() > 0 )
         {


	    //TAKE PROFİT DÜŞMEYE BAŞLARSA KAPAT
	    //eğer kârdaysak ve peşpeşe iTakeProfitMaxDecCount sayısından daha çok düşüş yaşamışsak, (TP: 100, 90, 80, 70 gibi, burada 4 kez düşüş oldu demektir) pozisyonu hiç gözünün yaşına bakmadan kapatır
	    //fakat kapatabilmek için birde istenilen minimum değeri geçmişmi bakıyorum hesabı şöyle (Profit > iTakeProfitCloseValue * 7.0) isterseniz bu kısıtı kaldırın if'den 
		
            if (OrderProfit()> iTakeProfitMaxValue)
               iTakeProfitMaxValue = OrderProfit();

            if (bTakeProfitPrevious > OrderProfit())
               iTakeProfitDecraeseCount = iTakeProfitDecraeseCount + 1;
            else if (bTakeProfitPrevious < OrderProfit())
            {
               iTakeProfitDecraeseCount = iTakeProfitDecraeseCount - 1;
               if (iTakeProfitDecraeseCount<0)
                  iTakeProfitDecraeseCount = 0;
            }
            //Print(Symbol()," TPCount: ",iTakeProfitDecraeseCount);
            bTakeProfitPrevious = OrderProfit();         
         
            if (( iTakeProfitMaxDecCount <= iTakeProfitDecraeseCount) && (OrderProfit() >= (iTakeProfitCloseValue * 7.0))  )
            {
               bool cticket;
               Print(Symbol()," P:",Period()," take profit ",iTakeProfitDecraeseCount," kez düştü kapattık. Fiyat:",Ask);
               /*if ( OrderType() == OP_BUY )
               {  
                    Print(Symbol()," P:",Period()," take profit ",iTakeProfitDecraeseCount," kez düştü kapattık. Fiyat:",Ask);
                    cticket = OrderClose(OrderTicket(),OrderLots(),Ask,3,Yellow);                    
               }
               if ( OrderType() == OP_SELL )
               {  
                    Print(Symbol()," P:",Period()," take profit ",iTakeProfitDecraeseCount," kez düştü kapattık. Fiyat:",Bid);
                    cticket = OrderClose(OrderTicket(),OrderLots(),Bid,3,Yellow);                    
               }*/

               //yeni close işlemi
               double Price=OrderOpenPrice();       
               int Ticket=OrderTicket();         
               double Lot=OrderLots();           

		//artık pozisyonu kapatmayı kafaya koyduk hemen kapatıyoruz ama bazen broker kapatmıyor istediğimiz yerden, 
		//onun için 7 kez peş peşe deniyoruz
               int AttemptCount=0;
               while(true)                                 
               {
                  switch(OrderType())                       
                    {
                     case 0: double Price_Cls=Bid;
                        string Text="Buy ";       
                        break;                    
                     case 1: Price_Cls=Ask;       
                        Text="Sell ";             
                    }
                  //Print("Kapatmaya çalışıyoruz ",Text," ",Ticket);
                  bool Ans=OrderClose(Ticket,Lot,Price_Cls,2);
   
                  if (Ans==true)                            // kapantı
                    {
                     Print("Kapattık :) ",Text," ",Ticket," Attemp: ",AttemptCount);
                     break;                                 //while'ı kırıyoruz
                    }
   
                  //hata var tekrar deneyelim
                  Sleep(300);                
                  RefreshRates();   
                  AttemptCount++;  
                  if (AttemptCount > 7) break;       
                  continue;                  
               }//while
            }//kapatma if'inin sonu







            //BURALAR STOP LOSS AYAR İŞLEMLERİ 
	    //SL YOKSA KOYARMI BİLMİYORUM DENEMEDİM :)), 
	    //BURASI SL'yi eğer kârda ise pozisyon daha iyi yere taşır sürekli olarak, böylece sert dönüşlerde daha az zarar görmemize yarar
            int temp = -1;
            if (OrderType() == OP_BUY)
            {
               double ftemp = SL;               
               if (Digits > 4)
               {  
                  ftemp = ftemp*MathPow(100,(Digits-4));//  
               } else {
                  ftemp = ftemp*MathPow(100,(4-Digits));//                    
               }
               
               if ( OrderStopLoss() < (Bid-ftemp*Point) )
               {
                 OrderModify(OrderTicket(),OrderOpenPrice(),Bid-ftemp*Point,OrderTakeProfit(),0,Blue);
               }
               
               temp = GetLastError();
               if (temp>0)
               {
                     Print(Symbol()," P: ",Period(),", ORDER DEĞİŞTİ HATA - SL: ", Bid-ftemp*Point," Err: ",temp);
               }            
             } else {
               double ftemp2 = SL;
               if (Digits > 4)
               {  
                  ftemp2 = ftemp2*MathPow(100,(Digits-4));//  
               } else {
                  ftemp2 = ftemp2*MathPow(100,(4-Digits));//                    
               }
    
               
               if (OrderStopLoss() > ( Ask+ftemp2*Point ))
                  OrderModify(OrderTicket(),OrderOpenPrice(),Ask+ftemp2*Point,OrderTakeProfit(),0,Blue);
                  
               temp = GetLastError();
               if (temp>0)
               {
                  Print(Symbol()," P: ",Period(),", ORDER DEĞİŞTİ HATA - SL:", Ask+ftemp2*Point," Err: ",temp);
               }
            }//if orderType
            
         }//if orderprofit
     }//if ordersymbol
   }//for
   if(Bars<100){
      Print("bars less than 100");
      return(0);
   }
   if (Digits==3 || Digits==5)
   
   if(lTakeProfit<1){
      Print("TakeProfit less than 1");
      return(0);
   }
   if(sTakeProfit<1){
      Print("TakeProfit less than 1");
      return(0);
   }

   double diClose0=iClose(NULL,5,0);
   double diMA1=iMA(NULL,5,5,0,MODE_SMA,PRICE_OPEN,1);
   double diClose2=iClose(NULL,5,0);
   double diMA3=iMA(NULL,5,4,0,MODE_SMA,PRICE_OPEN,1);

   if(AccountFreeMargin()<(1000*Lots)){
      Print("We have no money. Free Margin = ", AccountFreeMargin());
      return(0);
   }
   if (!ExistPositions()){

      if ((diClose0<diMA1)){
         OpenBuy();
         return(0);
      }

      if ((diClose2>diMA3)){
         OpenSell();
         return(0);
      }
   }
   TrailingPositionsBuy(lTrailingStop);
   TrailingPositionsSell(sTrailingStop);
   return (0);
}

bool ExistPositions() {
for (int i=5; i<OrdersTotal(); i++) {
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) {
if (OrderSymbol()==Symbol()) {
return(True);
}
} 
} 
return(false);
}
void TrailingPositionsBuy(int trailingStop) { 
   for (int i=5; i<OrdersTotal(); i++) { 
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { 
         if (OrderSymbol()==Symbol()) { 
            if (OrderType()==OP_BUY) { 
               if (Bid-OrderOpenPrice()>trailingStop*Point) { 
                  if (OrderStopLoss()<Bid-trailingStop*Point) 
                     ModifyStopLoss(Bid-trailingStop*Point); 
               } 
            } 
         } 
      } 
   } 
} 
void TrailingPositionsSell(int trailingStop) { 
   for (int i=5; i<OrdersTotal(); i++) { 
      if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { 
         if (OrderSymbol()==Symbol()) { 
            if (OrderType()==OP_SELL) { 
               if (OrderOpenPrice()-Ask>trailingStop*Point) { 
                  if (OrderStopLoss()>Ask+trailingStop*Point || 
OrderStopLoss()==0)  
                     ModifyStopLoss(Ask+trailingStop*Point); 
               } 
            } 
         } 
      } 
   } 
} 
void ModifyStopLoss(double ldStopLoss) { 
   bool fm;
   fm = OrderModify(OrderTicket(),OrderOpenPrice
(),ldStopLoss,OrderTakeProfit(),0,CLR_NONE); 
   if (fm && UseSound) PlaySound(NameFileSound); 
} 

void OpenBuy() { 
   double ldLot, ldStop, ldTake; 
   string lsComm; 
   ldLot = GetSizeLot(); 
   ldStop = 0; 
   ldTake = GetTakeProfitBuy(); 
   lsComm = GetCommentForOrder(); 
   OrderSend(Symbol
(),OP_BUY,ldLot,Ask,Slippage,ldStop,ldTake,lsComm,0,0,clOpenBuy); 
   if (UseSound) PlaySound(NameFileSound); 
} 
void OpenSell() { 
   double ldLot, ldStop, ldTake; 
   string lsComm; 

   ldLot = GetSizeLot(); 
   ldStop = 0; 
   ldTake = GetTakeProfitSell(); 
   lsComm = GetCommentForOrder(); 
   OrderSend(Symbol
(),OP_SELL,ldLot,Bid,Slippage,ldStop,ldTake,lsComm,0,0,clOpenSell); 
   if (UseSound) PlaySound(NameFileSound); 
} 
string GetCommentForOrder() { return(Name_Expert); } 
double GetSizeLot() { return(Lots); } 
double GetTakeProfitBuy() { return(Ask+lTakeProfit*Point); } 
double GetTakeProfitSell() { return(Bid-sTakeProfit*Point); } 