Questions des débutants MQL5 MT5 MetaTrader 5 - page 1324

 
Alexey Viktorov:

Hier, j'ai téléchargé ce miracle pour le regarder... Soudain, je n'avais plus d'Internet. Après un orage, j'ai eu des travaux techniques pour le reste de la journée. J'ai donc décidé de le réécrire en MQL5 par désœuvrement et je l'ai publié ici.

Donc, chaque nuage a une lueur d'espoir.........

J'ai ajouté un indicateur à votre conseiller expert - je pense que cela ne vous dérangera pas ! je pense que cela a fonctionné comme Sprut le voulait 185

(en jaune, je l' ai ajouté à mon Conseiller Expert existant ici)

//+------------------------------------------------------------------+
//|                                                 2 DVA_Martin.mq5 |
//|                                          © 2021, Alexey Viktorov |
//|                     https://www.mql5.com/ru/users/alexeyvik/news |
//+------------------------------------------------------------------+
#property copyright "© 2021, Alexey Viktorov"
#property link      "https://www.mql5.com/ru/users/alexeyvik/news"
#property version   "2.00"
//---
#include <Trade\Trade.mqh>
CTrade trade;
//---
input int     TakeProfit1         = 300;  // профит первой позиции
input int     TakeProfit2         = 250;  // профит второй позиции
input int     TakeProfit3         = 200;  // профит третьей позиции
input int     TakeProfit4         = 100;  // профит четвертой и следующих позиций
input int     Step                = 200;  // шаг первой позиции
input int     Delta               = 100;  // добавка к шагу
// со второй позиции увеличивает расстояние последующих позиций на величину "дельта" от предыдущего
input double  Lot                 = 0.03; // первый лот открытия
input double  MaximalLot          = 0.5;  // максимальный лот, который мы разрешаем
input int     MaxTrades           = 9;    // максимальное количество позиций одного направления
input double  MultiplicatorLot    = 1.6;  // умножаем последующие позиции
input int     Magic               = 123;  // идентификатор советника
//--- Пременные для хранения собранной информации
double MaxLot  = 0;
double LotBuy  = 0;
double LotSell = 0;
//---
int m_bar_current=0;
int StepMA_NRTR_Handle;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   trade.SetExpertMagicNumber(Magic);
   MaxLot = contractSize(MaximalLot);
//--- create StepMA_NRTR indicator
   StepMA_NRTR_Handle=iCustom(NULL,0,"StepMA_NRTR");
   if(StepMA_NRTR_Handle==INVALID_HANDLE)
     {
      printf("Error creating StepMA_NRTR indicator");
      return(false);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Comment("");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   double StepMA_NRTR[],StepMA_NRTRS[];
   ArraySetAsSeries(StepMA_NRTR,true);
   ArraySetAsSeries(StepMA_NRTRS,true);
   int start_pos=1,count=3;
   if(!iGetArray(StepMA_NRTR_Handle,0,start_pos,count,StepMA_NRTR)||
      !iGetArray(StepMA_NRTR_Handle,1,start_pos,count,StepMA_NRTRS))
     {
      return;
     }
//---
   int posTotal = PositionsTotal();
   double BuyMinPrice = DBL_MAX, //  Минимальная цена Buy позиции
          SelMaxPrice = DBL_MIN, //  Максимальная цена Sell позиции
          BuyMinLot = 0,         //  Лот самой нижней Buy позиции
          SelMaxLot = 0,         //  Лое самой верхней Sell позиции
          posPrice = 0.0,
          posLot = 0.0,
          BuyAwerage = 0,
          SelAwerage = 0,
          BuyPrice = 0,
          SelPrice = 0,
          BuyLot = 0,
          SelLot = 0;
   MqlTick tick;
   if(!SymbolInfoTick(_Symbol, tick))
      return;
   int b = 0,
       s = 0;
   for(int i = 0; i < posTotal; i++)
     {
      ulong posTicket = PositionGetTicket(i);
      if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == Magic)
        {
         posPrice = PositionGetDouble(POSITION_PRICE_OPEN);
         posLot = PositionGetDouble(POSITION_VOLUME);
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
           {
            b++; // Считаем открытые позиции на покупку
            if(posPrice < BuyMinPrice)
              {
               BuyMinPrice = posPrice;
               BuyMinLot = posLot;
               BuyPrice += posPrice*posLot;  // добавить к переменной BuyPrice Цена оредра 1 * лот ордера 1
               BuyLot += posLot;             // суммируем лоты
              }
           }
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
           {
            s++; // Считаем открытые позиции на продажу
            if(posPrice > SelMaxPrice)
              {
               SelMaxPrice = posPrice;
               SelMaxLot = posLot;
               SelPrice += posPrice*posLot;  // добавить к переменной BuyPrice Цена оредра 1 * лот ордера 1
               SelLot += posLot;             // суммируем лоты
              }
           }
        }
     }
   LotBuy = b == 0 ? contractSize(Lot) : fmin(MaxLot, contractSize(BuyMinLot*MultiplicatorLot));
   LotSell = s == 0 ? contractSize(Lot) : fmin(MaxLot, contractSize(SelMaxLot*MultiplicatorLot));
//---
//--- BUY Signal
   if(StepMA_NRTR[m_bar_current]<StepMA_NRTRS[m_bar_current])
     {
      if(b == 0 || (b < MaxTrades && BuyMinPrice-tick.ask >= (Step+Delta*b)*_Point))
         openPos(ORDER_TYPE_BUY, LotBuy, tick.ask);
     }
//--- SELL Signal
   if(StepMA_NRTR[m_bar_current]>StepMA_NRTRS[m_bar_current])
     {
      if(s == 0 || (s < MaxTrades && tick.bid-SelMaxPrice >= (Step+Delta*s)*_Point))
         openPos(ORDER_TYPE_SELL, LotSell, tick.bid);
     }
//--- посчитаем математические формулы средних цен
   switch(b)
     {
      case 0 :
         return;
      case 1 :
         BuyAwerage = BuyPrice/BuyLot+TakeProfit1*_Point;
         break;
      case 2 :
         BuyAwerage = BuyPrice/BuyLot+TakeProfit1*_Point;
         break;
      case 3 :
         BuyAwerage = BuyPrice/BuyLot+TakeProfit3*_Point;
         break;
      default:
         BuyAwerage = BuyPrice/BuyLot+TakeProfit4*_Point;
         break;
     }
   switch(s)
     {
      case 0 :
         return;
      case 1 :
         SelAwerage = SelPrice/SelLot-TakeProfit1*_Point;
         break;
      case 2 :
         SelAwerage = SelPrice/SelLot-TakeProfit2*_Point;
         break;
      case 3 :
         SelAwerage = SelPrice/SelLot-TakeProfit3*_Point;
         break;
      default:
         SelAwerage = SelPrice/SelLot-TakeProfit4*_Point;
         break;
     }
   normalizePrice(BuyAwerage); // Произведем расчет цены TP Buy
   normalizePrice(SelAwerage); // Произведем расчет цены TP Sell
//---
   for(int i = 0; i < posTotal; i++)
     {
      ulong posTicket = PositionGetTicket(i);
      if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == Magic)
        {
         double posTP = PositionGetDouble(POSITION_TP);
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
           {
            if(fabs(posTP-BuyAwerage) > _Point && tick.ask < BuyAwerage) // Если тейк не равен требуемой цене
               if(!trade.PositionModify(posTicket, 0.0, BuyAwerage))
                  Print("Ошибка ", __LINE__);
           }
         if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
           {
            if(fabs(posTP-SelAwerage) > _Point && tick.bid > SelAwerage) // Если тейк не равен требуемой цене
               if(!trade.PositionModify(posTicket, 0.0, SelAwerage))
                  Print("Ошибка ", __LINE__);
           }
        }
     }
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void openPos(ENUM_ORDER_TYPE type, double lot, double price)
  {
   trade.CheckVolume(_Symbol, lot, price, type);
   if(trade.CheckResultMarginFree() <= 0.0)
     {
      Print("Not enough money for ", EnumToString(type), " ", lot, " ", _Symbol, " Error code=", trade.CheckResultRetcode());
      return;
     }
   if(!trade.PositionOpen(_Symbol, type, LotBuy, price, 0.0, 0.0))
      Print(trade.ResultRetcode());
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double contractSize(double volume, string symbol = NULL)
  {
   symbol = symbol == NULL ? _Symbol : symbol;
   double v = volume;
   double volumeStep = SymbolInfoDouble(symbol, SYMBOL_VOLUME_STEP);
   v = round(volume/volumeStep)*volumeStep;
   double minLot = SymbolInfoDouble(symbol, SYMBOL_VOLUME_MIN);
   return((v < minLot ? minLot : v));
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
double normalizePrice(double &price, string symbol = NULL)
  {
   symbol = symbol == NULL ? _Symbol : symbol;
   double tickSize = SymbolInfoDouble(symbol, SYMBOL_TRADE_TICK_SIZE);
   price = round(price/tickSize)*tickSize;
   return(tickSize);
  }
//+------------------------------------------------------------------+
//| Filling the indicator buffers from the indicator                 |
//+------------------------------------------------------------------+
bool iGetArray(const int handle,const int buffer,const int start_pos,
               const int count,double &arr_buffer[])
  {
   bool result=true;
   if(!ArrayIsDynamic(arr_buffer))
     {
      return(false);
     }
   ArrayFree(arr_buffer);
//--- reset error code
   ResetLastError();
//--- fill a part of the iBands array with values from the indicator buffer
   int copied=CopyBuffer(handle,buffer,start_pos,count,arr_buffer);
   if(copied!=count)
     {
      return(false);
     }
   return(result);
  }
//+------------------------------------------------------------------+

Советники: DVA_Martin
Советники: DVA_Martin
  • 2021.06.30
  • www.mql5.com
Статьи и техническая библиотека по автоматическому трейдингу: Советники: DVA_Martin
 
SanAlex:

J'ai ajouté un indicateur à votre conseiller expert - je pense que cela ne vous dérangera pas ! Je pense que cela s'est passé comme Sprut le voulait 185

(en jaune, je l'ai ajouté à mon conseiller expert existant ici).

Et pourquoi les valeurs de l'indicateur à partir de trois barres ? Et pourquoi basculer le tableau en série temporelle ?

En général, il me semble que ce n'est pas la bonne... Aucune Martin ne fonctionnera.

 
Alexey Viktorov:

Pourquoi avez-vous besoin des valeurs des indicateurs de trois barres ? Et pourquoi basculer le tableau en série temporelle ?

En général, il me semble que ce n'est pas le cas... Aucun martin ne fonctionnera.

L'indicateur ici n'est qu'un filtre de direction - et votre conseiller-expert s'occupe de tout.

\\\\\\\\\\\\\

L'indicateur lui-même n'ouvre pas de positions.

 
SanAlex:

L'indicateur ici est simplement un filtre directionnel - et votre expert fait toute la tâche

Le code écrit devrait faire l'affaire. Mais vous avez mis une condition telle que la Martin ne s'allumera jamais. Je pense que oui, mais je n'ai ni l'envie ni le temps de le vérifier.

 
Alexey Viktorov:

La tâche doit être accomplie par le code que vous avez écrit. Mais vous avez posé comme condition que la Martin ne s'allume jamais. Je pense que oui, mais je n'ai ni l'envie ni le temps de le vérifier.

Ici, je vérifie son fonctionnement - tout fonctionne comme prévu.

2 DVA_Martin

 
Alexey Viktorov:

Martin ne doit-il être activé que lorsque le signal de l'indicateur est opposé ou cela n'a-t-il pas d'importance ?

Exemple : Une position d'achat a été ouverte selon l'indicateur. Le prix a baissé de la distance fixée et l'indicateur montre déjà Sell. Faut-il ouvrir la position d'achat ?

Comme promis - j'ai photoshoppé quelque chose.

1

Si ce n'est pas clair, je ne pourrai expliquer le sens de mon idée que si je vous en parle en personne.

 
SanAlex:

J'ai fait quelque chose de mal ici - je ne sais pas ce qui est passé de 100 000 roubles à deux millions.

a changé l'indicateur et 5min Eurobucks en 15 jours à un million.

LeMan_BrainTrend1Sig 2

LeMan_BrainTrend1Sig

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

ajouté au conseiller expert - pour fermer le profit (de toutes les paires) et supprimer le conseiller expert

input group  "---- : Parameters:  ----"
input int    TargetProfit     = 1000000; // : Balance + Profit(add to balance)
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick(void)
  {
//---
   if(AccountInfoDouble(ACCOUNT_EQUITY)>=TargetProfit)
     {
      AllClose();
      ExpertRemove();
     }
//---

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

J'ai besoin de ces 2 indicateurs (les noms des indicateurs ne doivent pas changer).

 
SanAlex:

J'ai échangé l'indicateur et les eurobucks 5min en 15 jours contre un million.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

ajouté dans Expert Advisor - par le profit total (de toutes les paires) pour fermer le profit et supprimer Expert Advisor

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

J'ai besoin que ces deux indicateurs soient présents (c'est-à-dire que les noms des indicateurs ne changent pas).

Pas assez de stoploss dans la configuration

 

Il existe des moyens de diviser une chaîne de caractères en plusieurs chaînes de caractères à l'aide d'une méthode telle que \n".

Existe-t-il des moyens de diviser une variable de type chaîne en une seule chaîne ?

C'est-à-dire, écrire tous les textes, valeurs, paramètres, etc., qui sont disponibles dans cette variable chaîne dans une seule chaîne.

Le problème s'est produit lors de l'écriture au format csv (les valeurs des variables de chaîne sont écrites dans un ensemble de chaînes).

 
Vitaly Muzichenko:

Pas assez de stoploss dans la configuration

avec Stop Loss n'est plus le même bénéfice

Stop Loss

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

Je pense que vous devez simplement redémarrer le conseiller expert plus souvent - par exemple, j'ai pris le profit total (de toutes les paires) pour la semaine et supprimé le conseiller expert de toutes les paires.

Je pense que nous devons redémarrer l'EA jusqu'à ce que le nouveau profit total de toutes les paires soit pris.

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

une autre idée concernant le stop - stop non pas pour fermer la position mais pour ouvrir une position opposée avec beaucoup de positions ouvertes opposées (perdantes)

voici un compte rendu des positions ouvertes en lots

   int total=PositionsTotal();
   for(int i=total-1; i>=0; i--) // returns the number of open positions
     {
      string   position_GetSymbol=PositionGetSymbol(i); // GetSymbol позиции
      if(position_GetSymbol==m_symbol.Name())
        {
         if(m_position.PositionType()==POSITION_TYPE_BUY)
           {
            PROFIT_BUY=PROFIT_BUY+PositionGetDouble(POSITION_PROFIT);
            PROFIT_BUY_Lot=PROFIT_BUY_Lot+PositionGetDouble(POSITION_VOLUME);
           }
         else
           {
            PROFIT_SELL=PROFIT_SELL+PositionGetDouble(POSITION_PROFIT);
            PROFIT_SELL_Lot=PROFIT_SELL_Lot+PositionGetDouble(POSITION_VOLUME);
           }
           {
            PROFIT_CLOSE=AccountInfoDouble(ACCOUNT_PROFIT);
           }
        }
     }
//---

Stop Loss 777

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

La raison en est que le stop ne ferme pas la position et que le lot opposé devrait aider dans le trading manuel.

Raison: