//+------------------------------------------------------------------+
//|                                       ManualTrader_v1.6 600+.mq4 |
//|                             Copyright © 2011-15, TrendLaboratory |
//|            http://finance.groups.yahoo.com/group/TrendLaboratory |
//|                                   E-mail: igorad2003@yahoo.co.uk |
//|http://newdigital-world.com/forum.php                             |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2011-15, TrendLaboratory"
#property link      "http://finance.groups.yahoo.com/group/TrendLaboratory"

#include <stdlib.mqh>
#include <WinUser32.mqh>

//---- input parameters
extern string     Expert_Name          = "ManualTrader_v1.6 600+";

extern int        Magic                =     0;    // Magic Number
extern int        Slippage             =     3;

extern string     slInputs             = "===== StopLoss settings: =====";
extern double     RiskFactor           =     0;    // Risk Factor(in %) for StopLoss calculation  
extern double     StopLoss             =    50;    // StopLoss in pips 
extern int        HideStopLoss         =     0;    // Hidden StopLoss in pips 

extern string     tpInputs             = "===== TakeProfit settings: =====";   
extern double     TakeProfit           =   100;    // TakeProfit in pips 

extern string     trInputs             = "===== Trailing Stop & Breakeven settings: =====";  
extern int        TrailingMode         =     0;    // Trailing Stop Mode: 0-off,1-in pips,2-by Up/DownTrend Stop
extern double     TrailStop            =    15;    // Trailing Stop in pips
extern double     TrailStopStep        =    15;    // Trailing Stop Step in pips
extern double     BreakEven            =    50;    // Breakeven in pips  
extern double     PipsLockIn           =     5;    // Profit Lock in pips if Breakeven is achieved 

extern string     pcInputs             = "===== Partial Close settings: =====";
extern double     PartCloseTgt         =    50;    // Partial Close Target in pips
extern double     PartClosePct         =  50.0;    // Partial Close Position Percent

extern string     csInputs             = "===== ChandelierStop settings: =====";
extern int        csTimeFrame          =     0;    // TimeFrame in min
extern int        csUpPrice            =     2;    // Upper Price = 0...10 (see List of Prices)
extern int        csLoPrice            =     3;    // Lower Price = 0...10 (see List of Prices)
extern int        csLength             =    15;    // Bands Period
extern int        csATR_Length         =    14;    // ATR Period 
extern double     csMultiplier         =     4;    // ATR Multiplier 
extern double     csRatchet            =   0.0;    // Ratchet(-1-off,>= 0-on) 
extern double     csMoneyRisk          =  1.00;    // Offset Factor(eg.1.2)
extern int        csShift              =     1;    // 0-current bar,1-previous closed bar 
extern int        csMode               =     1;    // Exit Mode: 0-off

extern string     adInputs             = "===== Additional settings: =====";   
extern int        DebugMode            =     1;    // Switch of Debug mode (0-off;1-on) 
extern int        CommentMode          =     1;    // 0-Comment off,1-on 
extern int        ECN_Mode             =     1;    // 0-off,1-on(will modify Stoploss and TakeProfit) 
extern int        DrawTarget           =     1;    // 0-off,1-on

extern string     forTest              = "===== Settings for Testing: =====";
extern double     Lots                 =     1;    // Trade Volume 
extern int        MA_period            =     5;    // MA period
extern int        MA_mode              =     0;    // MA mode
//-----

int      TriesNum = 5;  
double   _point, lot_step, lot_min, minstop, dRatio, tick_val, tick_size;
double   Pct1, Tgt1, uptrend[2], dntrend[2];
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
{
//---- 
   dRatio    = MathPow(10,Digits%2);  
   lot_step  = MarketInfo(Symbol(),MODE_LOTSTEP); 
   lot_min   = MarketInfo(Symbol(),MODE_MINLOT);
   minstop   = MarketInfo(Symbol(),MODE_STOPLEVEL)/dRatio;
   _point    = MarketInfo(Symbol(),MODE_POINT)*dRatio;
   tick_val  = MarketInfo(Symbol(),MODE_TICKVALUE);//*dRatio;
   tick_size = MarketInfo(Symbol(),MODE_TICKSIZE);//*dRatio; 
//----
   Pct1 = 0.01*PartClosePct;
   Tgt1 = PartCloseTgt; 
   
   return(0);
}

// ---- Scan Trades

