[ARCHIVE] Any rookie question, so as not to clutter up the forum. Professionals, don't pass by. Nowhere without you - 3. - page 557

 
T-G:

Hello, question about order lifetime, I need an order to "live" for 2 minutes

Why such a construction gives error 3 - why and how to correct it?

The order should live for at least 15 minutes. If less is needed, then kill it with OrderDelete
 
orb:

I see, so far it's easier for me to write this way.

Can you tell me how to get rid of while being executed one more time?



There is no such thing as "easier" - you don't write " tell me how to get rid of while SOON...". "And in the code, you have to keep in mind that everything you've written should be understood by a dumb machine.

So there are two ways: right and wrong.

I understand Lazy to rewrite it correctly, Lazy to understand the rules, so tell me how long you've been trying to write this thing into a file? Three weeks...

 
Hello, could you tell me how to write a condition: if an open position(no matter how many, numbering is not needed) closes one or more profitable positions, how do I open a new one after that?
 
Stasjan:
Hello, advise how to write a condition: if an open position (no matter how many, numbering is not needed) closes one or more profitable, how to open a new position (one) after that?


Edit for yourself:

//---Поиск последнего отработавшего ордера для открытия очередной позиции ---   
   for (orderIndex = (OrdersHistoryTotal() - 1); orderIndex >= 0; orderIndex--)
   {   
      if (!OrderSelect(orderIndex, SELECT_BY_POS, MODE_HISTORY)) {Print("Ошибка при доступе к исторической базе (",GetLastError(),")");continue;}   
      if ((OrderSymbol() != Symbol()) || (OrderMagicNumber() != MagicNumber))  continue;              
   //------------------------- Принимаем в расчет только ордер, закрытый cамым крайним -----------------------
      if (time<OrderCloseTime())     //(сравниваем его с хранящимся в пероеменной time) 
        {
         time=OrderCloseTime();     //если время закрытия ордера больше - ложим его в переменную     
         int lastType = OrderType();
         double lastLots = OrderLots();
         double lastProfit = OrderProfit() + OrderSwap();
         
         // Анализ только что закрывшегося ордера      
         if (lastProfit >= 0.0)
         {
  //---Ордер закрылся с прибылью - обнуляем счетчик итераций, счетчик для подсчета последовательного убытка позиций колен лавины,
  //---текущий и суммарный убыток и открываемся стартовым лотом по тренду                 
            Sum_Loss=0;    
            Iteration = 0; 
            if (Lot(StopLossPips)==false) //Функции  передаем ширину накала 
           {
              Comment("Пополните счет. Не хватает средств на минимальный лот. Советник остановлен.");   // Если средств не хватает на мин, то выход
              Print ("Пополните счет. Не хватает средств на минимальный лот. Lots_New = ",Lots_New, " AccountFreeMargin() = ", AccountFreeMargin() ); 
                                                                                                        // Если средств не хватает на мин, то выход
              return (0);
           }
            
          // Ордер закрылся с прибылью, открываемся стартовым лотом                     
                                                                        // if (iOpen(Symbol(),signal_period,1)<iClose(Symbol(),signal_period,1))
           if(OsMA_1>0 && OsMA_2<0)
              switch(Filter.Hour)  // торги по времени Да=1/Нет=0
               {
                 case 0:  WmOrderSend(Symbol(), OP_BUY, Lots_New, Ask, 0, 0, "старт после профита", MagicNumber); break; 
                 case 1:  if (TimeHour(TimeCurrent()) >= Start && TimeHour(TimeCurrent()) <  End)WmOrderSend(Symbol(), OP_BUY, Lots_New, Ask, 0, 0, "старт после профита", MagicNumber); break; 
               } 
            
                
           if(OsMA_1<0 && OsMA_2>0)  
              switch(Filter.Hour)  // торги по времени Да=1/Нет=0                    
               {
                 case 0:  WmOrderSend(Symbol(), OP_SELL, Lots_New, Bid, 0, 0, "старт после профита", MagicNumber); break;
                 case 1:  if (TimeHour(TimeCurrent()) >= Start && TimeHour(TimeCurrent()) <  End)WmOrderSend(Symbol(), OP_SELL, Lots_New, Bid, 0, 0, "старт после профита", MagicNumber); break;
               }         
         }
         else
         {
            // Ордер закрылся с убытком - открываемся в ОБРАТНОМ направлении c увеличением объема позиции в соотв-ии с вариантом ММ, если 
            // количество итераций не выше максимального                                 
           if (Iteration <= Max_Iteration && VAR_MM == 0)                  
              // Последующие лоты открываются по множителю в соответствие с числами ФИБО           
               switch(Iteration)                                  // Заголовок switch 
                   {                                              // Начало тела switch                  
                     case 1 : Lots_New = lastLots * 1; lots = lastLots; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );break; //расчет нового объема       
                     case 2 : Lots_New = lots * 2;    Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;   
                     case 3 : Lots_New = lots * 3;    Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;      
                     case 4 : Lots_New = lots * 5;    Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;  
                     case 5 : Lots_New = lots * 8;    Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;     
                     case 6 : Lots_New = lots * 13;   Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;      
                     case 7 : Lots_New = lots * 21;   Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;     
                     case 8 : Lots_New = lots * 34;   Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;         
                     case 9 : Lots_New = lots * 55;   Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;           
                     case 10: Lots_New = lots * 89;   Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break; 
                     case 11: Lots_New = lots * 144;  Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;               
                     case 12: Lots_New = lots * 233;  Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;               
                     case 13: Lots_New = lots * 377;  Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;               
                     case 14: Lots_New = lots * 610;  Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;  
                     case 15: Lots_New = lots * 987;  Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;               
                     case 16: Lots_New = lots * 1597; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );  break;                            
                     default: Lots_New = lots * 2584; Print("Iteration = ", Iteration, " Lots_New = ", Lots_New );   
                   }                                    // Конец тела switch      
                    
         
            
 // ---------НОРМАЛИЗУЕМ НОВЫЕ РАСЧЕТНЫЕ ЛОТЫ И ОТКРЫВАЕМ ОЧЕРЕДНУЮ ПОЗИЦИЮ...            
                    Lots_New = NormalizeLots(Lots_New);
                    if (lastType == OP_SELL) WmOrderSend(Symbol(), OP_BUY, Lots_New, Ask, 0, 0, "итерация" , MagicNumber);
                    if (lastType == OP_BUY)  WmOrderSend(Symbol(), OP_SELL,Lots_New, Bid, 0, 0, "итерация" , MagicNumber);                           
    } // к еlse - конец работы после предыдущего убыточного закрытого ордера         
         return (0);
      }    // к  if (time<OrderCloseTime())  - конец анализа и торгов по итогам закрытия самого свежего ордера  
      
// Найден закрытый ордер, но он старый      
      break;
   }       // выход из цикла по истории ордеров
   
 
FAQ:


there's no such thing as "easier" - you don't write "tell me how to get rid of it while you're doing it... "You have to keep in mind that everything you've written should be understood by a dumb piece of hardware.

So there are two ways: right and wrong.

I also understand the VERY lazy to rewrite correctly, VERY lazy to understand the rules, so tell me how long you've been pestering your topic with writing to a file? Three weeks...

I solve problems as they arise, the Expert Advisor I program from January 10. It has been 4 weeks. I have been trying to program in MQL since January 6.
 
orb:
i solve problems as they arise, the Expert Advisor i am programming since january 10. it has been 4 weeks. i have been trying to program in MQL since january 6.
You have to write the principle correctly. the data on the input, on the output, what is in the main block. and then optimize the code. over time, this will become a habit, just the optimization and correct writing, and i may understand you and be like you, who is a newbie and is not optimizing.
 
Roman thanks, but can't figure out where half the variables came from as not all the code
 
Stasjan:
Roman thanks, but can't figure out where half the variables came from as not all the code
#include <stdlib.mqh>
#include <stderror.mqh>
//#include <dynamic_channel.mqh>             // динамический канал
//#include <TrailingByFractals_LAVINA.mqh>
//#include <TrailingByFractals.mqh>
//
// Внешние переменные (оптимизируются)
extern string A0 = "Параметры ММ";
extern double Lots = 0.1;         // Стартовый лот
extern  double MaxRisk = 0;       // риск на капитал в %
                                  // рассчитываем объем позиции взависимости от размера стопа, при заданном риске
                                  // например при депо 10 000 риск 1% при стопе 100 пп это будет примерно лот 0.1,
                                  // при стопе 200 пп уже лот должен быть 0.05, для того чтобы риск 1% остался на том же уровне
extern int MaxLoss = 90;          // Максимально допустимая просадка в процентах от баланса

extern double StopLoss = 0;       // Стоплосс в пипсах - для пятизнака для йены, золота, серебра...
int TakeProfitPips = 0;           // Тейкпрофит в пипсах 

extern int Period_ATR = 30;       // значение АТР для расчета динамического канала
extern double Mul_TP = 4.0;       // целевая прибыль в единицах волатильности (АТР)
extern double Mul_Sl = 0.8;       // защитная остановка с последующим переворотом при ее сработке уже 
                                  // увеличенным лотом в единицах волатильности (АТР)

extern int Max_Iteration = 36;    // Максимальное количество итераций (ордеров) в мартине 
extern int k = 2;                 // с какой итерации тралим
extern int VAR_MM = 0;            // используемый вариант усреднения в соотв-ии: множитель с числами ФИБО = 0 / множитель по арифметической прогрессии = 1
                                  // 2 - классический мартин - удвоение предыдущего объема с 3-его усреднения  

extern string Trailing = "---------- Параметры трала";
extern int UseTrailing = 1;       // Использовать = 1/не использовать = 0 трал  
extern int  type = 0;             // вид трала - возможные значения: 0 - простой, 1 - по фракталам, 2 - по теням N свечей.   
extern bool trlinloss = false;    // Тралим только профит для всех видов тралов

extern string A1 = "Параметры простого трала,пo фракталам,теням N баров,каналу,МА,SAR";
extern int  TralingStop = 1000;   // дистанция простого трала в положительной зоне (пункты)
extern int  indent = 100;         // отступ (пунктов) при трале по фракталам, теням N свечей, ценовому каналу, МА,SAR
extern int  bars_n = 10;          // количество баров, для трала по их теням (от 1 и больше) или расчета границ канала 
     

extern string A2 = "Таймфрейм, время работы и параметры технических индикаторов";
//extern int t_trend_period =6;   // 1-М1, 2-М5, 3-М15, 4-М30, 5-Н1...-для старшего фильтра, внутри которого работаем
extern int s_trend_period = 3;    //  PERIOD_M1 1       1 минута
                                  //  PERIOD_M5 5       5 минут
                                  //  PERIOD_M15        15      15 минут
                                  //  PERIOD_M30        30      30 минут
                                  //  PERIOD_H1 60      1 час
                                  //  PERIOD_H4 240     4 часа
                                  //  PERIOD_D1 1440    1 день
                                  //  PERIOD_W1 10080   1 неделя
                                  //  PERIOD_MN1        43200   1 месяц
                                  //  0 (ноль)  0       Период текущего графика 
                                     
extern int Filter.Hour=0;       //  Д-Фильтр: торговля по часам, вне этих часовых рамок новые сделки не открываем, но текущие итеpации завершаем
extern int     Start=9;
extern int      End=20;

// Параметры используемых индикаторов
extern int    Fast            = 5;
extern int    Slow            = 39;
extern int    Signal          = 20;
extern int MagicNumber = 7;       // магик                                         
//extern int Period_MA = 20;      // Период МА                          
//extern int Period_ADX = 40;           
//extern int ADXOpenLevel = 12;   
//---- входные параметры индикатора iVAR
//extern int n = 5;
//extern int nBars = 100000;
                                    
//extern  int Iteration = 0;      // счетчик для подсчета итераций, колен лавины
//extern  int Sum_Loss = 0;
                                   
#include <TrailingByFractals_LAVINA.mqh>     // ТРАЛ ПО ФРАКТАЛАМ
#include <TrailingByShadows.mqh>             // ТРАЛ ПО ТЕНЯМ N БАРОВ
//
// Глобальные переменные
//
static datetime prevtime = 0;     // по ценам открытия
bool IsExpertFailed = false;
bool IsExpertStopped = false;

int NumberOfTry = 25;
int SlipPips = 3;

int signal_period;
int trend_period;


bool UseSound = true;
color ColorBuy = Blue;
color ColorSell = Red;
string ok.wav;

double  Level_new,  PointValue,
        lots;                       // вспомогательная переменная для расчета нового размера лота при очередной итерации
int Iteration, Counter_Loss, Ticket_at_history; // счетчик для подсчета последовательного убытка позиций колен лавины
//bool Flag_Counter_Loss = false;
double Current_Loss, Sum_Loss;     // текущий и суммарный убыток

int ticket;                        // Номер ордера
double orderLots;                  // Lots   
double orderProfit;                // Profit
double Price;                      // Цена открытия рыночного ордера
double SL;                         // Значение StopLoss ордера
double TP;                         // Значение TakeProfit ордера


double F1 =  1.0;                  // значение цены фрактала вверх (на 2-ом баре)
double F11 = 1.0;                  // вспомогательная переменная
double F2 = -200.0;                // значение цены фрактала вниз (на 2-ом баре)
double F22 =-200.0;                // вспомогательная переменная  
 
double V_StopLossPips=0;
double V_TakeProfitPips=0;
//double StopLossPips;
int Ticker, Counter;
double channel;
double  StopLossPips;
double Lots_New;                   // Количество лотов для новых ордеров

int time = 0;                      // время - для определения факта работы только с последним закрытым ордером      
 
How do I determine the maximum or minimum price between two time periods? Is there a special function for this?
 
RoboT1:
How do I determine the maximum or minimum price between two time periods? Is there a special function for this?
Find the min/max in the cycle on one interval, on the other, compare the resulting min/max.
Reason: