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

 
ponochka :
Bonjour! Aidez-moi à faire ce qui suit :
Il est nécessaire de réaliser un bénéfice cible pour chaque position ouverte sur le marché, mais pas général, mais distinct !
exemple : EURUSD s'est ouvert et il a un objectif de profit de 1$ dans ses paramètres, et dès qu'il l'a atteint, la position s'est fermée, rien qu'elle !
et donc chaque paire de devises devrait fonctionner pour elle-même, et non en fonction du profit total !

J'ai trouvé le code du profit total pour toutes les paires :
aidez-moi à le refaire pour chaque paire de devises séparément...... Merci d'avance !

Si vous creusez, vous pouvez le trouver.

 //+----------------------------------------------------------------------------+
//|                                          e-CloseByProfitPosInCurrency.mq4  |
//|                                                                            |
//|                                                    Ким Игорь В. aka KimIV  |
//|                                                       http://www.kimiv.ru  |
//|                                                                            |
//|  22.04.2008  Советник закрывает только те позиции, у которых профит        |
//|              в валюте депозита превысил некоторое заданное значение.       |
//+----------------------------------------------------------------------------+
#property copyright "Ким Игорь В. aka KimIV"
#property link        "http://www.kimiv.ru"


//------- Внешние параметры советника -----------------------------------------+
string _P_Expert = "---------- Параметры советника" ;
extern int     NumberAccount = 0 ;       // Номер торгового счёта
extern string symbol        = "" ;       // Торговый инструмент
                                       //   ""  - любой
                                       //   "0" - текущий
extern int     Operation     = - 1 ;       // Торговая операция:
                                       //   -1 - любая
                                       //    0 - OP_BUY
                                       //    1 - OP_SELL
extern double Profit        = 50 ;       // Профит в валюте депозита
extern int     MagicNumber   = 0 ;       // MagicNumber
extern bool    ShowComment   = True;     // Показывать комментарий


//------- Глобальные переменные советника -------------------------------------+
bool    gbNoInit      = False;           // Флаг неудачной инициализации
int     Slippage      = 3 ;               // Проскальзывание цены
int     NumberOfTry   = 5 ;               // Количество торговых попыток
bool    UseSound      = True;           // Использовать звуковой сигнал
string NameFileSound = "expert.wav" ;   // Наименование звукового файла
color   clCloseBuy    = Blue;           // Цвет значка закрытия покупки
color   clCloseSell   = Red;             // Цвет значка закрытия продажи

//------- Подключение внешних модулей -----------------------------------------+
#include <stdlib.mqh>             // Стандартная библиотека


//+----------------------------------------------------------------------------+
//|                                                                            |
//|  ПРЕДОПРЕДЕЛЁННЫЕ ФУНКЦИИ                                                  |
//|                                                                            |
//+----------------------------------------------------------------------------+
//|  expert initialization function                                            |
//+----------------------------------------------------------------------------+
void init() {
  gbNoInit = False;
   if (!IsTradeAllowed()) {
    Message( "Для нормальной работы советника необходимо\n" +
             "Разрешить советнику торговать" );
    gbNoInit=True; return ;
  }
   if (!IsLibrariesAllowed()) {
    Message( "Для нормальной работы советника необходимо\n" +
             "Разрешить импорт из внешних экспертов" );
    gbNoInit=True; return ;
  }
   if (Operation<- 1 || Operation> 1 ) {
    Message( "Недопустимое значение внешнего параметра Operation" );
    gbNoInit=True; return ;
  }
   if (symbol!= "0" && symbol!= "" ) {
     if (MarketInfo(StringUpper(symbol), MODE_BID)== 0 ) {
      Message( "В обзоре рынка отсутствует символ " +symbol);
      gbNoInit=True; return ;
    }
  }
   if (!IsTesting()) {
     if (IsExpertEnabled()) Message( "Советник будет запущен следующим тиком" );
     else Message( "Отжата кнопка \"Разрешить запуск советников\"" );
  }
}

//+----------------------------------------------------------------------------+
//|  expert deinitialization function                                          |
//+----------------------------------------------------------------------------+
void deinit() { if (!IsTesting()) Comment ( "" ); }

//+----------------------------------------------------------------------------+
//|  expert start function                                                     |
//+----------------------------------------------------------------------------+
void start() {
   if (gbNoInit) {
     Comment ( "Не удалось инициализировать советник!" ); return ;
  }
   if (!IsTesting()) {
     if (NumberAccount> 0 && NumberAccount!=AccountNumber()) {
       Comment ( "Работа на счёте: " +AccountNumber()+ " ЗАПРЕЩЕНА!" );
       return ;
    } else Comment ( "" );
     if (ShowComment) {
       string st= "NumberAccount=" +DoubleToStr(NumberAccount, 0 )
               + "  Symbol=" +IIFs(symbol== "0" , "All" , IIFs(symbol== "" , Symbol (), StringUpper(symbol)))
               + "  Operation=" +IIFs(Operation< 0 , "All" , GetNameOP(Operation))
               + "  Profit=" +DoubleToStr(Profit, 2 )+ " " +AccountCurrency()
               + "  MagicNumber=" +DoubleToStr(MagicNumber, 0 )
               +IIFs(ShowComment, "  ShowComment" , "" )
               ;
       Comment (st);
    } else Comment ( "" );
  }

  ClosePosBySizeProfitInCurrency(StringUpper(symbol), Operation, MagicNumber, Profit);
}


