//+------------------------------------------------------------------+
//|                                   2008                   Ilan1.4 |
//+------------------------------------------------------------------+
#property copyright "Nikisaki@yandex.ru"

//----

extern string S1="---------------- Trade At EMA Cross";

extern bool TradeAtEMACross=false;
extern int EMATF1=60;
extern int EMAPeriod1=50;
extern int EMAMethod1=1; //0=sma, 1=ema, ...
extern int EMAPrice1=0; //0=applied to close,...
extern int EMATF2=60;
extern int EMAPeriod2=100;
extern int EMAMethod2=1; //0=sma, 1=ema, ...
extern int EMAPrice2=0; //0=applied to close,...

extern string S2="---------------- Money Management";

extern double Lots=0.1;//|-----------------------lots size
extern bool RiskMM=false;//|---------------------risk management
extern double RiskPercent=1;//|------------------risk percentage
extern double LotsDigits=2; //2 - micro lots 0.01, 1 - mini lots 0.1, 0 - standard lots 1.0
extern int MMType=0; //0-lots, 1-lotexponent, 2-lotexponent if loss
extern double LotExponent=1; //multiply lots size
extern bool UseEquityStop=false; //close trades at equity loss
extern double TotalEquityRisk=10; //loss as a percentage of equity

extern string S3="---------------- Order Management";

extern int MaxTrades=10;
extern bool UseClose=false;
extern bool UseAdd=true;
extern double PipStep=10;
extern bool HideSLandTP=false;
extern double Stoploss=500;
extern double TakeProfit=10;
extern bool UseTrailingStop=false;
extern double TrailStart=10;
extern double TrailStop=10;
extern double Slippage=3;
extern int MagicNumber=12324;

extern string S4="---------------- ATR Take Profit";

extern bool AutoATRTP=false;
extern int ATRPeriod=14;
extern int XTimesATR=3;

extern string S5="---------------- Max Orders";

extern bool CloseAtMaxOrders=false;
extern int MaxOrders=100;

extern string S6="---------------- Time Out";

extern bool UseTimeOut=false;
extern double MaxTradeOpenHours=48;

extern string S7="---------------- MA Filter";

extern bool DoubleMAFilter=false;
extern int MATF1=0;
extern int MAPeriod1=10;
extern int MAMethod1=0; //0=sma, 1=ema, ...
extern int MAPrice1=0; //0=applied to close,...
extern int MATF2=0;
extern int MAPeriod2=20;
extern int MAMethod2=0; //0=sma, 1=ema, ...
extern int MAPrice2=0; //0=applied to close,...

//----

string EAName="Ilan1/4";
datetime timeprev=0, expiration;
int flag,total,ticket,NumOfTrades=0,cnt=0;
bool TradeNow=false, LongTrade=false,ShortTrade=false,NewOrdersPlaced=false;
double PriceTarget,StartEquity,BuyTarget,SellTarget,AveragePrice,SellLimit,BuyLimit,LastBuyPrice,LastSellPrice,ClosePrice,Spread,iLots,Stopper=0;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int init()
{
   Spread=MarketInfo(Symbol(),MODE_SPREAD)*Point;
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int deinit()
{
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int start()
{  
   int ATRTP;
   string BUY,SELL;
   double MA1=iMA(Symbol(),MATF1,MAPeriod1,0,MAMethod1,MAPrice1,1);
   double MA2=iMA(Symbol(),MATF2,MAPeriod2,0,MAMethod2,MAPrice2,1);
   
   if(MA1>MA2)BUY="true";
   if(MA1<MA2)SELL="true";
   
   double EMA1a=iMA(Symbol(),EMATF1,EMAPeriod1,0,EMAMethod1,EMAPrice1,2);
   double EMA2a=iMA(Symbol(),EMATF1,EMAPeriod2,0,EMAMethod2,EMAPrice2,2);
   double EMA1=iMA(Symbol(),EMATF2,EMAPeriod1,0,EMAMethod1,EMAPrice1,1);
   double EMA2=iMA(Symbol(),EMATF2,EMAPeriod2,0,EMAMethod2,EMAPrice2,1);
   
   double ATR=iATR(NULL,0,ATRPeriod,1);
   
   if(CloseAtMaxOrders&&(CountOrders(OP_BUY,MagicNumber)+CountOrders(OP_SELL,MagicNumber))>MaxOrders)
   {
      CloseBuyOrders(MagicNumber);
      CloseSellOrders(MagicNumber);
   }
   if((HideSLandTP&&Stoploss>0&&OrderType()==OP_BUY&&(OrderOpenPrice()-Ask)/Point>=Stoploss)||(HideSLandTP&&TakeProfit>0&&OrderType()==OP_BUY&&(Bid-OrderOpenPrice())/Point>=TakeProfit))
   {
      CloseBuyOrders(MagicNumber);
   }
   if((HideSLandTP&&Stoploss>0&&OrderType()==OP_SELL&&(Bid-OrderOpenPrice())/Point>=Stoploss)||(HideSLandTP&&TakeProfit>0&&OrderType()==OP_SELL&&(OrderOpenPrice()-Ask)/Point>=TakeProfit))
   {
      CloseSellOrders(MagicNumber);
   }
   if(UseTrailingStop)
   {
      TrailingAlls(TrailStart, TrailStop, AveragePrice);
   }
   if(UseTimeOut)
   {
      if(CurTime()>=expiration)
      {
         CloseThisSymbolAll();
         Print("Closed All due to TimeOut");
      }
   }
   if(timeprev==Time[0])
   {
      return(0);
   }
   timeprev=Time[0];
   
//----

   double CurrentPairProfit=CalculateProfit();
   if(UseEquityStop)
   {
      if(CurrentPairProfit<0 && MathAbs(CurrentPairProfit)>(TotalEquityRisk/100)*AccountEquityHigh())
      {
         CloseThisSymbolAll();
         Print("Closed All due to Stop Out");
         NewOrdersPlaced=false;
      }
   }
   total=CountTrades();
   
   if(RiskMM)CalculateMM();
   
//----

   if (total==0)
   {
      flag=0;
   }
   double LastBuyLots;
   double LastSellLots;
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)continue;
      if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
      if(OrderType()==OP_BUY)
      {
         LongTrade=true;
         ShortTrade=false;
         LastBuyLots=OrderLots();
         break;
      }
      if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
      if(OrderType()==OP_SELL)
      {
         LongTrade=false;
         ShortTrade=true;
         LastSellLots=OrderLots();
         break;
     }
   }
   if(total>0&&total<=MaxTrades)
   {
      RefreshRates();
      LastBuyPrice=FindLastBuyPrice();
      LastSellPrice=FindLastSellPrice();
      if(LongTrade&&(LastBuyPrice-Ask)>=(PipStep*Point))
      {
         TradeNow=true;
      }
      if(ShortTrade && (Bid - LastSellPrice)>=(PipStep*Point))
      {
         TradeNow=true;
      }
   }
   if(total<1)
   {
      ShortTrade=false;
      LongTrade=false;
      TradeNow=true;
      StartEquity=AccountEquity();
   }
   if(TradeNow)
   {
      LastBuyPrice=FindLastBuyPrice();
      LastSellPrice=FindLastSellPrice();
      if(ShortTrade)
      {
         if(UseClose)
         {
            fOrderCloseMarket(false,true);
            iLots=NormalizeDouble(LotExponent*LastSellLots,LotsDigits);
         }
         else
         {
            iLots=fGetLots(OP_SELL);
         }
         if(UseAdd&&(DoubleMAFilter==false||(DoubleMAFilter&&SELL=="true")))
         {
            NumOfTrades=total;
            if(iLots>0)
            {
               RefreshRates();
               ticket=OpenPendingOrder(OP_SELL,iLots,Bid,Slippage,Ask,0,0,EAName+"-"+NumOfTrades,MagicNumber,0,HotPink);
               if(ticket<0)
               {
                  Print("Error: ",GetLastError());
                  return(0);
               }
               LastSellPrice=FindLastSellPrice();
               TradeNow=false;
               NewOrdersPlaced=true;
            }
         }
      }
      else if(LongTrade)
      {
         if(UseClose)
         {
            fOrderCloseMarket(true,false);
            iLots=NormalizeDouble(LotExponent*LastBuyLots,LotsDigits);
         }
         else
         {
            iLots=fGetLots(OP_BUY);
         }
         if(UseAdd&&(DoubleMAFilter==false||(DoubleMAFilter&&BUY=="true")))
         {
            NumOfTrades=total;
            if(iLots>0)
            {
               ticket=OpenPendingOrder(OP_BUY,iLots,Ask,Slippage,Bid,0,0,EAName+"-"+NumOfTrades,MagicNumber,0,Lime);
               if(ticket<0)
               {
                  Print("Error: ",GetLastError());
                  return(0);
               }
               LastBuyPrice=FindLastBuyPrice();
               TradeNow=false;
               NewOrdersPlaced=true;
            }
         }
      }
   }
   if(TradeNow&&total<1)
   {
      double PrevCl=iClose(Symbol(),0,2);
      double CurrCl=iClose(Symbol(),0,1);
      SellLimit=Bid;
      BuyLimit=Ask;
      if(!ShortTrade&&!LongTrade)
      {
         NumOfTrades=total;
         if(PrevCl>CurrCl&&(DoubleMAFilter==false||(DoubleMAFilter&&SELL=="true"))&&(TradeAtEMACross==false||(TradeAtEMACross&&EMA1a>EMA2a&&EMA1<EMA2)))
         {
            iLots=fGetLots(OP_SELL);
            if(iLots>0)
            {
               ticket=OpenPendingOrder(OP_SELL,iLots,SellLimit,Slippage,SellLimit,0,0,EAName+"-"+NumOfTrades,MagicNumber,0,HotPink);
               if(ticket<0)
               {
                  Print(iLots,"Error: ",GetLastError());
                  return(0);
               }
               LastBuyPrice=FindLastBuyPrice();
               NewOrdersPlaced=true;
            }
         }
         if(PrevCl<CurrCl&&(DoubleMAFilter==false||(DoubleMAFilter&&BUY=="true"))&&(TradeAtEMACross==false||(TradeAtEMACross&&EMA1a<EMA2a&&EMA1>EMA2)))
         {
            iLots=fGetLots(OP_BUY);
            if(iLots>0)
            {
               ticket=OpenPendingOrder(OP_BUY,iLots,BuyLimit,Slippage,BuyLimit,0,0,EAName+"-"+NumOfTrades,MagicNumber,0,Lime);
               if(ticket<0)
               {
                  Print(iLots,"Error: ",GetLastError());
                  return(0);
               }
               LastSellPrice=FindLastSellPrice();
               NewOrdersPlaced=true;
            }
         }
      }
      if(ticket>0) expiration=CurTime()+MaxTradeOpenHours*60*60;
      TradeNow=false;
   }
   
//----------------------- Calculate average opening price  

   total=CountTrades();
   AveragePrice=0;
   double Count=0;
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
      continue;
      if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
      if(OrderType()==OP_BUY||OrderType()==OP_SELL)
      {
         AveragePrice=AveragePrice+OrderOpenPrice()*OrderLots();
         Count=Count+OrderLots();
      }
   }
   if(total>0)
   AveragePrice=NormalizeDouble(AveragePrice/Count,Digits);
   
//----------------------- Recalculate stoploss & profit target based on average opening price

   if(NewOrdersPlaced)
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
      continue;
      if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
      if(OrderType()==OP_BUY&&HideSLandTP==false) //Calculate profit/stop target for long 
      {
         if(AutoATRTP&&ATR>=(10*Point))PriceTarget=AveragePrice+(ATR*XTimesATR);else PriceTarget=AveragePrice+(TakeProfit*Point);
         BuyTarget=PriceTarget;
         Stopper=AveragePrice-(Stoploss*Point); //Stopper=0; 
         flag=1;
      }
      if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
      if(OrderType()==OP_SELL&&HideSLandTP==false) //Calculate profit/stop target for short
      {
         if(AutoATRTP&&ATR>=(10*Point))PriceTarget=AveragePrice-(ATR*XTimesATR);else PriceTarget=AveragePrice-(TakeProfit*Point); 
         SellTarget=PriceTarget;
         Stopper=AveragePrice+(Stoploss*Point); //Stopper=0; 
         flag=1;
      }
   }
   
//----------------------- If needed change all open orders to newly calculated profit target

   if(NewOrdersPlaced)
   if(flag==1) //check if average has really changed
   {
      for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
      { //PriceTarget=total;
         OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
         if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
         continue;
         if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber) //OrderModify(OrderTicket(),0,Stopper,PriceTarget,0,Yellow); //set all positions to averaged levels
         OrderModify(OrderTicket(),AveragePrice,Stopper,PriceTarget,0,Yellow); //set all positions to averaged levels
         NewOrdersPlaced=false;
      }
   }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

double ND(double v){return(NormalizeDouble(v,Digits));}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int fOrderCloseMarket(bool aCloseBuy=true,bool aCloseSell=true)
{
   int tErr=0;
   for(int i=OrdersTotal()-1;i>=0;i--)
   {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
      {
         if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
         {
            if(OrderType()==OP_BUY && aCloseBuy)
            {
               RefreshRates();
               if(!IsTradeContextBusy())
               {
                  if(!OrderClose(OrderTicket(),OrderLots(),ND(Bid),5,CLR_NONE))
                  {
                     Print("Error close BUY "+OrderTicket()); //+" "+fMyErDesc(GetLastError())); 
                     tErr=-1;
                  }
               }
               else
               {
                  static int lt1=0;
                  if(lt1!=iTime(NULL,0,0))
                  {
                     lt1=iTime(NULL,0,0);
                     Print("Need close BUY "+OrderTicket()+". Trade Context Busy");
                  }
                  return(-2);
               }
            }
            if(OrderType()==OP_SELL && aCloseSell)
            {
               RefreshRates();
               if(!IsTradeContextBusy())
               {
                  if(!OrderClose(OrderTicket(),OrderLots(),ND(Ask),5,CLR_NONE))
                  {
                     Print("Error close SELL "+OrderTicket()); //+" "+fMyErDesc(GetLastError())); 
                     tErr=-1;
                  }
               }
               else
               {
                  static int lt2=0;
                  if(lt2!=iTime(NULL,0,0))
                  {
                     lt2=iTime(NULL,0,0);
                     Print("Need close SELL "+OrderTicket()+". Trade Context Busy");
                  }
                  return(-2);
               }
            }
         }
      }
   }
   return(tErr);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

double fGetLots(int aTradeType)
{
   double tLots;
   switch(MMType)
   {
      case 0:
           tLots=Lots;
           break;
      case 1:
           tLots=NormalizeDouble(Lots*MathPow(LotExponent,NumOfTrades),LotsDigits);
           break;
      case 2:
           int LastClosedTime=0;
           tLots=Lots;
           for(int i=OrdersHistoryTotal()-1;i>=0;i--)
           {
              if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY))
              {
                 if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
                 {
                    if(LastClosedTime<OrderCloseTime())
                    {
                       LastClosedTime=OrderCloseTime();
                       if(OrderProfit()<0)
                       {
                          tLots=NormalizeDouble(OrderLots()*LotExponent,LotsDigits);
                       }
                       else
                       {
                          tLots=Lots;
                       }
                    }
                 }
              }
              else
              {
                 return(-3);
              }
           }
           break;
   }
   if(AccountFreeMarginCheck(Symbol(),aTradeType,tLots)<=0)
   {
      return(-1);
   }
   if(GetLastError()==134)
   {
      return(-2);
   }
   return(tLots);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int CountTrades()
{
   int count=0;
   int trade;
   for(trade=OrdersTotal()-1;trade>=0;trade--)
   {
      OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
      continue;
      if(OrderSymbol()==Symbol()&&OrderMagicNumber()==MagicNumber)
      if(OrderType()==OP_SELL||OrderType()==OP_BUY)
      count++;
   }
   return(count);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

void CloseThisSymbolAll()
{
   int trade;
   for(trade=OrdersTotal()-1;trade>=0;trade--)
   {
      OrderSelect(trade,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()!=Symbol())
      continue;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()== MagicNumber)
      {
         if(OrderType()==OP_BUY)
         OrderClose(OrderTicket(),OrderLots(),Bid,Slippage,Blue);
         if(OrderType()==OP_SELL)
         OrderClose(OrderTicket(),OrderLots(),Ask,Slippage,Red);
      }
      Sleep(1000);
   }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int OpenPendingOrder(int pType,double pLots,double pLevel,int sp, double pr, int sl, int tp,string pComment,int pMagic,datetime pExpiration,color pColor)
{
   int ticket=0;
   int err=0;
   int c=0;
   int NumberOfTries=100;
   switch(pType)
   {
      case OP_BUYLIMIT:
           for(c=0;c < NumberOfTries;c++)
           {
              ticket=OrderSend(Symbol(),OP_BUYLIMIT,pLots,pLevel,sp,StopLong(pr,sl),TakeLong(pLevel,tp),pComment,pMagic,pExpiration,pColor);
              err=GetLastError();
              if(err==0)
              {
                 break;
              }
              else
              {
                 if(err==4||err==137||err==146||err==136) //Busy errors
                 {
                    Sleep(1000);
                    continue;
                 }
                 else //normal error
                 {
                    break;
                 }
              }
           }
           break;
      case OP_BUYSTOP:
           for(c=0;c < NumberOfTries;c++)
           {
              ticket=OrderSend(Symbol(),OP_BUYSTOP,pLots,pLevel,sp,StopLong(pr,sl),TakeLong(pLevel,tp),pComment,pMagic,pExpiration,pColor);
              err=GetLastError();
              if(err==0)
              {
                 break;
              }
              else
              {
                 if(err==4||err==137||err==146||err==136) //Busy errors
                 {
                    Sleep(5000);
                    continue;
                 }
                 else //normal error
                 {
                    break;
                 }
              }
           }
           break;
      case OP_BUY:
           for(c=0;c < NumberOfTries;c++)
           {
              RefreshRates();
              ticket=OrderSend(Symbol(),OP_BUY,pLots,Ask,sp,StopLong(Bid,sl),TakeLong(Ask,tp),pComment,pMagic,pExpiration,pColor);
              err=GetLastError();
              if(err==0)
              {
                 break;
              }
              else
              {
                 if(err==4 || err==137 ||err==146 || err==136) //Busy errors
                 {
                    Sleep(5000);
                    continue;
                 }
                 else //normal error
                 {
                     break;
                 }
              }
           }
           break;
      case OP_SELLLIMIT:
           for(c=0;c < NumberOfTries;c++)
           {
              ticket=OrderSend(Symbol(),OP_SELLLIMIT,pLots,pLevel,sp,StopShort(pr,sl),TakeShort(pLevel,tp),pComment,pMagic,pExpiration,pColor);
              err=GetLastError();
              if(err==0)
              {
                 break;
              }
              else
              {
                 if(err==4||err==137||err==146||err==136) //Busy errors
                 {
                    Sleep(5000);
                    continue;
                 }
                 else //normal error
                 {
                    break;
                 }
              }
           }
           break;
      case OP_SELLSTOP:
           for(c=0;c < NumberOfTries;c++)
           {
              ticket=OrderSend(Symbol(),OP_SELLSTOP,pLots,pLevel,sp,StopShort(pr,sl),TakeShort(pLevel,tp),pComment,pMagic,pExpiration,pColor);
              err=GetLastError();
              if(err==0)
              {
                 break;
              }
              else
              {
                 if(err==4||err==137||err==146||err==136) //Busy errors
                 {
                    Sleep(5000);
                    continue;
                 }
                 else //normal error
                 {
                    break;
                 }
              }
           }
           break;
     case OP_SELL:
          for(c=0;c<NumberOfTries;c++)
          {
             ticket=OrderSend(Symbol(),OP_SELL,pLots,Bid,sp,StopShort(Ask,sl),TakeShort(Bid,tp),pComment,pMagic,pExpiration,pColor);
             err=GetLastError();
             if(err==0)
             {
                break;
             }
             else
             {
                if(err==4||err==137||err==146||err==136) //Busy errors
                {
                   Sleep(5000);
                   continue;
                }
                else //normal error
                {
                   break;
                }
             }
          }
          break;
   }
   return(ticket);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

double StopLong(double price,int stop)
{
   if(stop==0)
   return(0);
   else
   return(price-(stop*Point));
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

double StopShort(double price,int stop)
{
   if(stop==0)
   return(0);
   else
   return(price+(stop*Point));
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

double TakeLong(double price,int take)
{
   if(take==0)
   return(0);
   else
   return(price+(take*Point));
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

double TakeShort(double price,int take)
{
   if(take==0)
   return(0);
   else
   return(price-(take*Point));
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

double CalculateProfit()
{
   double Profit=0;
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
      continue;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber)
      if(OrderType()==OP_BUY || OrderType()==OP_SELL)
      {
         Profit=Profit+OrderProfit();
      }
   }
   return(Profit);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

void TrailingAlls(int start,int stop, double AvgPrice)
{
   int profit;
   double stoptrade;
   double stopcal;
   if(stop==0)
   return;
   int trade;
   for(trade=OrdersTotal()-1;trade>=0;trade--)
   {
      if(!OrderSelect(trade,SELECT_BY_POS,MODE_TRADES))
      continue;
      if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
      continue;
      if(OrderSymbol()==Symbol()||OrderMagicNumber()==MagicNumber)
      {
         if(OrderType()==OP_BUY)
         {
            profit=NormalizeDouble((Bid-AvgPrice)/Point,0);
            if(profit<start)
            continue;
            stoptrade=OrderStopLoss();
            stopcal=Bid-(stop*Point);
            if(stoptrade==0||(stoptrade!=0&&stopcal>stoptrade)) //OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Blue);
            OrderModify(OrderTicket(),AvgPrice,stopcal,OrderTakeProfit(),0,Aqua);
         }
         if(OrderType()==OP_SELL)
         {
            profit=NormalizeDouble((AvgPrice-Ask)/Point,0);
            if(profit<start)
            continue;
            stoptrade=OrderStopLoss();
            stopcal=Ask+(stop*Point);
            if(stoptrade==0||(stoptrade!=0&&stopcal<stoptrade)) // OrderModify(OrderTicket(),OrderOpenPrice(),stopcal,OrderTakeProfit(),0,Red);
            OrderModify(OrderTicket(),AvgPrice,stopcal,OrderTakeProfit(),0,Red);
         }
      }
      Sleep(1000);
   }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

double AccountEquityHigh()
{
   static double AccountEquityHighAmt,PrevEquity;
   if(CountTrades()==0) AccountEquityHighAmt=AccountEquity();
   if(AccountEquityHighAmt < PrevEquity) AccountEquityHighAmt=PrevEquity;
   else AccountEquityHighAmt=AccountEquity();
   PrevEquity=AccountEquity();
   return(AccountEquityHighAmt);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

double FindLastBuyPrice()
{
   double oldorderopenprice=0,orderprice;
   int cnt,oldticketnumber=0,ticketnumber;
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
      continue;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderType()==OP_BUY)
      {
         ticketnumber=OrderTicket();
         if(ticketnumber>oldticketnumber)
         {
            orderprice=OrderOpenPrice();
            oldorderopenprice=orderprice;
            oldticketnumber=ticketnumber;
         }
      }
   }
   return(orderprice);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

double FindLastSellPrice()
{
   double oldorderopenprice=0,orderprice;
   int cnt,oldticketnumber=0,ticketnumber;
   for(cnt=OrdersTotal()-1;cnt>=0;cnt--)
   {
      OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol()!=Symbol()||OrderMagicNumber()!=MagicNumber)
      continue;
      if(OrderSymbol()==Symbol() && OrderMagicNumber()==MagicNumber && OrderType()==OP_SELL)
      {
         ticketnumber=OrderTicket();
         if(ticketnumber>oldticketnumber)
         {
            orderprice=OrderOpenPrice();
            oldorderopenprice=orderprice;
            oldticketnumber=ticketnumber;
         }
      }
   }
   return(orderprice);
}

//+------------------------------------------------------------------+

//|---------count orders

int CountOrders(int Type,int Magic)
{
   int _CountOrd;
   _CountOrd=0;
   for(int i=0;i<OrdersTotal();i++)
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      if(OrderSymbol()==Symbol())
      {
         if((OrderType()==Type&&(OrderMagicNumber()==Magic)||Magic==0))_CountOrd++;
      }
   }
   return(_CountOrd);
}

//|---------close buy orders

int CloseBuyOrders(int Magic)
{
  int result,total=OrdersTotal();

  for (int cnt=total-1;cnt>=0;cnt--)
  {
    OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
    if(OrderMagicNumber()==Magic&&OrderSymbol()==Symbol())
    {
      if(OrderType()==OP_BUY)
      {
        OrderClose(OrderTicket(),OrderLots(),Bid,3);
        switch(OrderType())
        {
          case OP_BUYLIMIT:
          case OP_BUYSTOP:
          result=OrderDelete(OrderTicket());
        }
      }
    }
  }
  return(0);
}

//|---------close sell orders

int CloseSellOrders(int Magic)
{
  int result,total=OrdersTotal();

  for(int cnt=total-1;cnt>=0;cnt--)
  {
    OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES);
    if(OrderMagicNumber()==Magic&&OrderSymbol()==Symbol())
    {
      if(OrderType()==OP_SELL)
      {
        OrderClose(OrderTicket(),OrderLots(),Ask,3);
        switch(OrderType())
        {
          case OP_SELLLIMIT:
          case OP_SELLSTOP:
          result=OrderDelete(OrderTicket());
        }
      }
    }
  }
  return(0);
}

void CalculateMM()
{
   double MinLots=MarketInfo(Symbol(),MODE_MINLOT);
   double MaxLots=MarketInfo(Symbol(),MODE_MAXLOT);
   Lots=AccountFreeMargin()/100000*RiskPercent;
   Lots=MathMin(MaxLots,MathMax(MinLots,Lots));
   if(MinLots<0.1)Lots=NormalizeDouble(Lots,2);
   else
   {
     if(MinLots<1)Lots=NormalizeDouble(Lots,1);
     else Lots=NormalizeDouble(Lots,0);
   }
   if(Lots<MinLots)Lots=MinLots;
   if(Lots>MaxLots)Lots=MaxLots;
   return(0);
}