#include <OrderReliable_v0_2_5.mqh>

extern bool      UseOrdersReliable  = true;
extern int degree = 3;
extern double kstd = 2.0;
extern int bars = 250;
extern int shift = 0;
extern int iRegrTF=60;
extern int     OutSideBars = 3;
extern double  MaxSlopeRange = 2.5;
extern int     SlopeBars = 3;
//extern int     DistanceFromZeroLine = 0;
extern int    DeepSlopeAllowed = 1;
extern int   Directional_Trading         = 1;

extern int    INCREMENT        = 35;
extern double LOTS             = 0.1;
extern int    LEVELS           = 3; 
extern double MAX_LOTS         = 99;
extern int    MAGIC            = 1813;
extern bool   CONTINUE         = true;
extern bool   MONEY_MANAGEMENT = false;
extern int    RISK_RATIO       = 2;
extern bool   USE_ENTRY_TIME   = false;
extern int    ENTRY_TIME_A     = 0;
extern int    ENTRY_TIME_B     = 0;
extern bool   USE_EXIT_TIME    = false;
extern int    EXIT_TIME        = 0;
extern double ENTRY_PRICE      = 0;
extern int    SLIPPAGE         = 5;
int    MULTIPLIER;
extern double EPSILON          = 5;
extern int    MONEY_PROFIT     = 0;
//-------------------------------------------------------------------------------------------------
bool _useProfitTarget=false;
bool _usePartialProfitTarget=false;
int  _targetIncrement = 50;
int  _firstTarget = 20;
bool _enter = true;
int  _nextTP;
bool _isFirstTime = true;