//+----------------------------------------------------------------------------+
//|                                                                            |
//|  ПОЛЬЗОВАТЕЛЬСКИЕ ФУНКЦИИ                                                  |
//|                                                                            |
//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия  : 19.02.2008                                                      |
//|  Описание: Закрытие одной предварительно выбранной позиции                 |
//+----------------------------------------------------------------------------+
void ClosePosBySelect() {
   bool    fc;
   color   clClose;
   double ll, pa, pb, pp;
   int     err, it;

   if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
     for (it= 1 ; it<=NumberOfTry; it++) {
       if (!IsTesting() && (!IsExpertEnabled() || IsStopped ())) break ;
       while (!IsTradeAllowed()) Sleep ( 5000 );
      RefreshRates();
      pa=MarketInfo(OrderSymbol(), MODE_ASK);
      pb=MarketInfo(OrderSymbol(), MODE_BID);
       if (OrderType()==OP_BUY) {
        pp=pb; clClose=clCloseBuy;
      } else {
        pp=pa; clClose=clCloseSell;
      }
      ll=OrderLots();
      fc=OrderClose(OrderTicket(), ll, pp, Slippage, clClose);
       if (fc) {
         if (UseSound) PlaySound (NameFileSound); break ;
      } else {
        err= GetLastError ();
         if (err== 146 ) while (IsTradeContextBusy()) Sleep ( 1000 * 11 );
         Print ( "Error(" ,err, ") Close " ,GetNameOP(OrderType()), " " ,
              ErrorDescription(err), ", try " ,it);
         Print (OrderTicket(), "  Ask=" ,pa, "  Bid=" ,pb, "  pp=" ,pp);
         Print ( "sy=" ,OrderSymbol(), "  ll=" ,ll, "  sl=" ,OrderStopLoss(),
               "  tp=" ,OrderTakeProfit(), "  mn=" ,OrderMagicNumber());
         Sleep ( 1000 * 5 );
      }
    }
  } else Print ( "Некорректная торговая операция. Close " ,GetNameOP(OrderType()));
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 19.02.2008                                                     |
//|  Описание : Закрытие тех позиций, у которых профит в валюте депозита       |
//|             превысил некоторое значение                                    |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    sy - наименование инструмента   (""   - любой символ,                   |
//|                                     NULL - текущий символ)                 |
//|    op - операция                   (-1   - любая позиция)                  |
//|    mn - MagicNumber                (-1   - любой магик)                    |
//|    pr - профит                                                             |
//+----------------------------------------------------------------------------+
void ClosePosBySizeProfitInCurrency( string sy= "" , int op=- 1 , int mn=- 1 , double pr= 0 ) {
   int i, k= OrdersTotal ();

   if (sy== "0" ) sy= Symbol ();
   for (i=k- 1 ; i>= 0 ; i--) {
     if ( OrderSelect (i, SELECT_BY_POS, MODE_TRADES)) {
       if ((OrderSymbol()==sy || sy== "" ) && (op< 0 || OrderType()==op)) {
         if (OrderType()==OP_BUY || OrderType()==OP_SELL) {
           if (mn< 0 || OrderMagicNumber()==mn) {
             if (OrderProfit()+OrderSwap()>pr) ClosePosBySelect();
          }
        }
      }
    }
  }
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает наименование торговой операции                      |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    op - идентификатор торговой операции                                    |
//+----------------------------------------------------------------------------+
string GetNameOP( int op) {
   switch (op) {
     case OP_BUY      : return ( "Buy" );
     case OP_SELL     : return ( "Sell" );
     case OP_BUYLIMIT : return ( "Buy Limit" );
     case OP_SELLLIMIT: return ( "Sell Limit" );
     case OP_BUYSTOP  : return ( "Buy Stop" );
     case OP_SELLSTOP : return ( "Sell Stop" );
     default           : return ( "Unknown Operation" );
  }
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.02.2008                                                     |
//|  Описание : Возвращает одно из двух значений взависимости от условия.      |
//+----------------------------------------------------------------------------+
string IIFs( bool condition, string ifTrue, string ifFalse) {
   if (condition) return (ifTrue); else return (ifFalse);
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Вывод сообщения в коммент и в журнал                           |
//+----------------------------------------------------------------------------+
//|  Параметры:                                                                |
//|    m - текст сообщения                                                     |
//+----------------------------------------------------------------------------+
void Message( string m) {
   Comment (m);
   if ( StringLen (m)> 0 ) Print (m);
}

//+----------------------------------------------------------------------------+
//|  Автор    : Ким Игорь В. aka KimIV,  http://www.kimiv.ru                   |
//+----------------------------------------------------------------------------+
//|  Версия   : 01.09.2005                                                     |
//|  Описание : Возвращает строку в ВЕРХНЕМ регистре                           |
//+----------------------------------------------------------------------------+
string StringUpper( string s) {
   int c, i, k= StringLen (s), n;
   for (i= 0 ; i<k; i++) {
    n= 0 ;
    c=StringGetChar(s, i);
     if (c> 96 && c< 123 ) n=c- 32 ;     // a-z -> A-Z
     if (c> 223 && c< 256 ) n=c- 32 ;   // а-я -> А-Я
     if (c== 184 ) n= 168 ;             //  ё  ->  Ё
     if (n> 0 ) s=StringSetChar(s, i, n);
  }
   return (s);
}
//+----------------------------------------------------------------------------+

 
Bonjour. Quelqu'un peut-il expliquer à une personne inexpérimentée pourquoi la fonction

doubleiOpen(
symbole de chaîne de caractères,// symbole
inttimeframe,// période
intshift// shift
);

si j'insère le nom du symbole d'un instrument, comme il est indiqué dans le manuel, (pas 0 et pas NULL) et que je l'exécute dans le testeur sur le graphique, j'obtiens la réponse 0.0 ? En même temps, 0 et NULL donnent des valeurs correctes. Merci.

 
novichok2018:
Bonjour. Quelqu'un peut-il expliquer à une personne inexpérimentée pourquoi la fonction

doubleiOpen(
chaîne de caractèressymbole,// symbole
inttimeframe,// période
intshift// shift
) ;

Si j'insère un nom d'outil symbolique comme il est indiqué dans le manuel (pas 0 et pas NULL) et que je l'exécute dans le testeur sur le graphique, est-ce que j'obtiens une réponse 0.0 ? En même temps, 0 et NULL donnent les valeurs correctes. Merci.

Oups, désolé, imprudent : j'ai juste oublié une lettre dans le nom de l'instrument. C'est bon, un linguiste est un linguiste.

 
novichok2018:

Oups, désolé, je n'étais pas attentif : j'ai juste oublié une lettre dans le nom de l'instrument. C'est bon, un linguiste est un linguiste.

Et maintenant j'ai une autre question : pourquoi le double DJop1 = iOpen("DowJones30",PERIOD_H1,1) lancé sur un autre instrument (pas DowJones30) produit des valeurs correctes, alors que le double DJbid = MarketInfo("DowJones30",MODE_BID) produit 0.0, alors qu'il fonctionne bien sur DowJones30 ?

 
Alekseu Fedotov:

Merci, ce n'est pas clair, la position est maintenant plus, mais il est dit 0,25.

void OnTick()
  {
//---
   double drawdown=AccountProfit()*100/AccountBalance();
   Comment("текущая просадка  = ",drawdown);
  }
Dossiers :
htygj.jpg  421 kb
 
nalyk:

Merci, ce n'est pas clair, maintenant la position est du côté positif, mais il est écrit 0,25.

C'est vrai, faites le calcul.

 
 
Seric29:

Qui peut aider avec cette question https://www.mql5.com/ru/forum/160683/page897#comment_12221175 ?

#property strict

template<typename T>struct A
  {
   T                 val;
   int               ind;
  };
  A<double> MyStructDouble;
  
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   MyStructDouble.val = 123.456;
   MyStructDouble.ind = 123;
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
  Print("MyStructDouble.val = ",MyStructDouble.val," , MyStructDouble.ind = ",MyStructDouble.ind);
  }
//+------------------------------------------------------------------+ 

2019.06.27 14:20:36.265 test EURUSD,H1 : MyStructDouble.val = 123.456 , MyStructDouble.ind = 123

2019.06.27 14:20:35.700 test EURUSD,H1 : MyStructDouble.val = 123.456 , MyStructDouble.ind = 123

2019.06.27 14:20:35.427 test EURUSD,H1 : MyStructDouble.val = 123.456 , MyStructDouble.ind = 123

2019.06.27 14:20:34.758 test EURUSD,H1 : initialisé

 
Igor Makanu:

c'est-à-dire que malgré l'application du modèle, vous devez toujours attribuer le type

A<double> MyStructDouble;

Et avec les classes, à quoi ressemblerait ce code, appliquer un modèle à une classe.

 
Seric29:

c'est-à-dire que malgré l'application du modèle, vous devez toujours attribuer le type

Et avec les classes, à quoi ressemblerait ce code, appliquer un modèle à une classe.

C++ est basé sur MQL, tous les langages de type C sont strictement typés - google pour vous aider.

Exactement comme mon exemple, en remplaçant struct par class

Raison: