//====================== Locomotive v1.00 ======================== 


input bool    buy            = true;
input bool    sell           = true;

input double  take_profit    = 15;
input double  lot            = 0.1;
input double  lot_factor_1   = 1.6;
input double  step_1         = 25;
input double  set_2          = 4;
input double  lot_factor_2   = 1.7;
input double  step_2         = 35;
input double  set_3          = 8;
input double  hedje_factor   = 0.5;
input double  hedje_plus     = 0.05;
input string  menucomment02  = "||||||||||||||||||||||||||||||||||||||||||||| Прочие параметры |||||||||||||||||||||||||||||||||||||||||||||";
input int     magic          = 1543;
input int     magic2         = 1544;
double        Sensitivity    = 1;
input int     TryToTrade     = 20;
input int     WaitTime       = 1500;
input int     CommetSize     = 7;
input int     ATR_Period = 60;
input int     ATR_Factor = 3;
input int     CCI_Period = 10;
input int     CCI_Level = 110; 
input bool    AlertSystem = true;
input int     AlertPasuse = 60;
input bool    Send_Push_Notifications = true;
input int     bars = 10000;
input double  Layer_Multiplier = 10.5;
//input int     sellvalue =0;
//input int     buyvalue=0;
//-----------------------------------------------------------------------------------------------------------------------------
input int     Stoploss      = 0;    // Стоп-лосс
input int     Takeprofit    = 0;    // Тейк-профит
input int     TrailingStop  = 5;    // Длина трала
input int     TrailingStart = 5;    // Минимальная прибыль для старта
input int     TrailingStep  = 1;    // Шаг трала
//------------------------------------------------------------------------------------
double    TrallB        = 0;
double    TrallS        = 0;
int       slippage      =30;
//-----------------------------------------------------------------------------------------------------------------------------
int i, Ticket, DG, LastError, TimeB, TimeS;
bool TickeT, Work=true;
double Pp, Mnoj, Mnoj2;
string Symb,CommentBox[],cm2;
string indicator;
double BuySignal,SellSignal,BuyLine,SellLine ;
datetime t;

double lt[30],lt_h[30],step[30];
//896896896869869869869869689686986986986986968869869869869689689686986986986986986968968986
void start() {
   if (Work==false) return;
   if(buy) buyf();
   if(sell) sellf();
   BuySignal = iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 3, 1);
      SellSignal = iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 2, 1);
      BuyLine = iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 0, 1);
      SellLine = iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 1, 1);
//      Print ("SellSignal ",SellSignal);      
//      Print ("BuySignal ",BuySignal);
//Print ("0",iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 0, 1));
//Print ("1",iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 1, 1));
//Print ("2",iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 2, 1));
//Print ("3",iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 3, 1));
//Print ("4",iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 4, 1));
//Print ("5",iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 5, 1));
//Print ("6",iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 6, 1));
//Print ("7",iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 7, 1));
//Print ("8",iCustom(NULL, 0, "MarketInsider_v1.2.ex4", ATR_Period, ATR_Factor, CCI_Period, CCI_Level, AlertSystem,AlertPasuse,Send_Push_Notifications, bars , 8, 1));

   }
//896896896869869869869869689686986986986986968869869869869689689686986986986986986968968986
void buyf()
     {
   int market,lock;
   double lastprice;
         double price,slot;
   double del_price, del_slot;
   for(i=OrdersTotal()-1;i>=0;i--) 
      {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic) 
      {
         if(OrderType()==0)
       {
            market++;                                                         //счётчик buy
            if(OrderOpenPrice()<lastprice || lastprice==0) lastprice=OrderOpenPrice();          //обновление lastprice по цене последнего открытого ордера buy
            }
            else
            {
            lock++;                                                           //счётчик sell
            }
         }
      }
   if(market!=0 || lock!=0) 
      {
      for(i=OrdersHistoryTotal()-1;i>=0;i--) 
      {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY) && OrderSymbol()==Symb && OrderMagicNumber()==magic && OrderCloseTime()>TimeB)
        {
         del_price=OrderOpenPrice();
         del_slot=OrderLots();
//            DeleteAll(magic);                                //при закрытии самого старого ордера закрываются все остальные
//==============================================
//модификация ордеров при закрытии
      for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic) {
            if(OrderType()==0) slot+=OrderLots(); else slot-=OrderLots();
            }
         }
      slot =slot-del_slot;
      for(i=OrdersTotal()-1;i>=0;i--) 
      {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic&&slot>0) 
         {
            if(OrderType()==0) price+=OrderOpenPrice()*(OrderLots()/slot); else price-=OrderOpenPrice()*(OrderLots()/slot);
            }
         }
      price = price - del_price;
      price=NormalizeDouble(price+take_profit*Pp,Digits);
     for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic) {
            if(OrderType()==0) OrderModify(OrderTicket(),-1,1,price);
                          else OrderModify(OrderTicket(),-1,price+(Ask-Bid),1);
            }
         }
//==============================

            TimeB=TimeCurrent();                               //обновление TimeB по нынешнему времени
            
            return;
            }
         }
      }
   if(market==0 && (BuyLine<2147483647&&BuyLine>0&&BuySignal<2147483647&&BuySignal>0)&&iBarShift(NULL,0,t)>0) {
      TimeB=TimeCurrent();
      SendOrder(0,lt[0],-1,1,1500,1,0,magic);                    //открытие ордера на покупку если нет открытых buy
      t=iTime(NULL,0,0);
      }
   if(market>0 && Ask<lastprice-step[market-1]*Pp && (BuyLine<2147483647&&BuyLine>0&&BuySignal<2147483647&&BuySignal>0)&&iBarShift(NULL,0,t)>0) {                    //если есть ордер на покупку и цена ask меньше чем последняя цена по buy с учётом уставки и шага
      SendOrder(0,lt[market],-1,1,1500,1,0,magic);
      t=iTime(NULL,0,0);
      if(market>=set_3-1 && (SellLine<2147483647&&SellLine>0&&SellSignal<2147483647&&SellSignal>0)&&iBarShift(NULL,0,t)>0) {
      SendOrder(1,lt_h[market],-1,1,1500,1,0,magic);   //открытие хеджирующего ордера при достижении отметки на set_3
      t=iTime(NULL,0,0);
      }
      for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic) {
         //ordprofit= ordprofit+OrderProfit();
            if(OrderType()==0) slot+=OrderLots(); else slot-=OrderLots();
            }
         }
      for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic&& slot>0) {
            if(OrderType()==0) price+=OrderOpenPrice()*(OrderLots()/slot); 
            
            else price-=OrderOpenPrice()*(OrderLots()/slot);
            }
         }
      price=NormalizeDouble(price+take_profit*Pp,Digits);
      //if (ordprofit/lot>NormalizeDouble(take_profit, Digits)) DeleteAll(magic);
            
      
      for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic) {
           // ordprofit= ordprofit+OrderProfit();
            
            if(OrderType()==0) OrderModify(OrderTicket(),-1,-1,price);
                          else OrderModify(OrderTicket(),-1,price+(Ask-Bid),-1);
      }
         }
      }
   }
//896896896869869869869869689686986986986986968869869869869689689686986986986986986968968986
void sellf() {
   int market,lock;
   double lastprice;
   double price,slot, ordprofit;
   double del_price, del_slot;
   for(i=OrdersTotal()-1;i>=0;i--) {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic2) {
         if(OrderType()==1) {
            market++;
            if(OrderOpenPrice()>lastprice) lastprice=OrderOpenPrice();
            }else{
            lock++;
            }
         }
      }
   if(market!=0 || lock!=0) {
      for(i=OrdersHistoryTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY) && OrderSymbol()==Symb && OrderMagicNumber()==magic2 && OrderCloseTime()>TimeS) {
//            DeleteAll(magic2);
//==============================================
//модификация ордеров при закрытии
      for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic2) {
//         ordprofit= ordprofit+OrderProfit();
            if(OrderType()==0) slot+=OrderLots(); else slot-=OrderLots();
            }
         }
      slot =slot-del_slot;
      for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic2&&slot>0) {
            if(OrderType()==0) price+=OrderOpenPrice()*(OrderLots()/slot); else price-=OrderOpenPrice()*(OrderLots()/slot);
            }
         }
      price = price - del_price;
      price=NormalizeDouble(price-take_profit*Pp,Digits);
 //     if (ordprofit/lot>NormalizeDouble(take_profit, Digits)) DeleteAll(magic); 
      for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic2) {
            if(OrderType()==0) OrderModify(OrderTicket(),-1,-1,price);
                          else OrderModify(OrderTicket(),-1,price-(Ask-Bid),-1);
         }
         }
