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

 
MakarFX, tried it - no change, it only opens on buy, and sell is completely ignored...
 
artem artem #:
MakarFX, tried it - no change, it only opens on buy, but sell is completely ignored...
Hence the conclusion that there are no conditions for switching bools
 
What then do you need to add to the conditions?
 
artem artem #:
What should we add to these conditions?

Explain the logic...

The first one is clear: there is a signal and no orders are opening...

... and then I do not understand under which conditions orders should be opened or closed

 
artem artem #:
What then do you need to add to make the conditions?

Try this

//+------------------------------------------------------------------+
//| 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))
         { Order=false; OrderBuy=true; OrderSell=false; Print("BUY OK"); } 
     } 
   if(CheckForOpen()==1) // Если сигнал для продаж 
     {
      if(OrderSend(Symbol(),OP_SELL,Lots(),Bid,Slip,Ask+StopLoss*Point,Bid-TakeProfit*Point,"",MagicNumber,0,Red))
        { Order=false; OrderBuy=false; OrderSell=true; 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;
   if(sell==4 && OrderBuy)  res=1;
   return(res);
  }
//+------------------------------------------------------------------+
 

OK, I'll explain everything in order, trying to be specific and not to overflow...

It's based on a trend trading strategy called "Puria Method". It is based on crossing three moving averages and MACD bar opening. Two slow with periods (75) and (85), Linear Weighted method applied to Low. A fast average with a period (5), Exponential method, apply to Close. MACD indicator with the parameters 15/26/1. Entry point is formed by crossing two slow moving averages and MACD bar opening into the relevant zone with the fast one ( fast and MACD bar should be in the same zone):

  • BUY Signal - MA(5) crossed and is above both MA(75) and MA(85) with the MACD bar open in the positive area.
  • SELL Signal - MA(5) crossed and is below both MA(75) and MA(85), MACD has an open bar in the negative area.

The EA places a fixed profit and stop loss. The size of the profit and stop are set in the initial parameters. Orders are closed only when they reach Take Profit or Stop Loss.

This is what was in the original Puria Expert Advisors. Plus, in the latest version, there is also a trailing stop and option to trade by certain hours. Functions are useful, but I am not really interested in them now.

Now, actually, what additions I have made/want to make:

1. To make a deal opening and check for all indicator conditions(crossing a fast (5) of two slow (75) (85) and opening of a MACD bar in the same direction with a fast (5)), was performed only at opening price of a new candle (the first tick of each 30 minute candle). This has already been handled;
  1. Create conditions for "zeroing" of indicators. For example, for a fast moving (5) If it is higher than slow - then it is a signal to buy. If it then goes down and either touches one of them, or is between the slow moving (75) and (85)- then the signal from the fast moving indicator "zeros out" as it were, and will remain in this "zero" position as long as it touches or remains between the slow ones. If, after that, fast one crosses both slow ones to one side(including if it returned to the side it came from before touching the slow ones) - then it will be a signal of this indicator. With MACD the situation is similar- Only MACD=0 will be considered as "zeroing"(if on the first candle the MACD, for example, opened with 0.0043, and on the second candle with -0.0010, it means that the MACD on the second candle has "zeroed" and has given a new signal). However, there is a time when the fast (5) and the MACD should be kind of "on equal footing" - if (5) doesn't change its position relative to the slow, and the MACD has opened on the previous candle in the wrong zone (no entry), and on the next one - in the same zone as the fast, then all conditions have converged and an entry to the order should occur. Note that all this should be only on the opening prices of the candles - only on this one tick;
  1. And the last, to make the Expert Advisor wait for 4 consecutive candle openings:

    1. 1st open price - (5) above (75) and (85) + MACD bar opened above 0 - 1 out of 4 confirmations;
    2.The opening price of the 2nd candle - (5) over (75) and (85) + MACD bar opened above 0- 2 out of 4 confirmations is;
    3. The opening price of the 3rd candle - (5) over (75) and (85) + MACD bar opened above 0- 3 out of 4 confirmations is;
    4.Opening price of the 4th candle - (5) over (75) and (85) + MACD bar opened above 0- 4 out of 4 confirmations yes- Open buy trade on the same candle (4th).
The same situation with orders to sell, only in the other direction indicators should open. And there is an important point - if at, say, any stage from the 1st candle to the 4th, the indicators change their position(for example, on the 3rd opening candle, the MACD bar opens either below 0, or =0) - then everything is reset, because the signals have not passed the test on the opening of the 4th candle in a row.


Somehow, if something is unclear, or there are questions, please ask.

 
artem artem #:

OK, I'll explain everything in order, try to be specific and not to overflow...


  1. Create conditions for "zeroing" the indicators.

This is zeroing.

   if(malw>mas1&&malw>mas2&&macd>0) {buy+=1; sell=0;}
   if(malw<mas1&&malw<mas2&&macd<0) {buy=0; sell+=1;}

Maybe I don't understand you correctly...

try to make a screenshot

 
I have attached a screenshot, if you don't understand anything, just ask
Files:
 
artem artem #:
I've attached a screenshot, if you don't understand something, just ask me.
I got it, I'll think about it.
 
artem artem #:
Attached a screenshot, if anything is not clear - just ask

Try this one - will it open in those places?

//+------------------------------------------------------------------+
//|                                                  artem artem.mq4 |
//|                        Copyright 2021, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict
//---
#define  MagicNumber  122122
//---
#include <stdlib.mqh> // Стандартная библиотека
//---
input string s0 = "Баланс";            // 1
input string Template       = "ADX";   // Имя шаблона(without '.tpl')
input double TargetProfit   = 1000000; // Баланс + Прибыль(прибавить к балансу)
input double TargetLoss     = 0;       // Баланс - Убыток(отнять от баланса)
input string s1 = "Размер лота";       // 2
input double Lot            = 0.01;    // размер лота 0 - авт.расчет
input string s2 = "TP SL";             // 3
input double InpTProfit     = 1000;    // Exchange TP
input double InpStopLoss    = 1000000; // Exchange SL
input string s3 = "Индикатор";         // 4
input int    MovingPeriodLw = 13;      // MovingPeriodLw
input int    MovingPeriodS1 = 89;      // MovingPeriodS1
input int    MovingPeriodS2 = 144;     // MovingPeriodS2
input string s4 = "Day & Hour";        // 5
input int    HrStart        = 0;       // время начала торговли
input int    HrEnd          = 23;      // время окончания торговли
//+------------------------------------------------------------------+
int    Monday         = 1;      // Понедельник 1 вкд. 0 выкл.
int    Tuesday        = 1;      // Вторник
int    Wednesday      = 1;      // Среда
int    Thursday       = 1;      // Четверг
int    Friday         = 1;      // Пятница
//+------------------------------------------------------------------+
uint SLEEPTIME=1;
double Price[2];
datetime timeprev=0;
ENUM_TIMEFRAMES TimeFrame= PERIOD_CURRENT;
bool OrderBuy=false,OrderSell=false,Order=false,Init=true,ClOp=true;
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- Закрыть Общий профит или профит на паре
   if(ProfitTarget())
     {
      return;
     }
//--- Закрыть профит BUY или SELL на паре
   ProfitOnTick();
// Определение направления пересечения мувингов
   if(Init)
      InitMetod();
// Ожидание нового бара на графике
   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,12,26,9,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,3,0,0,"",MagicNumber,0,Blue);
      Order=false;
      return;
     }
// Открываем ордер Sell
   if(macd<0 && OrderSell && Order)
     {
      res=OrderSend(Symbol(),OP_SELL,Lots(),Bid,3,0,0,"",MagicNumber,0,Red);
      Order=false;
      return;
     }
  }
//+------------------------------------------------------------------+
//| 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;
  }
//+------------------------------------------------------------------+
//| 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);
  }
//+------------------------------------------------------------------+
// 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;
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool ProfitTarget(void)
  {
   bool res=false;
   if(AccountInfoDouble(ACCOUNT_EQUITY)<=TargetLoss ||
      AccountInfoDouble(ACCOUNT_EQUITY)>=TargetProfit)
     {
      CloseAllOrders();
      Sleep(SLEEPTIME*1000);
      CloseAllOrders();
      ExpertRemove();
      DeleteChart();
      PlaySound("expert.wav");
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| Check for long position closing                                  |
//+------------------------------------------------------------------+
bool ProfitOnTick(void)
  {
   bool res=false;
   double PROFIT_BUY=0.00;
   double PROFIT_SELL=0.00;
   for(int i=OrdersTotal()-1; i>=0; i--) // returns the number of open positions
     {
      if(OrderSelect(i,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY)
           {
            PROFIT_BUY=PROFIT_BUY+NormalizeDouble(OrderProfit(),2);
           }
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
           {
            PROFIT_SELL=PROFIT_SELL+NormalizeDouble(OrderProfit(),2);
           }
        }
     }
   int Close_ticketb=0;
   int totalb=OrdersTotal();
   int b = 0;
   for(b = totalb; b >=0; b--)
     {
      if(OrderSelect(b,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         //OrderSelect(i,SELECT_BY_POS);
         if(OrderSymbol()==Symbol() && OrderType()==OP_BUY)
           {
            if(PROFIT_BUY<-InpStopLoss || PROFIT_BUY>=InpTProfit)
              {
               Close_ticketb = OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_BID),5);
               PlaySound("ok.wav");
              }
           }
        }
      res=true;
     }
   int Close_tickets=0;
   int totals=OrdersTotal();
   int s = 0;
   for(s = totals; s >=0; s--)
     {
      if(OrderSelect(s,SELECT_BY_POS) && OrderSymbol()==Symbol())
        {
         if(OrderSymbol()==Symbol() && OrderType()==OP_SELL)
           {
            if(PROFIT_SELL<-InpStopLoss || PROFIT_SELL>=InpTProfit)
              {
               Close_tickets = OrderClose(OrderTicket(),OrderLots(),MarketInfo(Symbol(),MODE_ASK),5);
               PlaySound("ok.wav");
              }
           }
        }
      res=true;
     }
//--- result
   return(res);
  }
//+------------------------------------------------------------------+
//| script program start function                                    |
//+------------------------------------------------------------------+
void CloseAllOrders(void)
  {
   int iOrders=OrdersTotal()-1, i;
   if(ClOp)
     {
      for(i=iOrders; i>=0; i--)
        {
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES) && (OrderType()<=OP_SELL) && GetMarketInfo() &&
            !OrderClose(OrderTicket(),OrderLots(),Price[1-OrderType()],0))
            Print(OrderError());
         if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
           {
            if(OrderDelete(OrderTicket()))
               Print(OrderError());
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Function..: OrderError                                           |
//+------------------------------------------------------------------+
string OrderError(void)
  {
   int iError=GetLastError();
   return(StringConcatenate("Order:",OrderTicket()," GetLastError()=",iError," ",ErrorDescription(iError)));
  }
//+------------------------------------------------------------------+
//| Function..: GetMarketInfo                                        |
//+------------------------------------------------------------------+
bool GetMarketInfo(void)
  {
   RefreshRates();
   Price[0]=MarketInfo(OrderSymbol(),MODE_ASK);
   Price[1]=MarketInfo(OrderSymbol(),MODE_BID);
   double dPoint=MarketInfo(OrderSymbol(),MODE_POINT);
   if(dPoint==0)
      return(false);
   return(Price[0]>0.0 && Price[1]>0.0);
  }
//+------------------------------------------------------------------+
//| start function                                                   |
//+------------------------------------------------------------------+
void DeleteChart(void)
  {
   long currChart,prevChart=ChartFirst();
   int i=0,limit=100;
   bool errTemplate;
   while(i<limit)
     {
      currChart=ChartNext(prevChart);
      if(TimeFrame!=PERIOD_CURRENT)
        {
         ChartSetSymbolPeriod(prevChart,ChartSymbol(prevChart),TimeFrame);
        }
      errTemplate=ChartApplyTemplate(prevChart,Template+".tpl");
      if(!errTemplate)
        {
         Print("Error ",ChartSymbol(prevChart),"-> ",GetLastError());
        }
      if(currChart<0)
         break;
      Print(i,ChartSymbol(currChart)," ID =",currChart);
      prevChart=currChart;
      i++;
     }
  }
//+------------------------------------------------------------------+
Reason: