Any questions from newcomers on MQL4 and MQL5, help and discussion on algorithms and codes - page 1655

 
Volodymyr Zubov #:

There are fingers to the fact that it is inappropriate to only put OrderSend, and then not to worry about something wrong. You always have to look for errors.

Volodya, the question was about something else.

 
MakarFX #:

Volodya, the question was different.

What is it?

 
Volodymyr Zubov #:

In what?

Dobranich)
 
MakarFX #:
Dobranich)

You too.

 
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(CheckForOpen()==0)
     {
      if(OrderSend(Symbol(),OP_BUY,Lots(),Ask,Slip,Bid-StopLoss*Point,Ask+TakeProfit*Point,"",MagicNumber,0,Blue)) Print("BUY OK");
     }
   if(CheckForOpen()==1)
     {
      if(OrderSend(Symbol(),OP_SELL,Lots(),Bid,Slip,Ask+StopLoss*Point,Bid-TakeProfit*Point,"",MagicNumber,0,Red)) Print("SELL OK");
     }
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
int CheckForOpen() // Открытие ордера по методу Пуриа
  {
   double malw,mas1,mas2,macd;
   int    res=-1, buy=0, sell=0;
   // Считывание параметров индикаторов 3 свечи
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,3);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,3);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,3);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,3);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 2 свечи
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,2);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,2);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,2);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,2);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 1 свечи
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,1);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,1);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,1);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,1);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 0 свечи
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,0);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,0);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,0);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,0);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   
   if(buy ==4) res=0;
   if(sell==4) res=1;
   return(res);
  }

Can you tell me how to make it not open an order with each new candle if all conditions are met? I just inserted this code, it really started waiting for 4 candles confirmation, but after opening an order 1 time (when all conditions are met) it started to open an order on all subsequent candles, if the conditions persisted, this is how it looks in the tester.

+ just in case, I will paste all the original code, just in case I missed something important:

#define  MagicNumber  122122
extern string s1             = "Trading options";
extern double Lot            = 0.01;    // размер лота 0 - авт.расчет
extern double StopLoss       = 40;     // стоплосс
extern double TakeProfit     = 10;     // тейкпрофит
extern double TrailStop      = 21;     // уровень без убытка
extern int    Trailing       = 0;      // трейлинг стоп 1 вкл. 0 выкл.
extern int    Breakeven      = 0;      // перенос стоп лосса в без убыток
extern string s2             = "Day & Hour";
extern int    HrStart        = 0;      // время начала торговли
extern int    HrEnd          = 23;     // время окончания торговли
extern int    Monday         = 1;      // Понедельник 1 вкд. 0 выкл.
extern int    Tuesday        = 1;      // Вторник
extern int    Wednesday      = 1;      // Среда
extern int    Thursday       = 1;      // Четверг
extern int    Friday         = 1;      // Пятница
//+------------------------------------------------------------------+
// параметры индикаторов
double MovingPeriodLw        = 5;      
double MovingPeriodS1        = 75;
double MovingPeriodS2        = 85;
double StopLevel;
double TrailStep             = 3;      // шаг трейлинг стопа
bool OrderBuy = false, OrderSell = false, Order = false, Init = true;
int timeprev = 0, Slip = 3.0;

//+------------------------------------------------------------------+
//| Init function                                                    |
//+------------------------------------------------------------------+
void OnInit()
{
   if (Digits == 3 || Digits == 5) { // Пересчет для 5-ти знаков                                                    
      TakeProfit *= 10;
      TrailStop *= 10;
      TrailStep *= 10;
      StopLoss *=10;
      Slip *=10;
   } 
   return; 
}
//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
{
   StopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL); 
   
   // Определение направления пересечения мувингов
   if (Init) InitMetod(); 
   
   // Трейлинг стоп открытых позиций
   if (Trailing != 0 ) RealTrailOrder(TrailStop, TrailStep, StopLevel, MagicNumber);
   
   // Ожидание нового бара на графике
   if(timeprev == Time[0]) return;
   timeprev = Time[0];
   
   // Открытие ордера по методу Пуриа
   CheckForOpen();
}
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
void CheckForOpen() // Открытие ордера по методу Пуриа
{
   double malw,mas1,mas2,macd;
   int    res;  
   // Считывание параметров индикаторов
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,0);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,0);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,0);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,0);
  
   // Проверяем положение мувмнгов
   if(malw>mas1 && malw>mas2  && OrderSell)
     {
     OrderBuy=true;
     OrderSell=false;
     Order=true;
     }
   
   if(malw<mas1 && malw<mas2  && OrderBuy)
     {
     OrderBuy=false;
     OrderSell=true;
     Order=true;
     }

   // Открываем ордер Buy
   if(macd>0 && OrderBuy && Order)
     {
     res=OrderSend(Symbol(),OP_BUY,Lots(),Ask,Slip,Bid-StopLoss*Point,Ask+TakeProfit*Point,"",MagicNumber,0,Blue);
     Order=false;
     return;
     }     
   // Открываем ордер Sell   
   if(macd<0 && OrderSell && Order)
     {
     res=OrderSend(Symbol(),OP_SELL,Lots(),Bid,Slip,Ask+StopLoss*Point,Bid-TakeProfit*Point,"",MagicNumber,0,Red);
     Order=false;
     return;
     }
 
}  
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double Lots()  // Расчет объема лота
{
   double Lots;
   if (Lot > 0) return(Lot);
   Lots=AccountFreeMargin()/5000;
   Lots=MathMin(15,MathMax(0.01,Lots));
   if(Lots<0.1) Lots=NormalizeDouble(Lots,2);
   else 
     {
     if(Lots<1) Lots=NormalizeDouble(Lots,1);
     else       Lots=NormalizeDouble(Lots,0);
     }
   return(Lots);
}
//+------------------------------------------------------------------+
//| Init metod Puria function                                        |
//+------------------------------------------------------------------+
void InitMetod()  // Опредеоение начального пересечения мувингов
{
   double malw,mas1,mas2;
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,0);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,0);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,0);

   if((malw<=mas1 && malw>=mas2) || (malw>=mas1 && malw<=mas2))
     {
     Init=false;
     OrderBuy=true;
     OrderSell=true;
     }   
   return;
}
 
//+------------------------------------------------------------------+
// Treylingstop function                                             |
//+------------------------------------------------------------------+
   // Трейлинг стоп
void RealTrailOrder(double trstop, double trstep, double stlevel, int magic) 
{
   double openprice;
   double openstoploss;
   double calculatestoploss;
   double trailstop = MathMax(trstop, stlevel);
   for (int cmt = OrdersTotal() - 1; cmt >= 0; cmt--) 
     {
     if(OrderSelect(cmt, SELECT_BY_POS, MODE_TRADES) == TRUE) 
       {
       if(OrderMagicNumber() == magic && OrderSymbol() == Symbol()) 
         {
         openprice = OrderOpenPrice();
         openstoploss = OrderStopLoss();
         while (IsTradeContextBusy()) Sleep(500);
         RefreshRates();
         if(OrderType() == OP_BUY) 
           {
           calculatestoploss = ND(Bid - trailstop * Point);
           if((Bid > openprice + trailstop * Point) || (Breakeven == 0)) 
             {
             if(((calculatestoploss >= openstoploss + trstep * Point) && (trailstop * Point > stlevel * Point))) 
               {
               if(!OrderModify(OrderTicket(), OrderOpenPrice(), calculatestoploss, OrderTakeProfit(), 0, Blue))
                 Print("BUY OrderModify Error " + IntegerToString(GetLastError()));
               }
             }
           }
         if(OrderType() == OP_SELL) 
           {
           calculatestoploss = ND(Ask + trailstop * Point);
           if((Ask < openprice - trailstop * Point) || (Breakeven == 0)) 
             {
             if(((calculatestoploss <= openstoploss - trstep * Point) && (trailstop * Point > stlevel * Point))) 
               {
               if(!OrderModify(OrderTicket(), OrderOpenPrice(), calculatestoploss, OrderTakeProfit(), 0, Red))
                 Print("BUY OrderModify Error " + IntegerToString(GetLastError()));
               }
             }
           }
         }
       }
     }
}
//=============================================================================================================================================
double ND(double ad_0) 
{
  return (NormalizeDouble(ad_0, Digits));
}  
//нннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
//
// Permission to trade in this day 
// 
//********************************************************************************************************
bool TradingDay(int hmin, int hmax) // Определение времени и дня разрешения торговли 
{ 
  bool dtrade = false; 
  switch (DayOfWeek()) 
    {
  
    case 1: // Monday
       if (Monday == 1) dtrade = true; 
       break;
    case 2: // Tuesday 
       if (Tuesday == 1) dtrade = true;
       break;
    case 3: // Wednesday
       if (Wednesday == 1) dtrade = true;
       break;     
    case 4: // Thursday
       if (Thursday == 1) dtrade = true;
       break;
    case 5: // Friday
       if (Friday == 1) dtrade = true;
       break;
    default: // 
       dtrade = false;
       break;
    }
  
  if (dtrade && !(Hour() >= hmin && Hour() <= hmax)) dtrade = true;
  return dtrade;
}
 
Files:
 
artem artem #:

Can you tell me how to make it not open an order with each new candle if all conditions are met? I just inserted this code, it really started waiting for 4 candles confirmation, but after opening an order 1 time (when all conditions are met) it started to open an order on all subsequent candles, if the conditions persisted, this is how it looks in the tester.

+ Just in case I missed something important:

I need control (counter) of open orders

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(CheckForOpen()==0&&CountTrade(0)==0) // Если сигнал для покупок и нет открытых покупок
     {
      if(OrderSend(Symbol(),OP_BUY,Lots(),Ask,Slip,Bid-StopLoss*Point,Ask+TakeProfit*Point,"",MagicNumber,0,Blue)) Print("BUY OK");
     }
   if(CheckForOpen()==1&&CountTrade(1)==0) // Если сигнал для продаж и нет открытых продаж
     {
      if(OrderSend(Symbol(),OP_SELL,Lots(),Bid,Slip,Ask+StopLoss*Point,Bid-TakeProfit*Point,"",MagicNumber,0,Red)) Print("SELL OK");
     }
  }
//+----------------------------------------------------------------------------+
//| Счетчик ордеров (0)-buy (1)-sell ()-all                                    |
//+----------------------------------------------------------------------------+
int CountTrade(int ot=-1)
  {
   int count = 0;
   for(int i = OrdersTotal()-1; i>=0; i--)
     {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
        {
         if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
           {
            if(OrderType()==ot||ot<0) count++;
           }  
        }
     }
   return(count);
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
int CheckForOpen() // Открытие ордера по методу Пуриа
  {
   double malw,mas1,mas2,macd;
   int    res=-1, buy=0, sell=0;
   // Считывание параметров индикаторов 3 свечи
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,3);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,3);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,3);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,3);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 2 свечи
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,2);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,2);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,2);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,2);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 1 свечи
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,1);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,1);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,1);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,1);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 0 свечи
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,0);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,0);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,0);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,0);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   
   if(buy ==4) res=0;
   if(sell==4) res=1;
   return(res);
  }
 
Tried it, yes, no more re-entries. But if Countrade does, then there will be no reaction to new signals as long as at least one order is open, which is unnecessary. I.e. there should be no re-openings after the 1st time, but there should also be an entry to the order if the malw or/and macd has changed its position and according to the conditions it is a signal + if the sigal is confirmed 4 times in a row => open a position. If this is added to the code, then, ideally, everything should be ready. What else needs to be added for this ?
 
artem artem open a position. If this is added to the code, then, ideally, everything should be ready. What else needs to be added for that ?
If we give it out in portions, the same thing will happen. In this case, all functions are built according to the conditions you described.
 

Tried to make changes to the code from MakarFX and this is what I have at the moment:


#define  MagicNumber  122122
extern string s1             = "Trading options";
extern double Lot            = 0.01;    // размер лота 0 - авт.расчет
extern double StopLoss       = 40;     // стоплосс
extern double TakeProfit     = 10;     // тейкпрофит
extern double TrailStop      = 21;     // уровень без убытка
extern int    Trailing       = 0;      // трейлинг стоп 1 вкл. 0 выкл.
extern int    Breakeven      = 0;      // перенос стоп лосса в без убыток
extern string s2             = "Day & Hour";
extern int    HrStart        = 0;      // время начала торговли
extern int    HrEnd          = 23;     // время окончания торговли
extern int    Monday         = 1;      // Понедельник 1 вкд. 0 выкл.
extern int    Tuesday        = 1;      // Вторник
extern int    Wednesday      = 1;      // Среда
extern int    Thursday       = 1;      // Четверг
extern int    Friday         = 1;      // Пятница
//+------------------------------------------------------------------+
// параметры индикаторов
double MovingPeriodLw        = 5;      
double MovingPeriodS1        = 75;
double MovingPeriodS2        = 85;
double StopLevel;
double TrailStep             = 3;      // шаг трейлинг стопа
bool OrderBuy = false, OrderSell = false, Order = false, Init = true;
int timeprev = 0, Slip = 3.0;

//+------------------------------------------------------------------+
//| Init function                                                    |
//+------------------------------------------------------------------+
void OnInit()
{
   if (Digits == 3 || Digits == 5) { // Пересчет для 5-ти знаков                                                    
      TakeProfit *= 10;
      TrailStop *= 10;
      TrailStep *= 10;
      StopLoss *=10;
      Slip *=10;
   } 
   return; 
}
//+------------------------------------------------------------------+
//| Start function                                                   |
//+------------------------------------------------------------------+
void start()
{
   StopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL); 
   
   // Определение направления пересечения мувингов
   if (Init) InitMetod(); 
   
   // Трейлинг стоп открытых позиций
   if (Trailing != 0 ) RealTrailOrder(TrailStop, TrailStep, StopLevel, MagicNumber);
   
   // Ожидание нового бара на графике
   if(timeprev == Time[0]) return;
   timeprev = Time[0];
   
   // Открытие ордера по методу Пуриа
   if(CheckForOpen()==0) // Если сигнал для покупок 
     {
      if(OrderSend(Symbol(),OP_BUY,Lots(),Ask,Slip,Bid-StopLoss*Point,Ask+TakeProfit*Point,"",MagicNumber,0,Blue)) Print("BUY OK");
     } 
   if(CheckForOpen()==1) // Если сигнал для продаж 
     {
      if(OrderSend(Symbol(),OP_SELL,Lots(),Bid,Slip,Ask+StopLoss*Point,Bid-TakeProfit*Point,"",MagicNumber,0,Red)) Print("SELL OK");
     }
  }
//+------------------------------------------------------------------+
//| Check for open order conditions                                  |
//+------------------------------------------------------------------+
int CheckForOpen() // Открытие ордера по методу Пуриа
  {
   double malw,mas1,mas2,macd;
   int    res=-1, buy=0, sell=0;
   // Считывание параметров индикаторов 3 свечи (4ой)
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,3);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,3);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,3);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,3);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 2 свечи (3ей)
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,2);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,2);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,2);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,2);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 1 свечи (2ой)
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,1);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,1);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,1);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,1);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   // Считывание параметров индикаторов 0 свечи (1ой)
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,0);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,0);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,0);
   macd=iMACD(NULL,0,15,26,1,PRICE_CLOSE,MODE_MAIN,0);
   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}
   
   if(buy ==4 && OrderSell) { res=0; Order=false; OrderBuy=true; OrderSell=false; } 
   if(sell==4 && OrderBuy)  { res=1; Order=false; OrderBuy=false; OrderSell=true; }
   return(res);
  }
//+------------------------------------------------------------------+
//| Calculate optimal lot size                                       |
//+------------------------------------------------------------------+
double Lots()  // Расчет объема лота
{
   double Lots;
   if (Lot > 0) return(Lot);
   Lots=AccountFreeMargin()/5000;
   Lots=MathMin(15,MathMax(0.01,Lots));
   if(Lots<0.1) Lots=NormalizeDouble(Lots,2);
   else 
     {
     if(Lots<1) Lots=NormalizeDouble(Lots,1);
     else       Lots=NormalizeDouble(Lots,0);
     }
   return(Lots);
}
//+------------------------------------------------------------------+
//| Init metod Puria function                                        |
//+------------------------------------------------------------------+
void InitMetod()  // Опредеоение начального пересечения мувингов
{
   double malw,mas1,mas2;
   malw=iMA(NULL,0,MovingPeriodLw,0,MODE_EMA,PRICE_CLOSE,0);
   mas1=iMA(NULL,0,MovingPeriodS1,0,MODE_LWMA,PRICE_LOW,0);
   mas2=iMA(NULL,0,MovingPeriodS2,0,MODE_LWMA,PRICE_LOW,0);

   if((malw<=mas1 && malw>=mas2) || (malw>=mas1 && malw<=mas2))
     {
     Init=false;
     OrderBuy=true;
     OrderSell=true;
     }   
   return;
}
 
//+------------------------------------------------------------------+
// Treylingstop function                                             |
//+------------------------------------------------------------------+
   // Трейлинг стоп
void RealTrailOrder(double trstop, double trstep, double stlevel, int magic) 
{
   double openprice;
   double openstoploss;
   double calculatestoploss;
   double trailstop = MathMax(trstop, stlevel);
   for (int cmt = OrdersTotal() - 1; cmt >= 0; cmt--) 
     {
     if(OrderSelect(cmt, SELECT_BY_POS, MODE_TRADES) == TRUE) 
       {
       if(OrderMagicNumber() == magic && OrderSymbol() == Symbol()) 
         {
         openprice = OrderOpenPrice();
         openstoploss = OrderStopLoss();
         while (IsTradeContextBusy()) Sleep(500);
         RefreshRates();
         if(OrderType() == OP_BUY) 
           {
           calculatestoploss = ND(Bid - trailstop * Point);
           if((Bid > openprice + trailstop * Point) || (Breakeven == 0)) 
             {
             if(((calculatestoploss >= openstoploss + trstep * Point) && (trailstop * Point > stlevel * Point))) 
               {
               if(!OrderModify(OrderTicket(), OrderOpenPrice(), calculatestoploss, OrderTakeProfit(), 0, Blue))
                 Print("BUY OrderModify Error " + IntegerToString(GetLastError()));
               }
             }
           }
         if(OrderType() == OP_SELL) 
           {
           calculatestoploss = ND(Ask + trailstop * Point);
           if((Ask < openprice - trailstop * Point) || (Breakeven == 0)) 
             {
             if(((calculatestoploss <= openstoploss - trstep * Point) && (trailstop * Point > stlevel * Point))) 
               {
               if(!OrderModify(OrderTicket(), OrderOpenPrice(), calculatestoploss, OrderTakeProfit(), 0, Red))
                 Print("BUY OrderModify Error " + IntegerToString(GetLastError()));
               }
             }
           }
         }
       }
     }
}
//=============================================================================================================================================
double ND(double ad_0) 
{
  return (NormalizeDouble(ad_0, Digits));
}  
//нннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннннн
//
// Permission to trade in this day 
// 
//********************************************************************************************************
bool TradingDay(int hmin, int hmax) // Определение времени и дня разрешения торговли 
{ 
  bool dtrade = false; 
  switch (DayOfWeek()) 
    {
  
    case 1: // Monday
       if (Monday == 1) dtrade = true; 
       break;
    case 2: // Tuesday 
       if (Tuesday == 1) dtrade = true;
       break;
    case 3: // Wednesday
       if (Wednesday == 1) dtrade = true;
       break;     
    case 4: // Thursday
       if (Thursday == 1) dtrade = true;
       break;
    case 5: // Friday
       if (Friday == 1) dtrade = true;
       break;
    default: // 
       dtrade = false;
       break;
    }
  
  if (dtrade && !(Hour() >= hmin && Hour() <= hmax)) dtrade = true;
  return dtrade;
}
 

Highlighted is what I tried to add from me. As a result, everything works as it should, but deals open only on buy. How do I make it open for sell too, who knows?

 
artem artem #:

Tried to make changes to the code from MakarFX and this is what I have at the moment:


Highlighted is what I tried to add from me. As a result, everything works as it should, but deals open only on buy. How do I make it open for sell too, who knows?

Try putting "true" at the beginning
bool OrderBuy = false, OrderSell = false,