int ScanTrades(int& buy,int& sell,int& buylimit,int& selllimit,int& buystop,int& sellstop,double& buyavgopen,double& buysumlots,double& sellavgopen,double& sellsumlots)
{   
   buy = 0; sell = 0; buylimit = 0; selllimit = 0; buystop = 0; sellstop = 0;
   double buysumopen = 0, sellsumopen = 0; 
   buysumlots  = 0;
   sellsumlots = 0;  
   
   
   for(int cnt=0; cnt <OrdersTotal(); cnt++) 
   {        
   if(!OrderSelect(cnt, SELECT_BY_POS)) continue;            
   if(OrderSymbol() != Symbol() || OrderMagicNumber() != Magic) continue;  
      
      if(OrderType() == OP_BUY      ) {buy ++;      buysumopen  += OrderOpenPrice(); buysumlots  += OrderLots();} 
      if(OrderType() == OP_SELL     ) {sell++;      sellsumopen += OrderOpenPrice(); sellsumlots += OrderLots();}         
      if(OrderType() == OP_BUYLIMIT ) {buylimit++;  buysumopen  += OrderOpenPrice(); buysumlots  += OrderLots();}
      if(OrderType() == OP_SELLLIMIT) {selllimit++; sellsumopen += OrderOpenPrice(); sellsumlots += OrderLots();}
      if(OrderType() == OP_BUYSTOP  ) {buystop++;   buysumopen  += OrderOpenPrice(); buysumlots  += OrderLots();}
      if(OrderType() == OP_SELLSTOP ) {sellstop++;  sellsumopen += OrderOpenPrice(); sellsumlots += OrderLots();}        
      
   }
   
   if(buy  + buylimit  + buystop  > 0) buyavgopen  = buysumopen /(buy  + buylimit  + buystop );  
   if(sell + selllimit + sellstop > 0) sellavgopen = sellsumopen/(sell + selllimit + sellstop); 
   
   return(buy+sell+buylimit+selllimit+buystop+sellstop);
}  


double TotalProfit(int trade,int pmode,int hmode,datetime date)
{
   double Pips = 0, profit=0, totalPips = 0, totalProfits = 0, mPips = 0;   
      
      if(hmode == 0) 
      {
      int total = OrdersTotal(); 
      int opt =  MODE_TRADES;
      }
      else 
      {
      total = OrdersHistoryTotal();
      opt =  MODE_HISTORY;
      }
      
   for (int cnt=0;cnt<total;cnt++)
   { 
   if(!OrderSelect(cnt, SELECT_BY_POS, opt)) continue;   
   
   int mode=OrderType();
   bool mcondition = false, dcondition = false;
   
   if (OrderMagicNumber() == Magic && OrderSymbol() == Symbol()) mcondition = true;
   else if(Magic == 0 && OrderSymbol() == Symbol()) mcondition = true;   
   
   if(date > 0)
   { 
   if(date == StrToTime(TimeToStr(OrderCloseTime(),TIME_DATE))) dcondition = true;
   }
   else
   if(date == 0) dcondition = true;  
       
      if (mcondition && dcondition)
      {      
         if (mode == OP_BUY && (trade == 1 || trade == 0))
         {
         Pips = (OrderClosePrice() - OrderOpenPrice())/_point;
         profit = OrderProfit() + OrderSwap() + OrderCommission();
         totalPips += Pips;
         totalProfits += profit;
         }
         
         if (mode == OP_SELL && (trade == 2 || trade == 0))   
         {          
         Pips = (OrderOpenPrice() - OrderClosePrice())/_point;
         profit = OrderProfit() + OrderSwap() + OrderCommission();
         totalPips += Pips;
         totalProfits += profit;
         }
      }            
	}
   
   switch(pmode)
   {
   case  0: return(Pips); break;
   case  1: return(profit); break;
   case  2: return(totalPips); break;
   case  3: return(totalProfits); break;
   default: return(Pips); break;
   }
   
}

