extern int TIK=            50; //тик до которого разрешен вход
extern double Lots =       0.1;//лот при DDEP =0
extern double DDEP =       0.3;// доля св. средств в расчёте лота
extern double Max_Lot =    1000;
extern double Klot =       2;//множитель лота отложника
extern int Stop_Loss =     15;
extern double TrailingStopLoss = 10 ;//трал
extern int TrailingStep =        10 ;//шаг трала
extern int PIPCOMIS =      6;// пипы комиссии ( при её наличии )
extern int Pip_Dist =      150;//дистанция цены от ма в пип
extern int METODma =       2; //метод ма
extern int delta_Dist =    20;//увеличение дист. при увеличении атр
extern int Pma =           18;//период ма
extern double Uwpr =      -50;//порог впр 
extern double TakeProfit = 500;
extern double TIME =       11;//время жизнм отложника
extern double SPREAD =     12;//макс. разрешённый спред
extern double STOP_level = 20;//макс. разрешённый уровень стопов
extern int slip =          10;//слиппейдж
extern bool DELETE =       true;//удаление отложников
extern bool ATR =          true;//вход по атр
extern bool OP_STOP =      true;//разрешение отложников
bool Usa_Trailing =        true;
extern int BUY=            1;//флаг разрешения
extern int SELL=           1;//флаг разрешения
extern string News = "PAUSE NEWS:";
extern bool PAUSE_NEWS =   false;//пауза торговли
extern double HOUR_START_PAUSE =17;//час начала паузы
extern double HOUR_END_PAUSE   = 10;//час окончания паузы
extern double DEI_START_PAUSE  = 5;//день начала паузы
extern double DEI_END_PAUSE    = 1;//день окончания паузы
extern double START_PAUSE      = 0;//время начала ежедневного перерыва при > 0
extern double END_PAUSE        = 6;//время окончания перерыва
extern int MagicNumber =       9578;