//==============================
            TimeS=TimeCurrent();
            return;
            }
         }
      }
   if(market==0 && (SellLine<2147483647&&SellLine>0&&SellSignal<2147483647&&SellSignal>0)&&iBarShift(NULL,0,t)>0) {
      TimeS=TimeCurrent();
      SendOrder(1,lt[0],-1,1,1500,1,0,magic2);
      t=iTime(NULL,0,0);
      }
   if(market>0 && Bid>lastprice+step[market-1]*Pp && (SellLine<2147483647&&SellLine>0&&SellSignal<2147483647&&SellSignal>0)&&iBarShift(NULL,0,t)>0) {
      SendOrder(1,lt[market],-1,1,1500,1,0,magic2);
      t=iTime(NULL,0,0);
      if(market>=set_3-1 && (BuyLine<2147483647&&BuyLine>0&&BuySignal<2147483647&&BuySignal>0)&&iBarShift(NULL,0,t)>0) {
      SendOrder(0,lt_h[market],-1,1,1500,1,0,magic2);
      t=iTime(NULL,0,0);
      }
//      double price,slot;
      for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic2) {
            ordprofit= ordprofit+OrderProfit();
            if(OrderType()==1) slot+=OrderLots(); else slot-=OrderLots();
            }
         }
      for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic2&&slot>0) {
            if(OrderType()==1) price+=OrderOpenPrice()*(OrderLots()/slot); 
            else price-=OrderOpenPrice()*(OrderLots()/slot);
            }
         }
      price=NormalizeDouble(price-take_profit*Pp,Digits);
      if (ordprofit/lot>NormalizeDouble(take_profit, Digits)) DeleteAll(magic2);
      for(i=OrdersTotal()-1;i>=0;i--) {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==magic2) {
            if(OrderType()==1) OrderModify(OrderTicket(),-1,-1,price);
                          else OrderModify(OrderTicket(),-1,price-(Ask-Bid),-1);
         }
         }
      }
   }
//896896896869869869869869689686986986986986968869869869869689689686986986986986986968968986
bool SendOrder(int Type,double LT,double OP,int ModeSL,double SL,int ModeTP,double TP,int MG) {
   color CL;
   if (Type==0) CL=Blue; else  if (Type==1) CL=Red; else  if (Type==2 || Type==4) CL=DarkTurquoise; else if (Type==3 || Type==5) CL=Orange;
   // првоерка объема
   if (LT<MarketInfo(Symbol(),MODE_MINLOT)) LT=MarketInfo(Symbol(),MODE_MINLOT);
   if (LT>MarketInfo(Symbol(),MODE_MAXLOT)) LT=MarketInfo(Symbol(),MODE_MAXLOT);
   if (LT*MarketInfo(Symbol(),MODE_MARGINREQUIRED)>AccountEquity()) {
//      PnC(StringConcatenate("Нехватает денег для октрытия сделки",Type," объемом: ",DoubleToStr(LT,DG)),0);
      return(false);
      }
   // проверка отложенных ордеров
   double Slv=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point;
   if (Type>1) {
      if (Type==2 && Ask-OP<Slv) OP=Ask-Slv;
      if (Type==3 && OP-Bid<Slv) OP=Bid+Slv;
      if (Type==4 && OP-Ask<Slv) OP=Ask+Slv;
      if (Type==5 && Bid-OP<Slv) OP=Bid-Slv;
      }
   // открытие
   for(int k=0;k<=TryToTrade;k++) {
      if (Type==0) OP=Ask; 
      if (Type==1) OP=Bid;  
//      PnC(StringConcatenate("Открытие ордера, тип: ",Type," объем: ",DoubleToStr(LT,DG)," цена: ",DoubleToStr(OP,Digits)),0); 
      if (IsTradeAllowed()) {
          Ticket=OrderSend(Symbol(),Type,LT,NormalizeDouble(OP,Digits),3,0,0,NULL,MG,0,CL);
         }else{ //PnC(StringConcatenate("Торговый поток занят, ждем ",k),0); 
         Sleep(WaitTime); 
         continue; }
      if (Ticket >= 0) { //PnC(StringConcatenate("Открыт ордер ",Ticket),0); 
      break; }
      ResetLastError();
      LastError=Fun_Error(GetLastError());
      if (LastError==0) { 
         RefreshRates(); Sleep(WaitTime); 
         if (k==TryToTrade) return(false); }
      if (LastError==1) return(false);
      if (LastError==2) { Work=false; return(false); }
       }
   if (SL==0 && TP==0) return(true);
   Ticket=OrderSelect(Ticket,SELECT_BY_TICKET,MODE_TRADES);
   // проверка и расчет стопов
   if (ModeSL==0) {
      if (MathAbs(OrderOpenPrice()-SL)<Slv && SL!=0) {
         if (Type==0 || Type==2 || Type==4) SL=OrderOpenPrice()-Slv; else SL=OrderOpenPrice()+Slv;
         }
      }else{
      if (SL!=0) {
         if (Type==0 || Type==2 || Type==4) SL=OrderOpenPrice()-SL*Pp;
         if (Type==1 || Type==3 || Type==5) SL=OrderOpenPrice()+SL*Pp;
         }
      }
   if (ModeTP==0) {
      if (MathAbs(OrderOpenPrice()-TP)<Slv && TP!=0) {
         if (Type==0 || Type==2 || Type==4) TP=OrderOpenPrice()+Slv; else TP=OrderOpenPrice()-Slv;
         }
      }else{
      if (TP!=0) {
         if (Type==0 || Type==2 || Type==4) TP=OrderOpenPrice()+TP*Pp;
         if (Type==1 || Type==3 || Type==5) TP=OrderOpenPrice()-TP*Pp;
         }
      }
   // выставляем стопы
   for(k=0;k<=TryToTrade;k++) {
 //     PnC(StringConcatenate("Установка стопов на ордер: ",Ticket," с/л: ",DoubleToStr(SL,Digits)," т/п: ",DoubleToStr(TP,Digits)),0);
      if (IsTradeAllowed()) {
         TickeT=OrderModify(Ticket,OrderOpenPrice(),NormalizeDouble(SL,Digits),NormalizeDouble(TP,Digits),0,CLR_NONE);
         }else{ //PnC(StringConcatenate("Торговый поток занят, ждем ",k),0); 
         Sleep(WaitTime); continue; }
      if (TickeT == true) { //PnC(StringConcatenate("Модифицирован ордер ",Ticket),0);
       break; }
       ResetLastError();
      LastError=Fun_Error(GetLastError());
      if (LastError==0) { 
         RefreshRates(); Sleep(WaitTime); 
         if (k==TryToTrade) return(false); }
      if (LastError==1) return(false);
      if (LastError==2) { Work=false; return(false); }
   }
   return(true);
   }


//-----------
  /* double NormalizeLot(string symbol,double volume)
  {
   double lot=volume,
          lot_min=SymbolInfoDouble(symbol,SYMBOL_VOLUME_MIN),
          lot_max=SymbolInfoDouble(symbol,SYMBOL_VOLUME_MAX),
          lot_step=SymbolInfoDouble(symbol,SYMBOL_VOLUME_STEP);
   if(lot<lot_min)
      lot=lot_min;
   if(lot>lot_max)
      lot=lot_max;
   int step=(int)((lot-lot_min)/lot_step);
   return(lot_min+step*lot_step);
  }
  */
  
//896896896869869869869869689686986986986986968869869869869689689686986986986986986968968986
void CloseOrder(int Number,double LT) {
   if (!OrderSelect(Number,SELECT_BY_TICKET,MODE_TRADES)) return;
   bool Type=OrderType();
   if (Type>1) return;
   if(LT==-1) LT=NormalizeDouble(OrderLots(),DG); else LT=NormalizeDouble(LT,DG);
   double OCP;
   for(int k=0;k<=TryToTrade;k++) 
    {
      if (Type==0) OCP=Bid; else OCP=Ask;
      //PnC(StringConcatenate("Закрытие ордера: ",Number," тип: ",Type," объем: ",DoubleToStr(LT,DG)," по цене: ",DoubleToStr(OCP,Digits)),0);
      if (IsTradeAllowed()) 
      {
         TickeT=OrderClose(Number,LT,NormalizeDouble(OCP,Digits),30,White);
         }else{ PnC(StringConcatenate("Торговый поток занят, ждем ",k),0); Sleep(WaitTime); continue; }
      if (TickeT) { PnC("Закрыт ордер ",0); return; }
      LastError=Fun_Error(GetLastError());
      if (LastError==0)
       { 
         RefreshRates(); Sleep(WaitTime); 
         if (k==TryToTrade) return;
          }
      if (LastError==1) return;
      if (LastError==2) { Work=false; return;
       }
      }
   return;
   }
//896896896869869869869869689686986986986986968869869869869689689686986986986986986968968986
void DeleteAll(int MG) {
   for(i=OrdersTotal()-1;i>=0;i--) {
      if (OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb && OrderMagicNumber()==MG) {
         if (OrderType()<2) CloseOrder(OrderTicket(),OrderLots()); else bool d=OrderDelete(OrderTicket());
         }
      }
   }
//896896896869869869869869689686986986986986968869869869869689689686986986986986986968968986
void OrderModify (int Tick,double OP=-1,double SL=-1,double TP=-1) 
{
   if (OrderSelect(Tick,SELECT_BY_TICKET,MODE_TRADES)==false) return;
   string cm;
   if(OP<0) OP=OrderOpenPrice(); else cm="цена " + DoubleToStr(OrderOpenPrice(),Digits) + " => " + DoubleToStr(OP,Digits) + "; ";
   if(SL<0) SL=OrderStopLoss(); else cm=cm+"с/л " + DoubleToStr(OrderStopLoss(),Digits) + " => " + DoubleToStr(SL,Digits) + "; ";
   if(TP<0) TP=OrderTakeProfit(); else cm=cm+"т/п " + DoubleToStr(OrderTakeProfit(),Digits) + " => " + DoubleToStr(TP,Digits) + "; ";
   for(int k=0;k<=TryToTrade;k++) {
      PnC(StringConcatenate("Модификация ордера: ",Tick," ",cm),0);
      if (IsTradeAllowed()) {
         TickeT=OrderModify(OrderTicket(),NormalizeDouble(OP,Digits),NormalizeDouble(SL,Digits),NormalizeDouble(TP,Digits),0,CLR_NONE);
         }else{ PnC(StringConcatenate("Торговый поток занят, ждем ",k),0); Sleep(WaitTime); continue; }
      if (TickeT ==true) { PnC("Ордер модифицирован ",0); return; }
      LastError=Fun_Error(GetLastError());
      if (LastError==0) { 
         RefreshRates(); Sleep(WaitTime); 
         if (k==TryToTrade) return; }
      if (LastError==1) return;
      if (LastError==2) { Work=false; return; }
      }
   }
//896896896869869869869869689686986986986986968869869869869689689686986986986986986968968986
void init() {
   Pp=Point;
   Mnoj2=1/Pp;
   if (Pp==0.00001 || Pp==0.001) Pp*=10; 
   Mnoj=1/Pp;
   Symb=Symbol();
   if (MarketInfo(Symb,MODE_LOTSTEP)==0.01) DG=2;
   if (MarketInfo(Symb,MODE_LOTSTEP)==0.1)  DG=1;
   if(CommetSize>0) ArrayResize(CommentBox,CommetSize);
   for(i=0;i<CommetSize;i++) CommentBox[i]="";
   lt[0]=NormalizeDouble(lot,DG);
   step[0]=step_1;
   for(i=1;i<30;i++) 
   {
      if(i<set_2) 
      {
         lt[i]=NormalizeDouble(lt[i-1]*lot_factor_1,DG); 
         if (lt[i]>lt[0]*Layer_Multiplier) lt[i]=lt[0]*Layer_Multiplier;
         step[i]=step_1;
         }
         else
         { 
         lt[i]=NormalizeDouble(lt[i-1]*lot_factor_2,DG);
         if (lt[i]>lt[0]*Layer_Multiplier) lt[i]=lt[0]*Layer_Multiplier;
         step[i]=step_2;
         }
      if(i>=set_3-1) lt_h[i]=NormalizeDouble(lt[i]*(hedje_factor+hedje_plus*(set_3-1-i)),DG);
      if (lt_h[i]>lt[0]*Layer_Multiplier) lt_h[i]=lt[0]*Layer_Multiplier;
      }
   for(i=OrdersTotal()-1;i>=0;i--) 
   {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && OrderSymbol()==Symb) 
      {
         if(OrderMagicNumber()==magic && TimeB<OrderOpenTime()) TimeB=OrderOpenTime();
         if(OrderMagicNumber()==magic2 && TimeS<OrderOpenTime()) TimeS=OrderOpenTime();
         }
      }   
   return;
   }
