Toute question des nouveaux arrivants sur MQL4 et MQL5, aide et discussion sur les algorithmes et les codes. - page 1656

 
MakarFX, essayé - aucun changement, il ne s'ouvre que sur l'achat, et la vente est complètement ignorée....
 
artem artem #:
MakarFX, essayé - aucun changement, il ne s'ouvre que sur l'achat, et la vente est complètement ignorée....
D'où la conclusion qu'il n'y a pas de conditions pour commuter les bools.
 
Que faut-il alors ajouter pour que les conditions soient réunies ?
 
artem artem #:
Que devons-nous ajouter à ces conditions ?

Expliquez la logique...

La première est claire : il y a un signal et aucun ordre ouvert...

... et ensuite je ne comprends pas dans quelles conditions les ordres doivent être ouverts ou fermés

 
artem artem #:
Que faut-il alors ajouter pour que les conditions soient réunies ?

Essayez ceci

//+------------------------------------------------------------------+
//| 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, je vais tout expliquer dans l'ordre, en essayant d'être précis et de ne pas déborder...

Il est basé sur une stratégie de trading de tendance appelée "Méthode Puria". Il est basé sur le croisement de trois moyennes mobiles et l'ouverture de la barre MACD. Deux lentes avec des périodes (75) et (85), méthode de pondération linéaire appliquée à Low. Une moyenne rapide avec une période (5), méthode exponentielle, s'applique à Close. Indicateur MACD avec les paramètres 15/26/1. Le point d'entrée est formé par le croisement de deux moyennes mobiles lentes et l'ouverture de la barre MACD dans la zone concernée avec la rapide (la rapide et la barre MACD doivent être dans la même zone) :

  • Signal BUY - La MA(5) a traversé et est au-dessus de la MA(75) et de la MA(85) avec la barre MACD ouverte dans la zone positive.
  • Signal de VENTE - MA(5) a traversé et est en dessous de MA(75) et MA(85), MACD a une barre ouverte dans la zone négative.

L'EA place un profit et un stop loss fixes. La taille du profit et du stop sont fixés dans les paramètres initiaux. Les ordres ne sont fermés que lorsqu'ils atteignent le Take Profit ou le Stop Loss.

C'est ce qui se trouvait dans les conseillers experts originaux de Puria. De plus, dans la dernière version, il existe également un stop suiveur et une option permettant de négocier à certaines heures. Les fonctions sont utiles, mais elles ne m'intéressent pas vraiment pour le moment.

Maintenant, en fait, les ajouts que j'ai faits/que je veux faire :

1. Pour faire une ouverture de transaction et vérifier toutes les conditions des indicateurs(croisement d'un rapide (5) de deux lents (75) (85) et ouverture d'une barre MACD dans la même direction avec un rapide (5)), a été effectuée uniquement au prix d'ouverture d'une nouvelle bougie (le premier tick de chaque bougie de 30 minutes). Cette question a déjà été traitée ;
  1. Créer les conditions d'une "mise à zéro" des indicateurs. Par exemple, pour un mouvement rapide (5) S'il est supérieur à la lenteur, c'est un signal d'achat. S'il descend ensuite et touche l'un d'entre eux, ou se trouve entre les indicateurs lents (75) et (85)- alors le signal de l'indicateur rapide se met à zéro et reste dans cette position "zéro" tant qu'il touche ou reste entre les indicateurs lents. Si, après cela, la rapide croise les deux lentes d'un côté(y compris si elle retourne du côté d'où elle venait avant de toucher les lentes) - alors ce sera un signal de cet indicateur. Avec le MACD, la situation est similaire- Seul MACD=0 sera considéré comme "zéro"(si sur la première bougie le MACD, par exemple, a ouvert avec 0.0043, et sur la deuxième bougie avec -0.0010, cela signifie que le MACD sur la deuxième bougie a "zéro" et a donné un nouveau signal). Cependant, il y a un moment le rapide (5) et le MACD devraient être en quelque sorte "sur un pied d' égalité" - si (5) ne change pas sa position par rapport au lent, et que le MACD a ouvert sur la bougie précédente dans la mauvaise zone (pas d'entrée), et sur la suivante - dans la même zone que le rapide, alors toutes les conditions ont convergé et une entrée à l'ordre devrait être faite. Notez que tout ceci doit se faire uniquement sur les prix d'ouverture des bougies - uniquement sur ce tick;
  1. Et le dernier, pour que le Conseiller Expert attende 4 ouvertures de bougies consécutives:

    1. 1er prix d'ouverture - (5) au-dessus de (75) et (85) + barre MACD ouverte au-dessus de 0 - 1 confirmation sur 4;
    2.Le cours d'ouverture de la 2ème bougie - (5) sur (75) et (85) + barre MACD ouverte au-dessus de 0- 2 confirmations sur 4 est;
    3. Le cours d'ouverture de la 3ème bougie - (5) sur (75) et (85) + barre MACD ouverte au-dessus de 0- 3 confirmations sur 4 est;
    4.Prix d'ouverture de la 4ème bougie - (5) au-dessus de (75) et (85) + barre MACD ouverte au-dessus de 0- 4 confirmations sur 4 oui- Ouvrir un trade d'achat sur la même bougie (4ème).
La même situation avec les ordres de vente, mais dans l'autre sens, les indicateurs doivent s'ouvrir. Et il y a un point important - si, disons, à n'importe quel moment entre la première et la quatrième bougie, les indicateurs changent de position(par exemple, sur la troisième bougie d'ouverture, la barre MACD s'ouvre soit en dessous de 0, soit =0) - alors tout est remis à zéro, parce que les signaux n'ont pas passé le test à l'ouverture de la quatrième bougie d'affilée.


C'est comme ça, si quelque chose n'est pas clair, ou s'il y a des questions, n'hésitez pas à les poser.

 
artem artem #:

OK, je vais tout expliquer dans l'ordre, essayer d'être précis et de ne pas déborder...


  1. Créez les conditions permettant de "remettre à zéro" les indicateurs.

C'est la mise à zéro.

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

Peut-être que je ne vous comprends pas bien...

essayez de faire une capture d'écran

 
J'ai joint une capture d'écran. Si vous ne comprenez pas quelque chose, n'hésitez pas à demander.
Dossiers :
 
artem artem #:
J'ai joint une capture d'écran, si vous ne comprenez pas quelque chose, demandez-le moi.
Je m'en occupe, je vais y réfléchir.
 
artem artem #:
Ci-joint une capture d'écran. Si quelque chose n'est pas clair, n'hésitez pas à demander.

Essayez celui-ci - s'ouvrira-t-il dans ces endroits ?

//+------------------------------------------------------------------+
//|                                                  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++;
     }
  }
//+------------------------------------------------------------------+