void ChartComment(int buy,int sell,int buylimit,int selllimit,int buystop,int sellstop)
{
   
   string sComment   = "";
   string sp         = "----------------------------------------\n";
   string NL         = "\n";
   double pips = TotalProfit(0,2,0,0);
   double usd  = TotalProfit(0,3,0,0);
   double hist = TotalProfit(0,3,1,StrToTime(TimeToStr(TimeCurrent(),TIME_DATE)));
   double sum  = hist + usd;     
       
      
   sComment = sp;
   sComment = sComment + "Expert Name : " + Expert_Name+NL;
   sComment = sComment + sp;
   sComment = sComment + "Time: Current= "+TimeToStr(TimeCurrent()) + NL;
   sComment = sComment + "Orders: Open= "+(buy + sell)+" Pending= "+(buylimit+selllimit+buystop+sellstop)+" All= "+(buy+sell+buylimit+selllimit+buystop+sellstop)+NL;
   sComment = sComment + "Current Profit(pips)= " + DoubleToStr(pips,1) + NL;
   sComment = sComment + "Current Profit(USD) = " + DoubleToStr(usd,2)  + NL;
   sComment = sComment + "Daily Profit(USD): Closed= " + DoubleToStr(hist,2) + " Open= " + DoubleToStr(usd,2) + " Summary = " + DoubleToStr(sum,2) + NL; 
   sComment = sComment + "Balance= "+DoubleToStr(AccountBalance(),2) + " Equity= "+DoubleToStr(AccountEquity(),2)+NL;
   sComment = sComment + sp;
   
   if(DebugMode > 0)
   {
   sComment = sComment+"uptrend[0] = " + DoubleToStr(uptrend[0],Digits) + " dntrend[0] = " + DoubleToStr(dntrend[0],Digits) + NL;
   }
   
   Comment(sComment);
}


void TrailStop()
{
   int    error;  
   bool   result=false;
   double Gain,BuyStop,SellStop;
   int    total = OrdersTotal(); 
   
   
   for (int cnt=0;cnt<total;cnt++)
   { 
   if(!OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES)) continue;   
   int mode = OrderType();    
      if (OrderSymbol() == Symbol() && OrderMagicNumber() == Magic) 
      {
         if (mode==OP_BUY) 
         {
			Gain = 0; BuyStop = 0;
			double _Bid = MarketInfo(Symbol(),MODE_BID);
			   
			   if (BreakEven > 0 && NormalizeDouble(OrderStopLoss()-OrderOpenPrice(),Digits) < NormalizeDouble(PipsLockIn*_point,Digits))// && buyBEvent < total )
			   {
			   Gain = NormalizeDouble((_Bid - OrderOpenPrice())/_point,Digits);
			   if(Gain >= BreakEven) BuyStop = NormalizeDouble(OrderOpenPrice()+PipsLockIn*_point,Digits);
			   }
			   else
			   if(TrailingMode > 0)
			   {
			      if(TrailingMode == 1 && TrailStop  > 0) BuyStop = NormalizeDouble(_Bid - TrailStop*_point,Digits);
			      if(TrailingMode == 2 && uptrend[0] > 0 && uptrend[0] != EMPTY_VALUE) BuyStop = NormalizeDouble(uptrend[0] - TrailStop*_point,Digits);
			   
			   if(BuyStop >= NormalizeDouble(OrderStopLoss() + TrailStopStep *_point,Digits)) BuyStop = BuyStop; else BuyStop = OrderStopLoss();
			   }			   			   
			   
			   if(BuyStop <= 0) continue; 
			   
			   
			   if (_Bid - BuyStop < minstop*_point) BuyStop = NormalizeDouble(_Bid - minstop*_point,Digits);   
              
			   if(NormalizeDouble(OrderOpenPrice(),Digits) <= BuyStop) 
            {   
			      if (NormalizeDouble(BuyStop,Digits) > NormalizeDouble(OrderStopLoss(),Digits) || OrderStopLoss() == 0) 
			      {
			      //Print("BS=",BuyStop);   
			         for(int k = 0 ; k < TriesNum; k++)
                  {
                  result = OrderModify(OrderTicket(),OrderOpenPrice(),
			                              NormalizeDouble(BuyStop,Digits),
			                              OrderTakeProfit(),0,Lime);
                  error=GetLastError();
                     if(error == 0 && result) break;
                     else
                     {
                     Sleep(5000); 
                     RefreshRates(); 
                     if(DebugMode > 0) Print("BUY Trail: OOP=",OrderOpenPrice()," BS=",BuyStop," bid=",Bid);
                     continue;
                     }
                  }   		 
               }            
            }
         }   
// - SELL Orders          
         if (mode==OP_SELL)
         {
         Gain = 0; SellStop = 0;
         double _Ask = MarketInfo(Symbol(),MODE_ASK);
            
            if (BreakEven > 0 && (NormalizeDouble(OrderOpenPrice()-OrderStopLoss(),Digits) < NormalizeDouble(PipsLockIn*_point,Digits) || OrderStopLoss()== 0))
			   {
			   Gain = NormalizeDouble((OrderOpenPrice()-_Ask)/_point,Digits);
			   if( Gain >= BreakEven )SellStop = NormalizeDouble(OrderOpenPrice()-PipsLockIn*_point,Digits);
			   }
			   else
			   if(TrailingMode > 0)
			   {
			      if(TrailingMode == 1 && TrailStop  > 0) SellStop = NormalizeDouble(_Ask + TrailStop*_point,Digits);   
			      if(TrailingMode == 2 && dntrend[0] > 0 && dntrend[0] != EMPTY_VALUE) SellStop = NormalizeDouble(dntrend[0] + TrailStop*_point,Digits);
			   
            if(SellStop <= NormalizeDouble(OrderStopLoss() - TrailStopStep *_point,Digits)) SellStop = SellStop; else SellStop = OrderStopLoss();
            }            
            
            if(SellStop <= 0) continue;
            
            
            if (SellStop - _Ask < minstop*_point) SellStop = NormalizeDouble(_Ask + minstop*_point,Digits);   
                        
            if(NormalizeDouble(OrderOpenPrice(),Digits) >= SellStop && SellStop > 0) 
            {
               if(NormalizeDouble(SellStop,Digits) < NormalizeDouble(OrderStopLoss(),Digits) || OrderStopLoss() == 0) 
               {
                  for( k = 0 ; k < TriesNum; k++)
                  {
                  result = OrderModify(OrderTicket(),OrderOpenPrice(),
			                              NormalizeDouble(SellStop,Digits),
			                              OrderTakeProfit(),0,Orange);
                  error=GetLastError();
                     if(error==0 && result) break;
                     else 
                     {
                     Sleep(5000); 
                     RefreshRates(); 
                     if(DebugMode > 0) Print("Sell Trail: OOP=",OrderOpenPrice()," SS=",SellStop," Ask =", Ask);
                     continue;
                     }
                  }
               }   
   			}	    
         }
      }
   }     
}