int start() {
   int U=0,R=1,ZB=0,ZS=0;
   double MG,Min_Lot,Lotti,T=0,T1=0,K=1,HN,LN,J=1,Pip_DistanzaB=Pip_Dist,Pip_DistanzaS=Pip_Dist;
//..........................................................
    for(int q = 0; q < OrdersTotal(); q++)
   {
    
    if(!OrderSelect(q, SELECT_BY_POS, MODE_TRADES)) continue;
    if(OrderSymbol() != Symbol()) continue;
    if(OrderMagicNumber() != MagicNumber) continue;    
    if(OrderType()==OP_BUY&&OrderStopLoss()>OrderOpenPrice()){T=1;
    }
    if(OrderType()==OP_SELL&&OrderStopLoss()<OrderOpenPrice()){T1=1;
    }
    if(DELETE == true&&OrderType()==OP_BUYSTOP&&T1==1)OrderDelete(OrderTicket(),CLR_NONE);
    if(DELETE == true&&OrderType()==OP_SELLSTOP&&T==1)OrderDelete(OrderTicket(),CLR_NONE);
   }
//........................................................................................
        int m;
        if(Lots>0)
        {
        if(AccountFreeMargin()>AccountMargin())MG=AccountFreeMargin();
        if(AccountFreeMargin()<AccountMargin())MG=0;
        Min_Lot = MarketInfo(Symbol(), MODE_MINLOT);
              
        if(DDEP>0)
        {
          m=MG/MarketInfo (Symbol(), MODE_MARGINREQUIRED)*DDEP/Min_Lot;
          Lotti = m*Min_Lot;

        if(MG==0)Lotti =0;
        if(MG>0&&Lotti < Min_Lot)
        Lotti =Min_Lot;     
        
        if(MG>0&&Lotti > MarketInfo (Symbol(), MODE_MAXLOT))
        Lotti = MarketInfo (Symbol(), MODE_MAXLOT);     
        
        if(MG>0&&Lotti > Max_Lot)
        Lotti =Max_Lot;       
        }
        }
        if(DDEP==0)Lotti= Lots;
 //.....................................................
 
  // пїЅпїЅпїЅпїЅпїЅ......................................................
   if(Hour()>= START_PAUSE&&Hour()<END_PAUSE&& START_PAUSE>0)
    R=0;
  if(DayOfWeek()>=DEI_START_PAUSE&&Hour()>=HOUR_START_PAUSE && PAUSE_NEWS == true)
    R=0;
  if(DayOfWeek()<=DEI_END_PAUSE&&Hour()<=HOUR_END_PAUSE && PAUSE_NEWS == true )
    R=0;
     
   // Orari per Tradare ----------------------------------
   // if(Lots>0) 
   
   if(BUY==1||SELL==1)      
   {
   bool Sto_Operando;
   double V = iATR(NULL,60,1,0);
   double V1 = iATR(NULL,60,1,1);
   double Media_Lunga = iMA(NULL,1, Pma, 0, METODma, PRICE_OPEN, 0);
   double Media_Lunga1 = iMA(NULL,1, Pma, 0, METODma, PRICE_OPEN, 0);
   double Media_Prezzo = iMA(NULL,1, 1, 0, 1, PRICE_MEDIAN, 0);
   double Media_Prezzo_2 = iMA(NULL,1, 1, 0, 1, PRICE_CLOSE, 0);
   double Media_Prezzo_3 = iMA(NULL,1, 1, 0, 1, PRICE_CLOSE, 1);
   double F=iForce(NULL,1,1,0,0,0);
   double F1=iForce(NULL,1,1,0,0,1);
   double C=iClose(NULL,1,0);
   double O=iOpen(NULL,1,0);
   double W=iWPR(NULL,1,35,0);
   double W1=iWPR(NULL,1,35,1);
   double WP=iWPR(NULL,1,1,0);
   double WP1=iWPR(NULL,1,1,1);
   double D = iATR(NULL,1440,7,0);
   double D1 = iATR(NULL,1440,7,1);
   double N = iATR(NULL,240,7,0);
   double N1 = iATR(NULL,240,7,1);
   if(ATR==true&&D>0.014||D>D1){Pip_DistanzaB=Pip_Dist+delta_Dist;Pip_DistanzaS=Pip_Dist+delta_Dist;}
   if (OrdersTotal() < 1) ObjectDelete("OrderStopline");
   double Lotti_da_Usare; 
   if (Lotti_da_Usare < Lotti) Lotti_da_Usare = Lotti;
  
   if (Lotti_da_Usare > MarketInfo(Symbol(), MODE_MAXLOT)) Lotti_da_Usare = MarketInfo(Symbol(), MODE_MAXLOT);
   if (Lotti_da_Usare < MarketInfo(Symbol(), MODE_MINLOT)) Lotti_da_Usare = MarketInfo(Symbol(), MODE_MINLOT);
 
   double Spread = MarketInfo(Symbol(), MODE_SPREAD) * Point;
   int Stop_Level = MarketInfo(Symbol(), MODE_STOPLEVEL);
   Comment("Livello_Degli_Stop=", Stop_Level);
   if (Stop_Level < Stop_Loss) Stop_Level = Stop_Loss;
   if (Stop_Level > Stop_Loss) Lotti_da_Usare = NormalizeDouble(Lotti_da_Usare / 2.0, 2);
   int Ordini_Aperti = 0; 
   int Ordini_Totali = OrdersTotal();
   for (Ordini_Aperti = 0; Ordini_Aperti <= Ordini_Totali; Ordini_Aperti++) {
      OrderSelect(Ordini_Aperti, SELECT_BY_POS, MODE_TRADES);
      if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber) Sto_Operando = TRUE;
   }
   if (Usa_Trailing) {
      TrailingPositions(TrailingStopLoss, TrailingStep, MagicNumber);
   }
 
   if(SPREAD*Point<Ask-Bid){R=0;J=0;}
   if(STOP_level<MarketInfo(Symbol(), MODE_STOPLEVEL))R=0;
    
   if(OrderType()==OP_BUY&&OrderStopLoss()==0&&OrderMagicNumber()==MagicNumber)
   OrderModify(OrderTicket(),OrderOpenPrice(),Bid - Stop_Loss * Point,0,0,CLR_NONE);
   if(OrderType()==OP_SELL&&OrderStopLoss()==0&&OrderMagicNumber()==MagicNumber)
   OrderModify(OrderTicket(),OrderOpenPrice(),Ask + Stop_Loss * Point,0,0,CLR_NONE);

             
//......................................................................................
   if(DDEP==0)Lotti_da_Usare = Lots ;
   if(Sto_Operando == FALSE)U=1;
   if(OrdersTotal()==0||OrderOpenTime()<Time[0])U=1; 
   if (U==1)
      {
         if (Volume[0]<TIK&&BUY==1&&ZB==0&&R==1&&Media_Prezzo_3 < Media_Prezzo_2 && Media_Prezzo_2 > Media_Prezzo && Media_Prezzo_2 < Media_Lunga - Pip_DistanzaB * Point
         &&W<Uwpr&&F>0&&F1<0&&WP>-50&&WP1<-50)
         {OrderSend(Symbol(), OP_BUY, Lotti_da_Usare,Ask, slip,0,0, "AT3", MagicNumber, 0, Green);
         if(OP_STOP==true&&N>N1&&V>V1)OrderSend(Symbol(), OP_SELLSTOP,Klot * Lotti_da_Usare, Bid-Stop_Loss * Point, slip,Bid ,0, "", MagicNumber,TimeCurrent()+TIME*60, Red);
         }
         if (Volume[0]<TIK&&SELL==1&&ZS==0&&R==1&&Media_Prezzo_3 > Media_Prezzo_2 && Media_Prezzo_2 < Media_Prezzo && Media_Prezzo_2 > Media_Lunga1 + Pip_DistanzaS * Point
         &&W>Uwpr&&F<0&&F1>0&&WP<-50&&WP1>-50)
         {OrderSend(Symbol(), OP_SELL, Lotti_da_Usare,Bid, slip,0,0, "AT3", MagicNumber, 0, Red);
         if(OP_STOP==true&&N>N1&&V>V1)OrderSend(Symbol(), OP_BUYSTOP, Klot * Lotti_da_Usare, Ask+ Stop_Loss * Point, slip,Ask ,0, "", MagicNumber, TimeCurrent()+TIME*60, Green);  
         }
     }
   return (0);
  }
}


void TrailingPositions(int trailingStopLoss, int trailingStep, int magicNumber) {
   double bid = 0;
   double ask = 0;
   
   for (int i = 0; i < OrdersTotal(); i++) {
      if (!(OrderSelect(i, SELECT_BY_POS)) || OrderSymbol() != Symbol() || OrderMagicNumber() != magicNumber) {
         continue;
      }
      
      bid = MarketInfo(OrderSymbol(), MODE_BID);
      ask = MarketInfo(OrderSymbol(), MODE_ASK);
      
      if (OrderType() == OP_BUY) {
         if (bid - OrderOpenPrice() > (trailingStopLoss+PIPCOMIS) * Point) {           
            if (OrderStopLoss() < bid - (trailingStopLoss + trailingStep) * Point || OrderStopLoss() == 0) {
               OrderModify(OrderTicket(), OrderOpenPrice(), bid - trailingStopLoss * Point, OrderTakeProfit(), OrderExpiration());
            }
         }
      } else if (OrderType() == OP_SELL) {
         if (OrderOpenPrice() - ask > (trailingStopLoss+PIPCOMIS) * Point) {           
            if (OrderStopLoss() > ask + (trailingStopLoss + trailingStep) * Point || OrderStopLoss() == 0) {
               OrderModify(OrderTicket(), OrderOpenPrice(), ask + trailingStopLoss * Point, OrderTakeProfit(), OrderExpiration());
            }
         }
      }
   }

}

 
 
 