string trend="no Trade",slopetrend,znote;
//int sR;
int mtp,DistancePrice;
double sR;
double a,b,p,BuyPrice,SellPrice,LinePrice,ppoint;
double TL1,TL2,MIDL;
double slopeRange,MaxSR;
int nINCREMENT,wwidth;
string LineStep="start";
double prc0;
double nTop, nBot,nTime,cekP2;
double nnTop,nnBot;
double lp1,lp2,xlp1,xlp2;
datetime ld1,ld2,xld1,xld2;
bool xx;
double spread;
//----------------------------------------
//----------------------------------------
void xtrend()
{  
bool xx;
if ( (USE_ENTRY_TIME && Hour() < ENTRY_TIME_A ) || (USE_EXIT_TIME && Hour() > EXIT_TIME) )
xx=false;
else
xx=true;

int xa,xb;

   double prc1=Close[1];  double prc0=Close[0];
   double top=iCustom(NULL,iRegrTF,"i-Regr",degree, kstd, bars, shift,1,1);
   double bot=iCustom(NULL,iRegrTF,"i-Regr",degree, kstd, bars, shift,2,1);
   double top0=iCustom(NULL,0,"i-Regr",degree, kstd, bars, shift,1,0);
   double bot0=iCustom(NULL,0,"i-Regr",degree, kstd, bars, shift,2,0);        
        
   double top2=iCustom(NULL,iRegrTF,"i-Regr",degree, kstd, bars, shift,1,SlopeBars+1);
   double bot2=iCustom(NULL,iRegrTF,"i-Regr",degree, kstd, bars, shift,2,SlopeBars+1);

   double z1=iCustom(NULL,iRegrTF,"i-Regr",degree, kstd, bars, shift,0,1);
   double z2=iCustom(NULL,iRegrTF,"i-Regr",degree, kstd, bars, shift,0,SlopeBars+1);
TL1=top; TL2=bot; MIDL=z1;
if(Directional_Trading==1)
{
if(z1>z2)   
   {  slopetrend="up"; sR=MathFloor((z1-z2)/Point); 
      slopeRange=NormalizeDouble(sR/SlopeBars,2); 
      znote="("+DoubleToStr(z1,Digits)+" - "+DoubleToStr(z2,Digits)+")   "+DoubleToStr(sR,0)+
            " / "+SlopeBars+" = "+DoubleToStr(slopeRange,2);
   }
if(z1<z2)   
   {  slopetrend="dn"; sR=MathFloor((z2-z1)/Point); 
      slopeRange=NormalizeDouble(sR/SlopeBars,2); 
      znote="("+DoubleToStr(z2,Digits)+" - "+DoubleToStr(z1,Digits)+")   "+DoubleToStr(sR,0)+
            " / "+SlopeBars+" = "+DoubleToStr(slopeRange,2);
   }
}
else
   slopetrend="Not Use";


for(int a=1; a<=OutSideBars; a++)
   {  if(Close[a]>top) xa++;
      else continue; }
      
for(int b=1; b<=OutSideBars; b++)
   {  if(Close[b]<bot) xb++;
      else continue; }

bool CloseOnTop=xa>=OutSideBars;
bool CloseOnBot=xb>=OutSideBars;

if( (CloseOnTop && prc0<=top0) || (CloseOnBot && prc0>=bot0) )   trend="go";
   else trend="no Trade";    
   
   
if(xx) {

if(Directional_Trading==1)
{
if(slopeRange<=MaxSR)
   {  if(slopetrend=="up" && (CloseOnBot && prc0>=bot0)) 
         {  trend="go";
            if(jmlStopBuy()==0 && BuyPrice==0 )
               BuyPrice    = bot;//bot+(DistancePrice*Point);
            if(jmlStopSell()==0 && SellPrice==0)
               SellPrice   = bot;//bot-(DistancePrice*Point); 
               if(LinePrice==0) LinePrice=bot; 
         }
      else
      if(slopetrend=="dn" && (CloseOnTop && prc0<=top0))
         {  trend="go";
            if(jmlStopBuy()==0 && BuyPrice==0 )
               BuyPrice    = top;//top+(DistancePrice*Point);
            if(jmlStopSell()==0 && SellPrice==0)
               SellPrice   = top;//top-(DistancePrice*Point);
               if(LinePrice==0) LinePrice=top;
         }
      else
        trend="No Trade";          
   }      
else   
//-----------------   
if(slopeRange>MaxSR)
   {  if(DeepSlopeAllowed == 1)
         {  if(CloseOnBot && prc0>=bot0)
               {  trend="go";
                  if(jmlStopBuy()==0 && BuyPrice==0 )
                  BuyPrice    = bot;//bot+(DistancePrice*Point);
                  if(jmlStopSell()==0 && SellPrice==0)
                  SellPrice   = bot;//bot-(DistancePrice*Point); 
                  if(LinePrice==0) LinePrice=bot;  
               }
      
            if(CloseOnTop && prc0<=top0)
               {  trend="go";
                  if(jmlStopBuy()==0 && BuyPrice==0 )
                  BuyPrice    = top;//top+(DistancePrice*Point);
                  if(jmlStopSell()==0 && SellPrice==0)
                  SellPrice   = top;//top-(DistancePrice*Point); 
                  if(LinePrice==0) LinePrice=top; 
               }
         }
      else
        trend="No Trade";          
   }                  
}

if(Directional_Trading==0)
{  trend="No Trade";          
   if(CloseOnBot && prc0>=bot0)
      {  trend="go";
         if(jmlStopBuy()==0 && BuyPrice==0 )
         BuyPrice    = bot;//bot+(DistancePrice*Point);
         if(jmlStopSell()==0 && SellPrice==0)
            SellPrice   = bot;//bot-(DistancePrice*Point); 
         if(LinePrice==0) LinePrice=bot;  
       }
      
    if(CloseOnTop && prc0<=top0)
       {  trend="go";
          if(jmlStopBuy()==0 && BuyPrice==0 )
            BuyPrice    = top;//top+(DistancePrice*Point);
          if(jmlStopSell()==0 && SellPrice==0)
             SellPrice   = top;//top-(DistancePrice*Point); 
          if(LinePrice==0) LinePrice=top; 
       }
       
}
}
else
trend="Not in Trading Hour"; 
     
}
//-------------------------------------------------------------------------------------------------
int init()
{  if(Digits==2 || Digits == 4) { mtp=1; ppoint=Point; }
      if(Digits==3 || Digits == 5) { mtp=10; ppoint=Point*10; }
      MaxSR=MaxSlopeRange*mtp;
     // DistancePrice=DistanceFromZeroLine*mtp;
      
	double minLot = MarketInfo( Symbol(), MODE_MINLOT );
	double stopLevel = MarketInfo( Symbol(), MODE_STOPLEVEL );
	spread = MarketInfo( Symbol(), MODE_SPREAD );

	nINCREMENT = MathMax( INCREMENT * mtp, mtp + stopLevel + spread );
	SLIPPAGE *= mtp;
	EPSILON *= mtp;
	if ( MONEY_MANAGEMENT )
		LOTS = NormalizeDouble( AccountBalance() * AccountLeverage() / 1000000 * RISK_RATIO, 0 ) * minLot;

	_targetIncrement *= mtp;
	_firstTarget *= mtp;
	_nextTP = _firstTarget;
	
	return (0);
}
//-------------------------------------------------------------------------------------------------
int deinit()
{
	return (0);
}
//-------------------------------------------------------------------------------------------------
int start()
{

xtrend();
   int i, pipsLot, total, ticket, profit, buyGoalProfit, sellGoalProfit;
	double profitTarget = INCREMENT * 2, buyGoal, sellGoal,  initialPrice, additionalVolume;

	if(nINCREMENT<MarketInfo(Symbol(),MODE_STOPLEVEL)+spread)
		nINCREMENT =mtp+MarketInfo(Symbol(),MODE_STOPLEVEL )+spread;
	
	if ( MONEY_MANAGEMENT )
		LOTS = NormalizeDouble( AccountBalance() * AccountLeverage() / 1000000 * RISK_RATIO, 0 ) * MarketInfo( Symbol(), MODE_MINLOT );
	
	if ( LOTS < MarketInfo( Symbol(), MODE_MINLOT ) )
	  {  Print( "Not Enough Free Margin to begin" );  return (0); }

	for ( i = 1; i < LEVELS; i++ )  pipsLot += i * nINCREMENT;
	
	double totalProfit = 0;
	for ( i = 0; i < OrdersTotal(); i++ )
	  {  OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
		  if ( OrderMagicNumber() == MAGIC && OrderSymbol() == Symbol() )
		    {  total++;
			    totalProfit += OrderProfit();
			   if ( initialPrice == 0 )   initialPrice = StrToDouble( OrderComment() );
			   if ( _usePartialProfitTarget && _useProfitTarget && OrderType() < 2 )
			      {  double val = GetPipValue( OrderOpenPrice(), OrderType() );
				      TakeProfit( val, OrderTicket() );
			      }
		    }
	  }

	// close all open and pending positions when sertain profit is reached and start again	
	if ( MONEY_PROFIT > 0 && totalProfit >= MONEY_PROFIT )
	  {  Print( "$", MONEY_PROFIT, " profit reached. Closing all orders." );
		  EndSession(); return (0); 
		}
	
	if ( total < 1 && _enter )
	  {  if ( AccountFreeMargin() < ( 100 * LOTS ) )
		    {  Print( "Not enough free margin to begin" );
			    return (0);
		    }
	if ( (!USE_ENTRY_TIME || (USE_ENTRY_TIME && (Hour() == ENTRY_TIME_A || Hour() == ENTRY_TIME_B)))
			&& (!USE_EXIT_TIME || (USE_EXIT_TIME && Hour() < EXIT_TIME)) )
		{
			// if ENTRY_PRICE is defined and it's not the current one, then wait till ENTRY_PRICE is reached
			if ( _isFirstTime && ENTRY_PRICE > 0 && MathAbs(ENTRY_PRICE - Ask) > EPSILON * Point )
				return (0);
	
			// - Open Check - Start Cycle
			if ( _isFirstTime )  initialPrice = ENTRY_PRICE;
			if ( initialPrice == 0 )   initialPrice = Ask;
		
			//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
			if(trend=="go")
			   {  sellGoal = initialPrice - (LEVELS + 1) * nINCREMENT * Point;
			      buyGoal = initialPrice + (LEVELS + 1) * nINCREMENT * Point;
			      
			      if(jmlStopBuy()==0)
			      
			         if( UseOrdersReliable  ) {
                     OrderSendReliable(Symbol(), OP_BUYSTOP, LOTS, initialPrice + 1 * nINCREMENT * Point, SLIPPAGE, sellGoal, buyGoal, DoubleToStr( initialPrice, Digits ). MAGIC, 0 );
                  else
                           
				      OrderSend(  Symbol(),   OP_BUYSTOP, LOTS,
					     initialPrice + 1 * nINCREMENT * Point,
					     SLIPPAGE,   sellGoal,   buyGoal,
					     DoubleToStr( initialPrice, Digits ), MAGIC, 0 );
					
					Print(   "BuyPrice = ",DoubleToStr(initialPrice + 1 * nINCREMENT * Point,Digits),
                           "sellGoal = ",DoubleToStr(sellGoal,Digits),
                           "buyGoal = ",DoubleToStr(buyGoal,Digits),
                           "initialPrice = ",DoubleToStr(initialPrice,Digits)
                       );    
					
					     
	            if(jmlStopSell()==0)
	            
	            if( UseOrdersReliable  ) {
                     OrderSendReliable(Symbol(), OP_SELLSTOP, LOTS, initialPrice - 1 * nINCREMENT * Point, SLIPPAGE, buyGoal + spread * Point, sellGoal + spread * Point, DoubleToStr( initialPrice, Digits ). MAGIC, 0 );
                     _isFirstTime = false
                  else
                  
				     OrderSend(  Symbol(),   OP_SELLSTOP,   LOTS, 
					     initialPrice - 1 * nINCREMENT * Point,
					     SLIPPAGE,   buyGoal + spread * Point,
					     sellGoal + spread * Point,
					     DoubleToStr( initialPrice, Digits ), MAGIC, 0 );
			           _isFirstTime = false;
			      // initial order done - all channels are set up
		       }
		    
		    if(jmlStopBuy()>0 && jmlStopSell()>0)
			   {  for ( i = 1; i < LEVELS; i++ )
			   
			         if( UseOrdersReliable  ) {
                     OrderSendReliable(Symbol(), OP_BUYSTOP, LOTS, initialPrice + (i+1) * nINCREMENT * Point, SLIPPAGE, sellGoal, buyGoal, DoubleToStr( initialPrice, Digits ). MAGIC, 0 );
                  else   
			         {   OrderSend(  Symbol(),   OP_BUYSTOP, LOTS,
					          initialPrice + (i+1) * nINCREMENT * Point,
					          SLIPPAGE,   sellGoal,   buyGoal,
					          DoubleToStr( initialPrice, Digits ), MAGIC, 0 );
					          
					   if( UseOrdersReliable  ) {
                     OrderSendReliable(Symbol(), OP_SELLSTOP, LOTS, initialPrice - (i+1) * nINCREMENT * Point, SLIPPAGE, buyGoal + spread * Point, sellGoal + spread * Point, DoubleToStr( initialPrice, Digits ). MAGIC, 0 );
                     
                  else
					       OrderSend(  Symbol(),   OP_SELLSTOP,   LOTS, 
					          initialPrice - (i+1) * nINCREMENT * Point,
					          SLIPPAGE,   buyGoal + spread * Point,
					          sellGoal + spread * Point,
					          DoubleToStr( initialPrice, Digits ), MAGIC, 0 );  
		            }  
		                   _isFirstTime = false;
			      // initial setup done - all channels are set up
			   } 
	     } 
 }
	else 
	{
		// We have open Orders
		total = OrdersHistoryTotal();
		for ( i = 0; i < total; i++ )
		{
			OrderSelect( i, SELECT_BY_POS, MODE_HISTORY );
			if( OrderSymbol() == Symbol() && OrderMagicNumber() == MAGIC && StrToDouble(OrderComment()) == initialPrice)
			{
				EndSession();
				return (0);
			}
		}
		
		if ( _useProfitTarget && CheckProfits( LOTS, OP_SELL, true, initialPrice ) > profitTarget )
		{
			EndSession();
			return(0);
		}

		buyGoal = initialPrice + nINCREMENT * (LEVELS + 1) * Point;
		sellGoal = initialPrice - nINCREMENT * (LEVELS + 1) * Point;
		buyGoalProfit = CheckProfits( LOTS, OP_BUY, false, initialPrice );
		sellGoalProfit = CheckProfits( LOTS, OP_SELL, false, initialPrice );
		
		// - nINCREMENT Lots Buy
		if ( buyGoalProfit < profitTarget )
		{
			for( i = 1; i <= LEVELS && buyGoalProfit < profitTarget; i++ )
			{
				if ( Ask <= (initialPrice + (i * nINCREMENT - MarketInfo( Symbol(), MODE_STOPLEVEL)) * Point) )
				{
				
				  if( UseOrdersReliable ) {
				   additionalVolume = CollapseOrders( initialPrice + i * nINCREMENT * Point, sellGoal, buyGoal );
               ticket =
               OrderSendReliable(Symbol(),OP_BUYSTOP,1 * LOTS + additionalVolume, initialPrice + i * nINCREMENT * Point, SLIPPAGE, sellGoal, buyGoal, DoubleToStr( initialPrice, Digits ), MAGIC, 0 ); 
               }
              else {
               
					additionalVolume = CollapseOrders( initialPrice + i * nINCREMENT * Point, sellGoal, buyGoal );
					ticket = OrderSend(
						Symbol(),
						OP_BUYSTOP,
						i * LOTS + additionalVolume,
						initialPrice + i * nINCREMENT * Point,
						SLIPPAGE,
						sellGoal,
						buyGoal,
						DoubleToStr( initialPrice, Digits ),
						MAGIC, 0 );
				}
				if ( ticket > 0 )
					buyGoalProfit += LOTS * (buyGoal - initialPrice - i * nINCREMENT * Point) / Point;
			}
		}

		// - nINCREMENT Lots Sell		
		if ( sellGoalProfit < profitTarget )
		{
			for ( i = 1; i <= LEVELS && sellGoalProfit < profitTarget; i++ )
			{
				if ( Bid >= (initialPrice - (i * nINCREMENT - MarketInfo( Symbol(), MODE_STOPLEVEL )) * Point) )
				{
				
				if( UseOrdersReliable ) {
				   additionalVolume = CollapseOrders( initialPrice - i * nINCREMENT * Point, buyGoal + spread * Point, sellGoal + spread * Point );
               ticket =
               OrderSendReliable(Symbol(),OP_SELLSTOP,1*LOTS + additionalVolume, initialPrice - i * nINCREMENT * Point, SLIPPAGE, buyGoal + spread * Point, sellGoal + spread * Point, DoubleToStr( initialPrice, Digits ), MAGIC, 0 ); 
               }
              else {
              
					additionalVolume = CollapseOrders( initialPrice - i * nINCREMENT * Point, buyGoal + spread * Point, sellGoal + spread * Point );
					ticket = OrderSend(
						Symbol(),
						OP_SELLSTOP,
						i * LOTS + additionalVolume,
						initialPrice - i * nINCREMENT * Point,
						SLIPPAGE,
						buyGoal + spread * Point,
						sellGoal + spread * Point,
						DoubleToStr( initialPrice, Digits ),
						MAGIC, 0 );
				}
				if ( ticket > 0 )
					sellGoalProfit += LOTS * (initialPrice - i * nINCREMENT * Point - sellGoal - spread * Point) / Point;
			}
		}
	}
	
	
string hh= ENTRY_TIME_A+"  -  "+ Hour() +"   -  "+ EXIT_TIME;
string pTF;
if(iRegrTF==0) pTF="Chart TF";
if(iRegrTF==1) pTF=" 1 min";
if(iRegrTF==5) pTF=" 5 min";
if(iRegrTF==15) pTF="15 min";
if(iRegrTF==30) pTF="30 min";
if(iRegrTF==60) pTF="H1";
if(iRegrTF==240) pTF="H4";
if(iRegrTF==1440) pTF="Daily";
if(iRegrTF==10080) pTF="Weekly";
if(iRegrTF==43200) pTF="Monthly";


		Comment(
		"\n  ",WindowExpertName(),
		"\nFX Acc Server: ",      AccountServer(),
		"\nDate: ",               Month(), "-", Day(), "-", Year(), " Server Time: ", Hour(), ":", Minute(), ":", Seconds(),
		"\n",
		"\nMinimum Lot Sizing: ", MarketInfo( Symbol(), MODE_MINLOT ),
		"\nAccount Balance: $",   AccountBalance(),
		"\nSymbol: ",             Symbol(),
		"\nPrice: ",              NormalizeDouble( Bid, 4 ),
		"\nPip Spread: ",         MarketInfo( Symbol(), MODE_SPREAD ),
		"\n",
		"\nIncrement: ",          INCREMENT,
		"\nLots: ",               LOTS,
		"\nLevels: ",             LEVELS,
		"\n",
		"\nOutSide Bars: ",        OutSideBars,
		"\nDirectional_Trading : ",   Directional_Trading,
		"\ni-Regr TF : ",             pTF,
		"\nDeep Slope Allowed : ",   DeepSlopeAllowed,
		"\nSlope Bars : ",        SlopeBars,
		//"\nDistance From Zero Line : ",  DistanceFromZeroLine,
		"\nMax Slope Range : ",    DoubleToStr(MaxSR,2),
		"   Actual Slope Range : ",    DoubleToStr(slopeRange,2),
		"\nSlope Trend : ",        slopetrend,
		"\nTrend Condition : ",        trend
		
		 );
         
	
	return(0);
}
//-------------------------------------------------------------------------------------------------
// Removes all pending orders that have price, stoploss & takeprofit equal to given values.
// Returns total volume of removed orders.
double CollapseOrders( double price, double stopLoss, double takeProfit )
{
	int count = OrdersTotal();
	double totalVolume = 0;
	for ( int i = 0; i < count; i++ )
	{
		OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
		if ( OrderSymbol() == Symbol() 
			&& OrderMagicNumber() == MAGIC 
			&& OrderType() > 1
			&& MathAbs( OrderOpenPrice() - price ) < 0.0001
			&& MathAbs( OrderStopLoss() - stopLoss  ) < 0.0001
			&& MathAbs( OrderTakeProfit() - takeProfit ) < 0.0001 )
		{
			totalVolume += OrderLots();
			OrderDelete( OrderTicket() );
		}
	}
	return (totalVolume);
}
//-------------------------------------------------------------------------------------------------
int CheckProfits( double lots, int goal, bool current, double initialPrice )
{
	int i, profit;
	if ( current )
	{
		//return current profit
		for ( i = 0; i < OrdersTotal(); i++ )
		{
			OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
			if ( OrderSymbol() == Symbol() && StrToDouble(OrderComment()) == initialPrice )
			{
				if ( OrderType() == OP_BUY )
					profit += (Bid - OrderOpenPrice()) / Point * OrderLots() / lots;
				if ( OrderType() == OP_SELL) 
					profit += (OrderOpenPrice() - Ask) / Point * OrderLots() / lots;
			}
		}
		return (profit);
	}
	else
	{
		if ( goal == OP_BUY )
		{
			for( i = 0; i < OrdersTotal(); i++ )
			{
				OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
				if ( OrderSymbol() == Symbol() && StrToDouble(OrderComment()) == initialPrice )
				{
					if ( OrderType() == OP_BUY )
						profit += (OrderTakeProfit() - OrderOpenPrice()) / Point * OrderLots() / lots;
					if ( OrderType() == OP_SELL ) 
						profit -= (OrderStopLoss() - OrderOpenPrice()) / Point * OrderLots() / lots;
					if ( OrderType() == OP_BUYSTOP ) 
						profit += (OrderTakeProfit() - OrderOpenPrice()) / Point * OrderLots() / lots;
				}
			}
			return (profit);
		}
		else
		{
			for ( i = 0; i < OrdersTotal(); i++ )
			{
				OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
				if ( OrderSymbol() == Symbol() && StrToDouble(OrderComment()) == initialPrice )
				{
					if ( OrderType() == OP_BUY )
						profit -= (OrderOpenPrice() - OrderStopLoss()) / Point * OrderLots() / lots;
					if( OrderType() == OP_SELL )
						profit += (OrderOpenPrice() - OrderTakeProfit()) / Point * OrderLots() / lots;
					if ( OrderType() == OP_SELLSTOP )
						profit += (OrderOpenPrice() - OrderTakeProfit()) / Point * OrderLots() / lots;              
				}
			}
			return (profit);
		}
	}
}
//-------------------------------------------------------------------------------------------------
bool EndSession()
{
	int total = OrdersTotal();
	for ( int i = 0; i < total; i++ )
	{
		Sleep( 3000 );
		OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
		if ( OrderSymbol() == Symbol() && OrderType() > 1 )
         OrderDelete( OrderTicket() );
      
		else if ( OrderSymbol() == Symbol() && OrderType() == OP_BUY )
		
		 if(UseOrdersReliable) OrderCloseReliable(OrderTicket(),OrderLots(),Bid, SLIPPAGE);
         else OrderClose( OrderTicket(), OrderLots(), Bid, SLIPPAGE );
                
			
		else if ( OrderSymbol() == Symbol() && OrderType() == OP_SELL )
		
		 if(UseOrdersReliable) OrderCloseReliable(OrderTicket(),OrderLots(),Ask, SLIPPAGE);
         else OrderClose( OrderTicket(), OrderLots(), Ask, SLIPPAGE );
      
	}
	
	if ( !CONTINUE )
		_enter = false;
		if(jmlOrder()==0) { BuyPrice=0;  SellPrice=0; }
		
	return (true);
}
//-------------------------------------------------------------------------------------------------
double GetPipValue( double ord, int dir )
{
	double val;
	RefreshRates();
	if ( dir == 1)
		val = (NormalizeDouble( ord, Digits ) - NormalizeDouble( Ask, Digits ));
	else
		val = (NormalizeDouble( Bid, Digits ) - NormalizeDouble( ord, Digits ));
	val = val / Point;
	return (val);   
}
//-------------------------------------------------------------------------------------------------
void TakeProfit( int currentPips, int ticket )
{
	if ( OrderSelect( ticket, SELECT_BY_TICKET ) )
	{
		if ( currentPips >= _nextTP && currentPips < (_nextTP + _targetIncrement) )
		{
			if ( OrderType() == 1 )
			{
			
			   if(UseOrdersReliable) OrderCloseReliable(ticket, MAX_LOTS, Ask, 3 ) ) 
			      _next TP +=  _targetIncrement;
            else
                  //Print( "Error closing order : ", GetLastError() );
               
				( OrderClose( ticket, MAX_LOTS, Ask, 3 ) )
					_nextTP += _targetIncrement;
				          //else
					      //Print( "Error closing order : ", GetLastError() ); 
			} 
			else
			{
			
			   if(UseOrdersReliable) OrderCloseReliable(ticket, MAX_LOTS, Bid, 3 ) ) 
			      _next TP +=  _targetIncrement;
               else
                     //Print( "Error closing order : ", GetLastError() );
              
				( OrderClose( ticket, MAX_LOTS, Bid, 3 ) )
					_nextTP += _targetIncrement;
				        //else
					    //Print( "Error closing order : ",GetLastError() );
			}        
		}
	}
}
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv 
int jmlStopBuy()
 { int gantung;
   for (int i=0;i<OrdersTotal();i++)
     { OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if (OrderSymbol() == Symbol() && OrderCloseTime()==0) 
         {  if(OrderType()==OP_BUYSTOP )
               { if(OrderMagicNumber()==MAGIC ) 
                  gantung++;
               }   
         }
      }
   return(gantung);
 }
 
        
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

int jmlStopSell()
 { int gantung;
   for (int i=0;i<OrdersTotal();i++)
     { OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if (OrderSymbol() == Symbol() && OrderCloseTime()==0) 
         {  if(OrderType()==OP_SELLSTOP)
               { if(OrderMagicNumber()==MAGIC) 
                  gantung++;
               }  
         }
      }
   return(gantung);
 } 
 
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv 
void SetObject(string name,datetime T1,double P1,datetime T2,double P2,color clr)
  {
   if(ObjectFind(name) == -1)
     {
       ObjectCreate(name, OBJ_TREND, 0, T1, P1, T2, P2);
       ObjectSet(name, OBJPROP_COLOR, clr);
       ObjectSet(name, OBJPROP_STYLE, STYLE_DOT);
     }
   else
     {
       ObjectSet(name, OBJPROP_TIME1, T1);
       ObjectSet(name, OBJPROP_PRICE1, P1);
       ObjectSet(name, OBJPROP_TIME2, T2);
       ObjectSet(name, OBJPROP_PRICE2, P2);
       ObjectSet(name, OBJPROP_COLOR, clr);
       ObjectSet(name, OBJPROP_STYLE, STYLE_DOT);
     } 
  }
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv 
     
int jmlOrder()
 { int gantung;
   for (int i=0;i<OrdersTotal();i++)
     { OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if (OrderSymbol() == Symbol() && OrderCloseTime()==0) 
         {  if(OrderType()==OP_SELLSTOP || OrderType()==OP_BUYSTOP ||
               OrderType()==OP_SELL || OrderType()==OP_BUY)
               { if(OrderMagicNumber()==MAGIC) 
                  gantung++;
               }  
         }
      }
   return(gantung);
 } 
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
string onBool ( bool value)
   {  if(value==true) return ("ON");
      else return ("OFF");
   }   