void ECN_Init(double buyavgentry,double buysumlots,double sellavgentry,double sellsumlots)
{
   int    error;  
   bool   result=false;
   double BuyStop = 0, SellStop = 0;
   double BuyProfit =0, SellProfit = 0;
    
   for(int cnt=0;cnt<OrdersTotal();cnt++)
   { 
   if(!OrderSelect(cnt, SELECT_BY_POS)) continue;   
   int mode = OrderType();    
      if(OrderSymbol() == Symbol() && OrderMagicNumber() == Magic && ((OrderStopLoss() == 0 && StopLoss > 0)||(OrderTakeProfit() == 0 && TakeProfit > 0))) 
      {
         if(mode==OP_BUY) 
         {
            if(OrderStopLoss() == 0 && (StopLoss > 0 || RiskFactor > 0)) 
		      {
               if(StopLoss >  0 && RiskFactor == 0) BuyStop = OrderOpenPrice() - StopLoss*_point; 
			      else
			      if(StopLoss >= 0 && RiskFactor >  0)
			      {
			      double buysl = 0.01*AccountBalance()*RiskFactor/buysumlots*tick_size/tick_val;
			      BuyStop = buyavgentry - buysl - StopLoss*_point;
			      }
			      
			   if(OrderOpenPrice() - BuyStop < minstop *_point) BuyStop = OrderOpenPrice() - minstop *_point;
			   }   
			   else BuyStop = OrderStopLoss();
			   			   
			   if(OrderTakeProfit() == 0 && TakeProfit > 0) 
		      {
		      BuyProfit = OrderOpenPrice() + TakeProfit*_point; 
			   
			   //if(OrderOpenPrice() - BuyStop < MinStopLoss*_point) BuyStop = OrderOpenPrice() - MinStopLoss*_point;
			   }  
			   else BuyProfit = OrderTakeProfit();
			    
			   if(DebugMode > 0) Print("BuyStop=",BuyStop," BuyProfit=",BuyProfit);
			   
			   for(int k=0;k<TriesNum;k++)
            {
            result = OrderModify(OrderTicket(),OrderOpenPrice(),
			                        NormalizeDouble(BuyStop,Digits),
			                        NormalizeDouble(BuyProfit,Digits),0,Lime);
            error = GetLastError();
               if(error == 0) break;
               else {Sleep(5000); RefreshRates(); continue;}
            }   		 
         }   
// - SELL Orders          
         if(mode == OP_SELL)
         {
            if(OrderStopLoss() == 0 && (StopLoss > 0 || RiskFactor > 0)) 
		      {
               if(StopLoss >  0 && RiskFactor == 0) SellStop = OrderOpenPrice() + StopLoss*_point; 
			      else
			      if(StopLoss >= 0 && RiskFactor >  0)
			      {
			      double sellsl = 0.01*AccountBalance()*RiskFactor/sellsumlots*tick_size/tick_val;
			      SellStop = sellavgentry + sellsl + StopLoss*_point;
			      }
			   
			   if(SellStop - OrderOpenPrice() < minstop *_point) SellStop = OrderOpenPrice() + minstop *_point;
			   }   
			   else SellStop = OrderStopLoss();
            
            if(OrderTakeProfit() == 0 && TakeProfit > 0) 
		      {
		      SellProfit = OrderOpenPrice() - TakeProfit*_point; 
			   
			   //if(OrderOpenPrice() - BuyStop < MinStopLoss*_point) BuyStop = OrderOpenPrice() - MinStopLoss*_point;
			   }  
			   else SellProfit = OrderTakeProfit();
                       
            if(DebugMode > 0) Print("SellStop=",SellStop," SellProfit=",SellProfit);
            
            for(k=0;k<TriesNum;k++)
            {
            result = OrderModify(OrderTicket(),OrderOpenPrice(),
			                        NormalizeDouble(SellStop,Digits),
			                        NormalizeDouble(SellProfit,Digits),0,Orange);
            error = GetLastError();
               if(error == 0) break;
               else {Sleep(5000); RefreshRates(); continue;}
            }	    
         }
      }
   }     
}   

void PartClose()   
{
   double Profit, pLots = 0;
   
   
   for(int cnt=0;cnt<OrdersTotal();cnt++)
   { 
   if(!OrderSelect(cnt, SELECT_BY_POS)) continue;   
   if(OrderSymbol() != Symbol() || OrderMagicNumber() != Magic) continue; 
      
      if (OrderType() == OP_BUY)
      {
      Profit = (MarketInfo(Symbol(),MODE_BID) - OrderOpenPrice())/_point;
                  
         if(Profit >= Tgt1 && Tgt1 > 0)
         {
            if(!CommentVerify())
            {
            Print("pc_BUY: profit=",Profit," tgt=",Tgt1," pct=",Pct1);
            pLots  = MathMin(OrderLots(),MathCeil(Pct1 * OrderLots()/lot_step)*lot_step); 
            if(pLots >= lot_min) CloseAtMarket(1,OrderTicket(),pLots,Aqua); 
            }
         }   
         
         if(DrawTarget > 0)
         {
            if(ObjFind(DoubleToStr(OrderTicket(),0),6) == 0 && Tgt1 > 0) 
            {
            PlotLine("Tgt 1 "+DoubleToStr(OrderTicket(),0)," #"+DoubleToStr(OrderTicket(),0)+" Tgt1",OrderOpenPrice()+Tgt1*_point,Red,2,7,"Tahoma",White);
            
            }
         }
      }         
      else  
      if(OrderType() == OP_SELL)
      { 
      Profit = (OrderOpenPrice() - MarketInfo(Symbol(),MODE_ASK))/_point;
         
                           
         if(Profit >= Tgt1 && Tgt1 > 0)
         {
            if(!CommentVerify())   
            {
            Print("pc_SELL: profit=",Profit," tgt=",Tgt1," pct=",Pct1);
            pLots  = MathMin(OrderLots(),MathCeil(Pct1 * OrderLots()/lot_step)*lot_step);
            if(pLots >= lot_min) CloseAtMarket(2,OrderTicket(),pLots,Pink); 
            }
         }   
         
         if(DrawTarget > 0 && ObjFind(DoubleToStr(OrderTicket(),0),6) == 0 && Tgt1 > 0) 
         {
         PlotLine("Tgt 1 "+DoubleToStr(OrderTicket(),0)," #"+DoubleToStr(OrderTicket(),0)+" Tgt1",OrderOpenPrice()-Tgt1*_point,Red,2,7,"Tahoma",White);
         }
      }     
   }
   
   //if(prevTicket > 0) ObjDel(DoubleToStr(prevTicket,0),6); 
}

bool CloseOrder(int mode)  
{
   bool result = false; 
   int  total  = OrdersTotal();
   
   for(int cnt=0;cnt<OrdersTotal();cnt++)  
   {
   if(!OrderSelect(cnt, SELECT_BY_POS)) continue;   
   if(OrderSymbol() != Symbol() || OrderMagicNumber() != Magic) continue; 
   
   if((mode == 0 || mode == 1) && OrderType() == OP_BUY ) result = CloseAtMarket(1,OrderTicket(),OrderLots(),Aqua);
   if((mode == 0 || mode == 2) && OrderType() == OP_SELL) result = CloseAtMarket(2,OrderTicket(),OrderLots(),Pink);
   }
   return(result);
}

bool CloseAtMarket(int mode,int ticket,double lot,color clr) 
{
   bool   result = false; 
   double price; 
         
   int tries = 0;
   while (!result && tries < TriesNum) 
   {
   RefreshRates();
      
   if(mode == 1) price = NormalizeDouble(MarketInfo(OrderSymbol(),MODE_BID),Digits);
   if(mode == 2) price = NormalizeDouble(MarketInfo(OrderSymbol(),MODE_ASK),Digits);
      
   result = OrderClose(ticket,lot,price,dRatio*Slippage,clr);
      
      if (!result) 
      {
      Print("Error closing order : ",ErrorDescription(GetLastError())," ticket=",ticket," lot=",lot," Price=",price);
      Sleep(5000);
      }
      
   tries++;
   }
         
   return(result);
}

void PlotLine(string name,string text,double value,color line_color,int style,int size,string font,color clr)
{
   if(value > 0)
   {
   ObjectDelete(name);
   ObjectCreate(name,OBJ_HLINE,0,0,value,0,0);
   ObjectSet(name, OBJPROP_WIDTH, 1);
   ObjectSet(name, OBJPROP_STYLE, style);
   ObjectSet(name, OBJPROP_COLOR, line_color);
   ObjectSetText(name,text,size,font,clr);
   }
}         

bool ObjDel(string name,int start)
{
   int _GetLastError = 0;
   int total = ObjectsTotal();  
      
   for (int i=0;i<total;i++)
   {
      if(StringFind(ObjectName(i),name,start) == start)
      {
         if(!ObjectDelete(ObjectName(i)))
         {
         _GetLastError = GetLastError();
         Print( "ObjectDelete( \"",ObjectName(i),"\" ) - Error #", _GetLastError );
         }
         else {i--; total--;}
      }
   }

   if(_GetLastError > 0) return(false);
   else
   return (true);
}
//-----
int ObjFind(string name,int start)
{
   int cnt = 0;
   
   for(int i=0;i<ObjectsTotal();i++)
      if(StringFind(ObjectName(i),name,start) == start && StringFind(ObjectName(i),"#",0) != 0) cnt+=1;
       
   return(cnt);
}         

bool CommentVerify()
{ 
   bool result = false;
  
   result = StringSubstr(OrderComment(),0,6) == "from #";
   
   return(result);  
}


void CloseAtProfit(double target)   
{
   double Profit;
    
   for (int cnt=0;cnt<OrdersTotal();cnt++)
   { 
   if(!OrderSelect(cnt, SELECT_BY_POS)) continue;   
   if(OrderSymbol() != Symbol() || OrderMagicNumber() != Magic) continue; 
      
      if (OrderType() == OP_BUY)
      {
      Profit = (MarketInfo(Symbol(),MODE_BID) - OrderOpenPrice())/_point;
      if((target < 0 && Profit <= target)||(target > 0 && Profit >= target)) CloseAtMarket(1,OrderTicket(),OrderLots(),Aqua); 
      }         
      else  
      if (OrderType() == OP_SELL)
      { 
      Profit = (OrderOpenPrice() - MarketInfo(Symbol(),MODE_ASK))/_point;
      if((target < 0 && Profit <= target)||(target > 0 && Profit >= target)) CloseAtMarket(2,OrderTicket(),OrderLots(),Pink); 
      }     
   }
}

int chandelierStop(int mode,int tf,int upp,int lop,int len,int atrlen,double mult,double ratchet,double mrisk,int bar)
{   
   string indName = "ChandelierStop_v3 600+";
   
   uptrend[0] = iCustom(NULL,tf,indName,0,upp,lop,len,atrlen,mult,ratchet,mrisk,0,0,1,"",0,0,0,0,"","",0,0,0,bar);    
   dntrend[0] = iCustom(NULL,tf,indName,0,upp,lop,len,atrlen,mult,ratchet,mrisk,0,0,1,"",0,0,0,0,"","",0,0,1,bar); 
   
   uptrend[1] = iCustom(NULL,tf,indName,0,upp,lop,len,atrlen,mult,ratchet,mrisk,0,0,1,"",0,0,0,0,"","",0,0,0,bar+1);    
   dntrend[1] = iCustom(NULL,tf,indName,0,upp,lop,len,atrlen,mult,ratchet,mrisk,0,0,1,"",0,0,0,0,"","",0,0,1,bar+1); 
   
         
      switch(mode)
      {
      case 1: if(uptrend[0] > 0 && uptrend[0] != EMPTY_VALUE && uptrend[1] == EMPTY_VALUE) return( mode); 
              if(dntrend[0] > 0 && dntrend[0] != EMPTY_VALUE && dntrend[1] == EMPTY_VALUE) return(-mode);  
              break; 
      }
 
   return(0);  
}

//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//---- 
   ObjDel("Tgt",0);
   Comment("");
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
   if(!IsTradeAllowed() || IsTradeContextBusy()) return(0); 
   int result, trades, buy, sell, buylimit, selllimit, buystop, sellstop;
   double avgbuyEntry, sumbuyLots, avgsellEntry, sumsellLots;   
   
   trades  = ScanTrades(buy,sell,buylimit,selllimit,buystop,sellstop,avgbuyEntry,sumbuyLots,avgsellEntry,sumsellLots);             
   
   if(CommentMode > 0) ChartComment(buy,sell,buylimit,selllimit,buystop,sellstop);
   
   if(csMode > 0) int trend = chandelierStop(csMode,csTimeFrame,csUpPrice,csLoPrice,csLength,csATR_Length,csMultiplier,csRatchet,csMoneyRisk,csShift);   
   
   if(trades == 0) 
   {
   ObjDel("Tgt",0);
       
      if(IsTesting())
      {
         if(csMode == 0)
         {
         double ma0 = iMA(Symbol(),0,MA_period,0,MA_mode,PRICE_CLOSE,1);
         double ma1 = iMA(Symbol(),0,MA_period,0,MA_mode,PRICE_CLOSE,2);
         double ma2 = iMA(Symbol(),0,MA_period,0,MA_mode,PRICE_CLOSE,3);
         
         if(ma0 > ma1 && ma1 < ma2) result = OrderSend(Symbol(),OP_BUY ,Lots,NormalizeDouble(Ask,Digits),0,0,0,NULL,0,0,DeepSkyBlue);
         if(ma0 < ma1 && ma1 > ma2) result = OrderSend(Symbol(),OP_SELL,Lots,NormalizeDouble(Bid,Digits),0,0,0,NULL,0,0,OrangeRed);
         }
         else
         {
         if(trend > 0) result = OrderSend(Symbol(),OP_BUY ,Lots,NormalizeDouble(Ask,Digits),0,0,0,NULL,0,0,DeepSkyBlue);
         if(trend < 0) result = OrderSend(Symbol(),OP_SELL,Lots,NormalizeDouble(Bid,Digits),0,0,0,NULL,0,0,OrangeRed);
         } 
      }
   return(0);
   }
   else   
   {   
   if(ECN_Mode > 0 && (StopLoss > 0 || TakeProfit > 0)) ECN_Init(avgbuyEntry, sumbuyLots, avgsellEntry, sumsellLots);                                 
   
   if(HideStopLoss > 0) CloseAtProfit(-HideStopLoss); 
        
   if(TrailingMode > 0 || BreakEven > 0) TrailStop();
   if(PartClosePct > 0) PartClose(); 
   
      if(csMode > 0)
      {
         if(csMode == 1)
         {
         if(trend > 0) CloseOrder(2);
         if(trend < 0) CloseOrder(1); 
         }
      }
   }

//----
   return(0);
} 