//896896896869869869869869689686986986986986968869869869869689689686986986986986986968968986
void SL()
  {
   double OOP,SL;
   int b=0,s=0,tip,TicketB=0,TicketS=0;
   for(i=0; i<OrdersTotal(); i++)
     {
      if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderSymbol()==Symbol())
           {
            tip = OrderType();
            OOP = NormalizeDouble(OrderOpenPrice(),Digits);
            if(tip==OP_BUY)
              {
               b++;
               TicketB=OrderTicket();
               if(Stoploss!=0   && Bid<=OOP - Stoploss   * Point) {if(OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits),slippage,clrNONE)) continue;}
               if(Takeprofit!=0 && Bid>=OOP + Takeprofit * Point) {if(OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Bid,Digits),slippage,clrNONE)) continue;}
               if(TrailingStop>0)
                 {
                  SL=NormalizeDouble(Bid-TrailingStop*Point,Digits);
                  if(SL>=OOP+TrailingStart*Point && (TrallB==0 || TrallB+TrailingStep*Point<SL)) TrallB=SL;
                 }
              }
            if(tip==OP_SELL)
              {
               s++;
               if(Stoploss!=0   && Ask>=OOP + Stoploss   * Point) {if(OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),slippage,clrNONE)) continue;}
               if(Takeprofit!=0 && Ask<=OOP - Takeprofit * Point) {if(OrderClose(OrderTicket(),OrderLots(),NormalizeDouble(Ask,Digits),slippage,clrNONE)) continue;}
               TicketS=OrderTicket();
               if(TrailingStop>0)
                 {
                  SL=NormalizeDouble(Ask+TrailingStop*Point,Digits);
                  if(SL<=OOP-TrailingStart*Point && (TrallS==0 || TrallS-TrailingStep*Point>SL)) TrallS=SL;
                 }
              }
           }
        }
     }
   if(b!=0)
     {
      if(b>1) Comment("Трал корректно работает только с 1 ордером");
      else
      if(TrallB!=0)
        {
         Comment("Тралим ордер ",TicketB);
         DrawHline("SL Buy",TrallB,clrBlue,1);
         if(Bid<=TrallB)
           {
            if(OrderSelect(TicketB,SELECT_BY_TICKET))
               if(OrderProfit()>0)
                  if(!OrderClose(TicketB,OrderLots(),NormalizeDouble(Ask,Digits),slippage,clrRed))
                     Comment("Ошибка закрытия ордера ",GetLastError());
           }
        }
     }
   else {TrallB=0;ObjectDelete("SL Buy");}
//---
   if(s!=0)
     {
      if(s>1) Comment("Трал корректно работает только с 1 ордером");
      else
      if(TrallS!=0)
        {
         Comment("Тралим ордер ",TicketS);
         DrawHline("SL Sell",TrallS,clrRed,1);
         if(Ask>=TrallS)
           {
            if(OrderSelect(TicketS,SELECT_BY_TICKET))
               if(OrderProfit()>0)
                  if(!OrderClose(TicketS,OrderLots(),NormalizeDouble(Ask,Digits),slippage,clrRed))
                     Comment("Ошибка закрытия ордера ",GetLastError());
           }
        }
     }
   else {TrallS=0;ObjectDelete("SL Sell");}
//---
   int err;
   if(IsTesting() && OrdersTotal()==0)
     {
      double Lot=0.1;
      err=OrderSend(Symbol(),OP_BUY,Lot,NormalizeDouble(Ask,Digits),slippage,0,0,"тест",0);
      err=OrderSend(Symbol(),OP_SELL,Lot,NormalizeDouble(Bid,Digits),slippage,0,0,"тест",0);
      
     }
   
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void DrawHline(string name,double P,color clr,int WIDTH)
  {
   if(ObjectFind(name)!=-1) ObjectDelete(name);
   ObjectCreate(name,OBJ_HLINE,0,0,P,0,0,0,0);
   ObjectSet(name,OBJPROP_COLOR,clr);
   ObjectSet(name,OBJPROP_STYLE,2);
   ObjectSet(name,OBJPROP_WIDTH,WIDTH);
  }
//------------------------------------------------------------------------------------------
void PnC(string txt,int Mode)
 {
   int j;
   if(Mode!=2)
    {
      string HR=DoubleToStr(Hour(),0);    if (StringLen(HR)<2) HR="0"+HR;
      string MN=DoubleToStr(Minute(),0);  if (StringLen(MN)<2) MN="0"+MN;
      string SC=DoubleToStr(Seconds(),0); if (StringLen(SC)<2) SC="0"+SC;
      txt=HR+":"+MN+":"+SC+"; "+txt;
      Print(txt);
      if(IsTesting() && !IsVisualMode()) return;
      if (Mode>0) Alert(txt);
      for(j=CommetSize-1;j>=1;j--) CommentBox[j]=CommentBox[j-1];
      CommentBox[0]=txt;
      }
   if(CommetSize>0)
     { 
      string cm;
      for(j=CommetSize-1;j>=0;j--) if(CommentBox[j]!="") cm=cm+CommentBox[j]+"\n";
      cm=cm+"\n"+cm2;
      Comment(cm); 
      }
   }
//896896896869869869869869689686986986986986968869869869869689689686986986986986986968968986
int Fun_Error(int er)
                {
   switch(er) 
   {
      // группа 1: не прекращать попытки
      case 2: PnC("Общая ошибка",0); return(0);
      case 4: PnC("Торговый сервер занят",0); return(0);
      case 8: PnC("Слишком частые запросы",0); return(0);
      case 129: PnC("Неправильная цена",0); return(0);
      case 135: PnC("Цена изменилас",0); return(0);
      case 136: PnC("Нет цен",0); return(0);
      case 137: PnC("Брокер занят",0); return(0);
      case 138: PnC("Новые цены",0); return(0);
      case 141: PnC("Слишком много запросов",0); return(0);
      case 146: PnC("Подсистема торговли занята",0); return(0);
      // группа 2: прекращаем попытки
      case 0: PnC("Ошибка отсутствует",0); return(1);
      case 1: PnC("Нет ошибки, но результат не известен",0); return(1);
      case 3: PnC("Неправильные параметры",0); return(1);
      case 6: PnC("Нет связи с торговым сервером",0); return(1);
      case 128: PnC("Истек срок ожидания совершения сделки",0); return(1);
      case 130: PnC("Неправильные стопы",0); return(1);
      case 131: PnC("Неправильный объем",0); return(1);
      case 132: PnC("Рынок закрыт",0); return(1);
      case 133: PnC("Торговля запрещена",0); return(1);
      case 134: PnC("Недостаточно денег для совершения операции",0); return(1);
      case 139: PnC("Ордер заблокирован и уже обрабатывается",0); return(1);
      case 145: PnC("Модификация запрещена, так как ордер слишком близок к рынку",0); return(1);
      case 148: PnC("Количество открытых и отложенных ордеров достигло предела, установленного брокером",0); return(1);
      // группа 3: завершаем работу
      case 5: PnC("Старая версия клиентского терминала",1); return(2);
      case 7: PnC("Недостаточно прав",1); return(2);
      case 9: PnC("Недопустимая операция нарушающая функционирование сервера",1); return(2);
      case 64: PnC("Счет заблокирован",1); return(2);
      case 65: PnC("Неправильный номер счета",1); return(2);
      case 140: PnC("Разрешена только покупка",1); return(2);
      case 147: PnC("Использование даты истечения ордера запрещено брокером",1); return(2);
      case 149: PnC("Попытка открыть противоположную позицию к уже существующей в случае, если хеджирование запрещено",1); return(2);
      case 150: PnC("Попытка закрыть позицию по инструменту в противоречии с правилом FIFO",1); return(2);
      
      }return(0);
   }                     


