Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 6. - page 330

 
artmedia70:

There's nothing to attach it to.

You can do it here:

It is for output in string format, not for calculation.
Made a clever move from int init() deleted the hell out of it. The EA text is now normalized. Everything works fine now. artmedia70 thanks.
 
The Expert Advisor places the pending orders at a given distance from the current price and then modifies them after a given time. All goes well, but sometimes the terminal does not allow modification. Then the unmodified order should be deleted. How to do it?
 
artmedia70:

Gentlemen!!! What are you people confused about?

iFractals() returns price, not bar number of fractal.


Yeah, sometimes it's not Friday)))
 
Hello, I'm asking for help, I have a task: Determine the effectiveness of using the Commodity Channel Index technical indicator on the statistical data of the D 1 timeframe of an ordinary share of OJSC Rosneft, I can’t formulate how to write this indicator correctly for opening and closing a long and short position, I seem to be doing but the adviser refuses to compile, gives an error . Please help, this indicator needs to be applied in this listing, I present it without my x changes.
 #property copyright "Copyright © 2010, E-Commerce"
#property link        "http://e-commerce.psati.ru"
 
extern double StopLoss= 3000   ;           // SL для открываемого ордера
extern double TakeProfit= 3000 ;           // ТР для открываемого ордера
extern int TrailingStop= 100 ; 
extern double Lots      = 0.1 ;           // Жестко заданное колич. лотов
double Prots     = 0.07 ;         // Процент свободных средств
extern int SignalLine  = 5 ;           // Период расчётной МА
extern int SignalLine1  = 10 ;           // Период расчётной МА
extern int N1 = 5 ;  
extern int N2  = 10 ; 
int Bars_V       = 34 ;           // Колич.баров для расчёта скор
int Aver_Bars    = 0 ;             // Колич. баров для сглаживания
double Level     = 0.001 ;

bool    Work= true ;                       // Эксперт будет работать.
string Symb;                           // Название финанс. инструмента

int start()
  {
   int
   Period_MA=SignalLine1,
   Period_MA_1=SignalLine,
   Total,                               // Количество ордеров в окне 
   Tip=- 1 ,
   coef,                             // Тип выбран. ордера (B=0,S=1)
   Ticket;                             // Номер ордера
   double
   MA_1_t,                             // Значен. МА_1 текущее
   MA_2_t,                             // Значен. МА_2 текущее 
   Lot,                                 // Колич. лотов в выбран.ордере
   Lts,                                 // Колич. лотов в открыв.ордере
   Min_Lot,                             // Минимальное количество лотов
   Step,                               // Шаг изменения размера лота
   Free,                               // Текущие свободные средства
   One_Lot,                             // Стоимость одного лота
   Price,                               // Цена выбранного ордера
   SL,                                 // SL выбранного ордера 
   TP;                               // TP выбранного ордера
   bool
   Ans  = false ,                         // Ответ сервера после закрытия
   Cls_B= false ,                         // Критерий для закрытия  Buy
   Cls_S= false ,                         // Критерий для закрытия  Sell
   Opn_B= false ,                         // Критерий для открытия  Buy
   Opn_S= false ;                         // Критерий для открытия  Sell
   int BBars= 10000000 ;
   if ( Bars < Period_MA_1)                       // Недостаточно баров
     {
       Alert ( "Недостаточно баров в окне. Эксперт не работает." );
       return ;                                   // Выход из start()
     }
   if (Work== false )                               // Критическая ошибка
     {
       Alert ( "Критическая ошибка. Эксперт не работает." );
       return ;                                   // Выход из start()
     }
     
   // Учёт ордеров
   Symb= Symbol ();                               // Название фин.инстр.
   Total= 0 ;                                     // Количество ордеров
   for ( int i= 1 ; i<= OrdersTotal (); i++)           // Цикл перебора ордер
     {
       if ( OrderSelect (i- 1 ,SELECT_BY_POS)== true ) // Если есть следующий
        {                                       // Анализ ордеров:
         if (OrderSymbol()!=Symb) continue ;       // Не наш фин. инструм
         if (OrderType()> 1 )                     // Попался отложенный
           {
             Alert ( "Обнаружен отложенный ордер. Эксперт не работает." );
             return ;                             // Выход из start()
           }
         Total++;                               // Счётчик рыночн. орд
         if (Total> 1 )                           // Не более одного орд
           {
             Alert ( "Несколько рыночных ордеров. Эксперт не работает." );
             return ;                             // Выход из start()
           }
         Ticket=OrderTicket();                   // Номер выбранн. орд.
         Tip   =OrderType();                     // Тип выбранного орд.
         Price =OrderOpenPrice();               // Цена выбранн. орд.
         SL    =OrderStopLoss();                 // SL выбранного орд.
         TP    =OrderTakeProfit();               // TP выбранного орд.
         Lot   =OrderLots();                     // Количество лотов
        }
     }

   // Торговые критерии
   int P= Period_MA_1;             // Период расчётной МА
   int B= Bars_V;                 // Колич.баров для расчёта скорост
   int A= Aver_Bars;               // Колич. баров для сглаживания
   int Z= Period_MA;
   //double L_1=iCustom(NULL,0,"IPM",H,P,B,A,0,0);
   //double L_5=iCustom(NULL,0,"IPM",H,P,B,A,1,0);
   double Ma2_Previus,Ma3_Previus, Ma2_Current, Ma3_CurrentPrice, CurrentLine, PreviousLine, Line15,Current, Line30;
   //Ma3_Previus=iCustom(NULL,0,"444",H,P,B,A,1,1);
   //Ma2_Previus=iCustom(NULL,0,"www",P,Z,N1,N2,0,2);
  
   //Ma3_Current=iCustom(NULL,0,"444",H,P,B,A,1,2);
   // Ma2_Current=iCustom(NULL,0,"www",P,Z,N1,N2,0,1);

//ПАРАМЕТРЫ ОТКРЫТИЯ ДЛИННОЙ ПОЗИЦИИ

if ( iCCI ( Symbol (), 0 , 12 , PRICE_TYPICAL , 0 )>= 100 )
{
if ((NumberOfBarOpenLastPos()> 0 ||NumberOfBarOpenLastPos()==- 1 )&&(NumberOfBarCloseLastPos()> 0 ||NumberOfBarCloseLastPos()==- 1 ))
{ 
Opn_B= true ;
//Cls_S=true;
}
}
 //ПАРАМЕТРЫ ОТКРЫТИЯ короткой ПОЗИЦИИ    
if ( iCCI ( Symbol (), 0 , 20 , PRICE_TYPICAL , 0 )<= 100 )
{
if ((NumberOfBarOpenLastPos()> 0 ||NumberOfBarOpenLastPos()==- 1 )&&(NumberOfBarCloseLastPos()> 0 ||NumberOfBarCloseLastPos()==- 1 ))
{
Opn_S= true ; 
//Cls_B=true;   
}  
}


if (Tip== 0 ){
           if (TrailingStop> 0 )  
              {                 
               if (Bid-OrderOpenPrice()> Point *TrailingStop)
                 {
                   if (SL<Bid- Point *TrailingStop)
                    {
                     OrderModify(Ticket,OrderOpenPrice(),Bid- Point *TrailingStop,TP, 0 ,Green);
                     //return(0);
                    }
                 }
              }
}

if (Tip== 1 ){
           if (TrailingStop> 0 )  
              {                 
               if ((OrderOpenPrice()-Ask)>( Point *TrailingStop))
                 {
                   if (SL>Ask+ Point *TrailingStop)
                    {
                     OrderModify(Ticket,OrderOpenPrice(),Ask+ Point *TrailingStop,TP, 0 ,Red);
                     // return(0);
                    }
                 }
              }
}


   // Закрытие ордеров
   while ( true )                                   // Цикл закрытия орд.
     {
//длинной
if ( iCCI ( Symbol (), 0 , 12 , PRICE_TYPICAL , 0 )<= 100 ){
       if (Tip== 0 )                 // Открыт ордер Buy..
        {                                       //и есть критерий закр
         Alert ( "Попытка закрыть Buy " ,Ticket, ". Ожидание ответа.." );
         RefreshRates();                         // Обновление данных
         Ans=OrderClose(Ticket,Lot,Bid, 2 );       // Закрытие Buy
         if (Ans== true )                         // Получилось :)
           {
             Alert ( "Закрыт ордер Buy " ,Ticket);
             break ;                               // Выход из цикла закр
           }
                           
            
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
        }

// короткой       
//if (Close[i]<0)
if ( iCCI ( Symbol (), 0 , 20 , PRICE_TYPICAL , 0 )>= 100 ){
       if (Tip== 1 )                 // Открыт ордер Sell..
        {                                       // и есть критерий закр
         Alert ( "Попытка закрыть Sell " ,Ticket, ". Ожидание ответа.." );
         RefreshRates();                         // Обновление данных
         Ans=OrderClose(Ticket,Lot,Ask, 2 );       // Закрытие Sell
         if (Ans== true )                         // Получилось :)
           {
             Alert ( "Закрыт ордер Sell " ,Ticket);
             break ;                               // Выход из цикла закр
           }
                  
           
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
        }
       break ;                                     // Выход из while
     }



// Стоимость ордеров
   RefreshRates();                               // Обновление данных
   Min_Lot=MarketInfo(Symb,MODE_MINLOT);         // Миним. колич. лотов 
   Free   =AccountFreeMargin();                 // Свободн средства
   One_Lot=MarketInfo(Symb,MODE_MARGINREQUIRED); // Стоимость 1 лота
   Step   =MarketInfo(Symb,MODE_LOTSTEP);       // Шаг изменен размера
 
   if (Lots > 0 )                                 // Если заданы лоты,то 
      Lts =Lots;                                 // с ними и работаем 
   else                                          // % свободных средств
      Lts= MathFloor (Free*Prots/One_Lot/Step)*Step; // Для открытия
 
   if (Lts < Min_Lot) Lts=Min_Lot;               // Не меньше минимальн
   if (Lts*One_Lot > Free)                       // Лот дороже свободн.
     {
       Alert ( " Не хватает денег на " , Lts, " лотов" );
       return ;                                   // Выход из start()
     }
   // Открытие ордеров
   while ( true )                                   // Цикл закрытия орд.
     {
       if (Total== 0 && Opn_B== true )               // Открытых орд. нет +
        {                                       // критерий откр. Buy
         RefreshRates();          
         SL=Bid - New_Stop(StopLoss)* Point ;     // Вычисление SL откр.
         TP=Bid + New_Stop(TakeProfit)* Point ;   // Вычисление TP откр.
         Alert ( "Попытка открыть Buy. Ожидание ответа.." );
         Ticket= OrderSend (Symb,OP_BUY,Lts,Ask, 2 ,SL,TP); //Открытие Buy

         if (Ticket > 0 )                         // Получилось :)
           {
             Alert ( "Открыт ордер Buy " ,Ticket);
             return ;                             // Выход из start()
           }
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
       if (Total== 0 && Opn_S== true )               // Открытых орд. нет +
        {                                       // критерий откр. Sell
         RefreshRates();        
         SL=Ask + New_Stop(StopLoss)* Point ;     // Вычисление SL откр.
         TP=Ask - New_Stop(TakeProfit)* Point ;   // Вычисление TP откр.
         Alert ( "Попытка открыть Sell. Ожидание ответа.." );
         Ticket= OrderSend (Symb,OP_SELL,Lts,Bid, 2 ,SL,TP); //Открытие Sel
         if (Ticket > 0 )                         // Получилось :)
           {
             Alert ( "Открыт ордер Sell " ,Ticket);
             return ;                             // Выход из start()
           }
         if (Fun_Error( GetLastError ())== 1 )       // Обработка ошибок
             continue ;                           // Повторная попытка
         return ;                                 // Выход из start()
        }
       break ;                                     // Выход из while
     }
   return ;                                       // Выход из start()
  }
int Fun_Error( int Error)                         // Ф-ия обработ ошибок
  {
   switch (Error)
     {                                           // Преодолимые ошибки            
       case    4 : Alert ( "Торговый сервер занят. Пробуем ещё раз.." );
         Sleep ( 3000 );                           // Простое решение
         return ( 1 );                             // Выход из функции
       case 135 : Alert ( "Цена изменилась. Пробуем ещё раз.." );
         RefreshRates();                         // Обновим данные
         return ( 1 );                             // Выход из функции
       case 136 : Alert ( "Нет цен. Ждём новый тик.." );
         while (RefreshRates()== false )           // До нового тика
             Sleep ( 1 );                           // Задержка в цикле
         return ( 1 );                             // Выход из функции
       case 137 : Alert ( "Брокер занят. Пробуем ещё раз.." );
         Sleep ( 3000 );                           // Простое решение
         return ( 1 );                             // Выход из функции
       case 146 : Alert ( "Подсистема торговли занята. Пробуем ещё.." );
         Sleep ( 500 );                             // Простое решение
         return ( 1 );                             // Выход из функции
         // Критические ошибки
       case    2 : Alert ( "Общая ошибка." );
         return ( 0 );                             // Выход из функции
       case    5 : Alert ( "Старая версия терминала." );
         Work= false ;                             // Больше не работать
         return ( 0 );                             // Выход из функции
       case 64 : Alert ( "Счет заблокирован." );
         Work= false ;                             // Больше не работать
         return ( 0 );                             // Выход из функции
       case 133 : Alert ( "Торговля запрещена." );
         return ( 0 );                             // Выход из функции
       case 134 : Alert ( "Недостаточно денег для совершения операции." );
         return ( 0 );                             // Выход из функции
       default : Alert ( "Возникла ошибка " ,Error); // Другие варианты   
         return ( 0 );                             // Выход из функции
     }
  }
int New_Stop( int Parametr)                       // Проверка стоп-прик.
  {
   int Min_Dist=MarketInfo(Symb,MODE_STOPLEVEL); // Миним. дистанция
   if (Parametr<Min_Dist)                       // Если меньше допуст.
     {
      Parametr=Min_Dist;                         // Установим допуст.
       Alert ( "Увеличена дистанция стоп-приказа." );
     }
   return (Parametr);                             // Возврат значения
  }
 
 int NumberOfBarOpenLastPos( string sy= "0" , int tf= 0 , int op=- 1 , int mn=- 1 ) {
   datetime t;
   int i, k= OrdersTotal ();

   if (sy== "" || sy== "0" ) sy= Symbol ();
   for (i= 0 ; i<k; i++) {
   if ( OrderSelect (i, SELECT_BY_POS, MODE_TRADES)) {
   if (OrderSymbol()==sy) {
   if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
   if (op< 0 || OrderType()==op) {
   if (mn< 0 || OrderMagicNumber()==mn) {
   if (t<OrderOpenTime()) t=OrderOpenTime();
  }
  }
  }
  }
  }
  }
   return (iBarShift(sy, tf, t, True));
}
int NumberOfBarCloseLastPos( string sy= "0" , int tf= 0 , int op=- 1 , int mn=- 1 ) {
   datetime t;
   int       i, k=OrdersHistoryTotal();

   if (sy== "" || sy== "0" ) sy= Symbol ();
   for (i= 0 ; i<k; i++) {
     if ( OrderSelect (i, SELECT_BY_POS, MODE_HISTORY)) {
       if (OrderSymbol()==sy) {
         if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
           if (op< 0 || OrderType()==op) {
             if (mn< 0 || OrderMagicNumber()==mn) {
               if (t<OrderCloseTime()) t=OrderCloseTime();
            }
          }
        }
      }
    }
  }
   return (iBarShift(sy, tf, t, True));
}
 
niformalka:
Hello, I beg for help, I have a task: Determine the effectiveness of the technical indicator Commodity Channel Index on the statistical data timeframe D1 ordinary shares of JSC "Rosneft", I can not formulate how to properly write this indicator to open and close a long and short positions, I think I do, but the council refuses to compile, gives an error. I think I need help here, I need to apply this indicator to this listing but I have not changed it.
So this is your advisor, not the indicator...Compilation without errors is going on....Now I will play with your code..... hypothetical....
 
Sepulca:
So it's an EA, not an indicator...Compiling goes without errors....Now I'll play with your code..... hypotest....


I need to apply exactly the indicator I need in my EA, namely icc, it compiles the source code
 
alsu:

Yeah, it's not like it's Friday))

What's wrong with it?

//+------------------------------------------------------------------+
//|                                                  TestFractal.mq4 |
//|                               Copyright 2013, Artyom A. Trishkin |
//|                       https://www.mql5.com/ru/users/artmedia70 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, Artyom A. Trishkin"
#property link      "https://www.mql5.com/ru/users/artmedia70"
#property version   "1.00"
#property  strict
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   for(int i=3; i<300; i++) {
      double fu=iFractals(Symbol(),Period(),MODE_UPPER,i);
      double fd=iFractals(Symbol(),Period(),MODE_LOWER,i);
      if(fu>0) Print("Значение UP на баре "+(string)i+" = "+DoubleToStr(fu,Digits));
      if(fd>0) Print("Значение DN на баре "+(string)i+" = "+DoubleToStr(fd,Digits));
      }
  }
//+------------------------------------------------------------------+

The price returns...

 

Let's start with the main thing, it's not really wise to go over orders from zero. It's better to start with the last one

for(int i=OrderTotal-1; i>=0; i--)          // Цикл перебора ордер
We don't want to get into a situation where we have closed/deleted the zero order and there are more orders on it. If you use the last order on the account, nothing bad happens.
 
Sepulca:

Начнем с главного, не совсем грамотно перебирать ордера с нулевого. Лучше с последнего

Чтобы не возникало ситуации, когда нулевой по счету закрыли/удалили а там ещё ордера есть. всё переколбасилось. Когда действуете с последним по счёту ничего страшного не происходит.


the teacher proves that nothing needs to be changed in the code, except for the lines with opening and closing short and long positions, I did something like this but it does not compile
if ((iCCI(Symbol,0,14,PRICE_TYPICAL,0)<100)&&(iCCI(Symbol,0,14,PRICE_TYPICAL,0)<-100)) 

 
Sepulca:

Let's start with the main thing, it's not really wise to go over orders from zero. It's better to start with the last one

So that we don't get into the situation where we have closed/deleted the zero order and there are more orders on it. When you act on the last order on the account, nothing bad happens.

You may be using the functions of Igor Kim without looking at them.
Reason: