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

 
ponochka :
Hello! Help me do the following:
It is necessary to make a target profit for each open position in the market, but not a general one, but a separate one!
example: EURUSD opened and it has a target profit of $ 1 in its settings, and as soon as it reached it, the position closed itself, only it!
and so each currency pair should work on its own, and not according to the total profit!

I found the code for the total profit for all pairs:
help me redo it for each currency pair separately ...... Thank you in advance!

If you dig, you can find it.

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

 
Hello. Can someone please explain to an inexperienced person why the function

doubleiOpen(
stringsymbol,// symbol
inttimeframe,// period
intshift// shift
);

if I insert the symbol name of an instrument, as it says in the manual,(not 0 and not NULL) and run it in the tester on the chart, I get the answer 0.0? At the same time 0 and NULL gives correct values. Thank you.

 
novichok2018:
Hello. Can someone explain to an inexperienced person why the function

doubleiOpen(
stringsymbol,// symbol
inttimeframe,// period
intshift// shift
);

If I insert a symbolic tool name as it says in the handbook,(not 0 and not NULL) and run it in the tester on the chart, I get a 0.0 response? At the same time 0 and NULL give the correct values. Thank you.

Oops, sorry, careless: I just missed one letter in instrument name. It's OK - a linguist is a linguist.

 
novichok2018:

Oops, sorry, I wasn't paying attention: I just missed one letter in the instrument name. It's OK - a linguist is a linguist.

And now I have another question: why double DJop1 = iOpen("DowJones30",PERIOD_H1,1) launched on another instrument (not DowJones30) produces correct values, while double DJbid = MarketInfo("DowJones30",MODE_BID) produces 0.0, though it works fine on DowJones30?

 
Alekseu Fedotov:

Thank you, it's not clear, the position is now plus, but it says 0.25.

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

Thank you, it's not clear, now the position is on the plus side, but it says 0.25.

That's right, do the math.

 
 
Seric29:

Who can help with this 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: initialized

 
Igor Makanu:

i.e. despite applying the template, you still need to assign the type

A<double> MyStructDouble;

And with classes, what would this code look like, apply a template to a class.

 
Seric29:

i.e. despite applying the template, you still need to assign the type

And with classes how would this code look like, apply a template to a class.

C++ is based on MQL, all C-like languages are strictly typed - google to help.

Exactly like my example, replace struct with class