Помогите, пожалуйста, дописать советник по индикатору

 

Нужно доработать несколько пунктов:

1. Учитывать сигнал только с текущего бара

2. Только 1 Trade на один бар

 

Вот исходный код: 

extern string    A1 = "Объем сделки";
extern double    Lots = 0.1;
extern string    A2 = "Параметры индикатора";
extern string    A3 = "Stop Loss";
extern double    StopLoss = 250;
extern string    A4 = "Take Profit";
extern double    TakeProfit = 0;
extern string    A5 = "Дополнительные настройки";
extern string    OpenOrderSound = "ok.wav";
extern int       MagicNumber = 116900;

int Signal,                                      
    Ticket,                                      
    Type;                                         

bool Activate, FreeMarginAlert, FatalError;
double Tick, Spread, StopLevel, MinLot, MaxLot, LotStep, FreezeLevel;
datetime LastBar, LastSignal;

int init()
 {FatalError = False;
  Tick = MarketInfo(Symbol(), MODE_TICKSIZE);                           
  Spread = ND(MarketInfo(Symbol(), MODE_SPREAD)*Point);                 
  StopLevel = ND(MarketInfo(Symbol(), MODE_STOPLEVEL)*Point);  
  FreezeLevel = ND(MarketInfo(Symbol(), MODE_FREEZELEVEL)*Point);   
  MinLot = MarketInfo(Symbol(), MODE_MINLOT);    
  MaxLot = MarketInfo(Symbol(), MODE_MAXLOT);   
  LotStep = MarketInfo(Symbol(), MODE_LOTSTEP);          
   if (StopLoss < 0)
     {Alert("Значение StopLoss не может быть отрицательным. Я не буду пахать, пень неотесанный!");
      return(0);}
   if (TakeProfit < 0)
     {Alert("Значение TakeProfit не может быть отрицательным. Начни с азов, чайник!");
      return(0);}
   
   LastBar = 0;
   LastSignal = 0;
   Activate = True;
   return(0);}

int deinit()
  {return(0);}

double GetLots()
  {return(LotRound(Lots));}

double LotRound(double L)
  {return(MathRound(MathMin(MathMax(L, MinLot), MaxLot)/LotStep)*LotStep);}

double ND(double A)
  {return(NormalizeDouble(A, Digits));}  

string ErrorToString(int Error)
  {switch(Error)
     {case 2: return("зафиксирована общая ошибка, дуй в техподдержку!"); 
      case 5: return("старая версия терминала, обнови его, старпер!"); 
      case 6: return("нет связи с сервером, попробуй перезапустить терминал или подключи скоростной интернет, село!"); 
      case 64: return("счет заблокирован, бегом в техподдержку, лузер!");
      case 132: return("рынок закрыт, отдыхай, трудяга!"); 
      case 133: return("торговля запрещена, потерпи!"); 
      case 149: return("запрещено локирование, понял?");}}

bool WaitForTradeContext()
  {int P = 0;
   while(IsTradeContextBusy() && P < 5)
     {P++;
      Sleep(1000);}
   if (P == 5)
     return(False);
   return(True);}

int OpenOrderCorrect(int Type, double Lot, double Price, double SL, double TP, 
                     bool Redefinition = True)
{if(AccountFreeMarginCheck(Symbol(), OP_BUY, Lot) <= 0 || GetLastError() == 134) 
  {if(!FreeMarginAlert)
    {Print("Недостаточно средств для открытия позиций, нищий! Свободные средства = ", 
           AccountFreeMargin());
     FreeMarginAlert = True;} 
   return(5);}
 FreeMarginAlert = False;  

 RefreshRates();
 switch (Type)
   {case OP_BUY: 
                string S = "BUY"; 
                if (MathAbs(Price-Ask)/Point > 3)
                  if (Redefinition) Price = ND(Ask);
                  else              return(2);
                if (ND(TP-Bid) <= StopLevel && TP != 0)
                  if (Redefinition) TP = ND(Bid+StopLevel+Tick);
                  else              return(4);
                if (ND(Bid-SL) <= StopLevel)
                  if (Redefinition) SL = ND(Bid-StopLevel-Tick);
                  else              return(3);
                break;
    case OP_SELL: 
                 S = "SELL"; 
                 if (MathAbs(Price-Bid)/Point > 3)
                   if (Redefinition) Price = ND(Bid);
                   else              return(2);
                 if (ND(Ask-TP) <= StopLevel) 
                   if (Redefinition) TP = ND(Ask-StopLevel-Tick);
                   else              return(4);
                 if (ND(SL-Ask) <= StopLevel && SL != 0)
                   if (Redefinition) SL = ND(Ask+StopLevel+Tick);
                   else              return(3);
                 break;
    case OP_BUYSTOP: 
                    S = "BUYSTOP";
                    if (ND(Price-Ask) <= StopLevel)
                      if (Redefinition) Price = ND(Ask+StopLevel+Tick);
                      else              return(2);
                    if (ND(TP-Price) <= StopLevel && TP != 0)
                      if (Redefinition) TP = ND(Price+StopLevel+Tick);
                      else              return(4);
                    if (ND(Price-SL) <= StopLevel)
                      if (Redefinition) SL = ND(Price-StopLevel-Tick);
                      else              return(3);
                    break;
    case OP_SELLSTOP: 
                     S = "SELLSTOP";
                     if (ND(Bid-Price) <= StopLevel)
                       if (Redefinition) Price = ND(Bid-StopLevel-Tick);
                       else              return(2);
                     if (ND(Price-TP) <= StopLevel)
                       if (Redefinition) TP = ND(Price-StopLevel-Tick);
                       else              return(4);
                     if (ND(SL-Price) <= StopLevel && SL != 0)
                       if (Redefinition) SL = ND(Price+StopLevel+Tick);
                       else              return(3);
                     break;
    case OP_BUYLIMIT: 
                     S = "BUYLIMIT";
                     if (ND(Ask-Price) <= StopLevel)
                      if (Redefinition) Price = ND(Ask-StopLevel-Tick);
                      else              return(2);
                     if (ND(TP-Price) <= StopLevel && TP != 0)
                       if (Redefinition) TP = ND(Price+StopLevel+Tick);
                       else              return(4);
                     if (ND(Price-SL) <= StopLevel)
                       if (Redefinition) SL = ND(Price-StopLevel-Tick);
                       else              return(3);
                     break;
    case OP_SELLLIMIT: 
                     S = "SELLLIMIT";
                     if (ND(Price - Bid) <= StopLevel) 
                       if (Redefinition) Price = ND(Bid+StopLevel+Tick);
                       else              return(2);
                     if (ND(Price-TP) <= StopLevel)
                       if (Redefinition) TP = ND(Price-StopLevel-Tick);
                       else              return(4);
                     if (ND(SL-Price) <= StopLevel && SL != 0)
                       if (Redefinition) SL = ND(Price+StopLevel+Tick);
                       else              return(3);
                     break;}

 if(WaitForTradeContext())
   {Comment("Отиравлен запрос на открытие ордера ", S, " ...");  
    int ticket=OrderSend(Symbol(), Type, Lot, Price, 3, 
               SL, TP, NULL, MagicNumber, 0);
    if(ticket<0)
      {int Error = GetLastError();
       if(Error == 2 || Error == 5 || Error == 6 || Error == 64 
          || Error == 132 || Error == 133 || Error == 149)    
         {Comment("Фатальная ошибка при открытии позиции, т. к. "+
                   ErrorToString(Error)+" Советник отключен!");
          FatalError = True;}
        else 
         Comment("Ошибка открытия позиции ", S, ": ", Error);      
       return(1);}

    Comment("Позиция ", S, " успешно открыта! Поздравляю!");
    PlaySound(OpenOrderSound); 
    return(0);}
  else
   {Comment("Время ожидания освобождения торгового потока истекло!");
    return(1);}}

double NP(double A)
  {return(MathRound(A/Tick)*Tick);}  

void GetSignal()
 {Signal = 0;
  double up_sig = iCustom(NULL, 0, "", , , 3, 0);
  double dn_sig = iCustom(NULL, 0, "", , , 2, 0);
   if (up_sig != EMPTY_VALUE)
    Signal = 1;                                                         
   if (dn_sig != EMPTY_VALUE)
    Signal = -1;}     
    
void FindOrders()
  {int total = OrdersTotal() - 1;
   Ticket = -1;
   Type = -1;
   for (int i = total; i >= 0; i--)               
      if (OrderSelect(i, SELECT_BY_POS))           
         if (OrderMagicNumber() == MagicNumber && OrderSymbol() == Symbol() && OrderType() < 2)
           {Ticket = OrderTicket();                
            Type = OrderType();}}

bool CloseDeal(int ticket) 
  {if (OrderSelect(ticket, SELECT_BY_TICKET) &&    
       OrderCloseTime() == 0)                      
      if (WaitForTradeContext())                
        {if (OrderType() == OP_BUY)                
            double Price = MarketInfo(Symbol(), MODE_BID);
         else                                     
            Price = MarketInfo(Symbol(), MODE_ASK);
         if (!OrderClose(OrderTicket(), OrderLots(), NP(Price), 3))
            return(False);}    
      else
         return(false);
   return(True);}     

double GetLevel(double value, double price, int koef)
  {if (value == 0)                          
      return(0);}                                  
      
bool Trade()
  {FindOrders();                               
   if (Signal > 0)               
     {if (Type == OP_SELL && Type == OP_SELLLIMIT)                         
         if (!CloseDeal(Ticket))                  
            return(false);                         
      double sl = GetLevel(StopLoss, Ask, -1);
      double tp = GetLevel(StopLoss, Ask, 1); 
      if (OpenOrderCorrect(OP_BUY, GetLots(), NP(Ask), sl, tp) != 0)
      ObjectDelete(Signal);
         return(False);}       
   
   if (Signal < 0)             
     {if (Type == OP_BUY && Type == OP_BUYLIMIT)                        
         if (!CloseDeal(Ticket))                
            return(false);                     
      sl = GetLevel(StopLoss, Bid, 1);
      tp = GetLevel(StopLoss, Bid, -1);
      if (OpenOrderCorrect(OP_SELL, GetLots(), NP(Bid), sl, tp) != 0)
      ObjectDelete(Signal);
         return(False);}       
   return(True);}

int start()
  {if (!Activate || FatalError) return(0);
   if (LastBar == Time[0])                        
      return(0);                                   
   if (!IsTesting())
     {Tick = MarketInfo(Symbol(), MODE_TICKSIZE);    
      Spread = ND(MarketInfo(Symbol(), MODE_SPREAD)*Point);
      StopLevel = ND(MarketInfo(Symbol(), MODE_STOPLEVEL)*Point);
      FreezeLevel = ND(MarketInfo(Symbol(), MODE_FREEZELEVEL)*Point);} 
   if (LastSignal != Time[0])                     
     {GetSignal();                                
      LastSignal = Time[0];}                                              
   if (Signal != 0)                              
      if (!Trade()) return(0);                  
   LastBar = Time[0];

   return(0);}

Причина обращения: