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

 
datetime some_time=TimeCurrent();
//extern string Symbol3 = ""; //Инструмент (""текущий по умолчанию)
extern int P=1;          //Таймфрейм
extern int MagicNumber = 100500;  // Установили магик


int start()
{

int send;
                                     
double SL=200;                                   
double TP=200;                       
double Lots=1;       

for(int i = OrdersTotal(); i >=0; i--)                                            // цикл для проверки ордеров
{
int af=OrderSelect(i, SELECT_BY_POS,MODE_TRADES);                                // Шаг 1: OrderSelect Выбираем ордер (SELECT_BY_POS - по порядковому номеру), (MODE_TRADES -из отложенных и открытых)

if((OrderSymbol() == "EURUSD") && (OrderMagicNumber() == MagicNumber))return(0); // Шаг 2: Если символ EURUSD отсутствует,И если ордер присутствует , и ни один из ордеров НЕ содержит магикномер, то выходим из цикла.( выходим -значит откр. позицию) 
                                                                                    (если какое-либо условие из двух указанных не совпадает, то выходим) 
}
          

             
if ((Close[0]>High[1]))
{
send=OrderSend("EURUSD",OP_BUY,Lots,Ask,3,Bid-SL*Point,Bid+TP*Point,MagicNumber);
}

if ((Close[0]<Low[1]))  
{
send=OrderSend("EURUSD",OP_SELL,Lots,Bid,3,Ask+SL*Point,Ask-TP*Point,MagicNumber);
}

return(0);
}

My understanding is that it's like a periodic check for availability. (Is there EURUSD? and is there an order with the specified Magic?) If any of the conditions is missing, we open a position. Only if both of those conditions are met, we open a position.

We are then asked in Step 2. Suppose we have one order opened manually. Then we meet the first condition (we have the same symbol) and we will not meet the second condition, since this order does not contain magic. And if one of the conditions does not match, then the code should open the order. This is exactly what the code does. But at the next tick, it opens the third, fourth and fifth order.....

Why does it open a third order?

But there are two orders that meet both conditions in total. There should be a check (change to return(0)), not an opening. , not the opening.

Совершение сделок - Торговые операции - Справка по MetaTrader 5
Совершение сделок - Торговые операции - Справка по MetaTrader 5
  • www.metatrader5.com
Торговая деятельность в платформе связана с формированием и отсылкой рыночных и отложенных ордеров для исполнения брокером, а также с управлением текущими позициями путем их модификации или закрытия. Платформа позволяет удобно просматривать торговую историю на счете, настраивать оповещения о событиях на рынке и многое другое. Открытие позиций...
 
Good night all! Can you tell me if you can write a code in mql5 that will draw a line on the chart (picture attached) and record all coordinates of this line in the file? If you want to use this line as a base for the future, then you need to use it as a base for the trading robot. direct
 
GlushkoV_V_V:
Good night all! Can you tell me if you can write a code in mql5 that will draw a line on the chart (picture attached) and record all coordinates of this line in the file? If you want to draw a line and fill it with the coordinates, then you need to do a simple tracing of the line.

Everything is in the documentation.

Документация по MQL5: Графические объекты / ObjectCreate
Документация по MQL5: Графические объекты / ObjectCreate
  • www.mql5.com
[in]  Номер подокна графика. 0 означает главное окно графика. Указанное подокно должно существовать, в противном случае функция возвращает false. Возвращает true при успешной постановке команды в очередь указанного графика, иначе false. Если объект был уже создан ранее, то производится попытка изменить его координаты. При вызове ObjectCreate...
 
Сергей Таболин:

Everything is in the documentation.

Thanks for the tip, maybe you can help me build one of these for free of course.

 
GlushkoV_V_V:

Thanks for the tip, but maybe you can help me build one of these things, not for free of course.

Not for free - that's for you)))

Торговые приложения для MetaTrader 5 на заказ
Торговые приложения для MetaTrader 5 на заказ
  • www.mql5.com
Убрать из советника второй индикатор заменить другим,изменить условие открытие ордера .Условие сделки покупка: НМА линия вверх второй индикатор столбик гистограмы выше нуля (второй индикатор пересечение нуля точка входа) по закрытой свече если нма и второй индикатор не изменили показания совершается покупка для продаже наоборот.Изменить...
 
Thank you very much, but for me it's like in Chinese and I don't know how to implement it in the code.
 
Alexey Belyakov:

My understanding is that it's like a periodic check for availability. (Is there EURUSD? and is there an order with the specified Magic?) If any of the conditions is missing, we open a position. Only if both conditions are met, we open a position.

We are then asked in Step 2. Suppose we have one order opened manually. Then we meet the first condition (we have the same symbol) and we will not meet the second condition, since this order does not contain magic. And if one of the conditions does not match, then the code should open the order. This is exactly what the code does. But at the next tick, it opens the third, fourth and fifth order.....

Why does it open a third order?

But there are two orders that meet both conditions in total. There should be a check (change to return(0)), not an opening. but not the opening.

== - if it is equal != - if it is not equal. Continuity - end of loop iteration and start of a new loop iteration. Breaking - cycle termination and transition to the next operator following the cycle, return - function termination, in your case Onstart and waiting for a new tick. And if an order with your magik is open, it should end the function and leave to wait for a new tick.

Question, if you want to open an order in the current window, why do you need to specify the tool explicitly, or do you want to open orders from the window of another tool? It is also not clear how many orders you want to open. According to your code, only one order can be opened and only after it is closed, the second one will be opened. You have one magician and one open window tool. Also, the order opening conditions are checked for the Current instrument and not for the Eurobucks.

datetime some_time=TimeCurrent();
//extern string Symbol3 = ""; //Инструмент (""текущий по умолчанию)
extern int P=1;          //Таймфрейм
extern int MagicNumber = 100500;  // Установили магик


int start()
{

int send;
                                     
double SL=200;                                   
double TP=200;                       
double Lots=1;       

for(int i = OrdersTotal(); i >=0; i--)                                            // цикл для проверки ордеров
{
bool af=OrderSelect(i, SELECT_BY_POS,MODE_TRADES);     // OrderSelect возвращает тип bool                           
                                               // Шаг 1: OrderSelect Выбираем ордер 
                                   //(SELECT_BY_POS - по порядковому номеру), (MODE_TRADES -из отложенных и открытых)

if((OrderSymbol() == Symbol()) && (OrderMagicNumber() == MagicNumber))return(0); // Шаг 2: Если символ Выбранного ордера 
                                        //равен EURUSD (заменено на текущий инструмент открытого окна) ,
                                       // И если магик Выбранного ордера равен магик то выходим из функции Онстарт.
// Если же наш ордер не будет выбран из ордеров терминала, то цикл закончится и начнется выставление ордеров. 
                                                                                   
}
          

             
if ((Close[0]>High[1])) // клоз и хай здесь для текущего окна и инструмента. 
{
send=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Bid-SL*Point,Bid+TP*Point,MagicNumber); // так же здесь цены аск и бид тоже для текущего инструмента
}

if ((Close[0]<Low[1]))  
{
send=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Ask+SL*Point,Ask-TP*Point,MagicNumber); // и поинт кстати тоже.
}

return(0);
}
 
Valeriy Yastremskiy:

== - if equal != - if not equal. Kontinue - terminates the loop iteration and starts a new loop iteration. Break - terminates the loop and goes to the next operator following the loop, return - terminates the function, in your case Onstart and waits for a new tick. And if an order with your magik is open, it should end the function and leave to wait for a new tick.

Question, if you want to open an order in the current window, why do you need to specify the tool explicitly, or do you want to open orders from the window of another tool? It is also not clear how many orders you want to open. According to your code, only one order can be opened and only after it is closed, the second one will be opened. You have one magician and one open window tool. Also, the order opening conditions are checked for the Current instrument and not for the Eurobucks.

- Yes, I want to open in the current window;

- One order. The next order is not opened until the previous order is closed.

"Also, the order opening conditions are checked for the Current instrument and not the Eurobucks." - then ?

((OrderSymbol() == "EURUSD" )  ???
Документация по MQL5: Константы, перечисления и структуры / Торговые константы / Свойства ордеров
Документация по MQL5: Константы, перечисления и структуры / Торговые константы / Свойства ордеров
  • www.mql5.com
Приказы на проведение торговых операций оформляются ордерами. Каждый ордер имеет множество свойств для чтения, информацию по ним можно получать с помощью функций Идентификатор позиции, который ставится на ордере при его исполнении. Каждый исполненный ордер порождает сделку, которая открывает новую или изменяет уже существующую позицию...
 
Alexey Belyakov:

- Yes, I want to open in the current window;

- One order. The next order is not opened until the previous order is closed.

"Also the order opening conditions are checked for the Current instrument and not for the Eurobucks." - then ?

And what then, for example, you have a window open not Eurobucks, but the Eurofunt, you compare the selected order symbol with Eurobucks, if it is true, then on the Eurobucks there is an order, and if our magik, then returnee from the OnStart function, and if not, then we set an order on the Eurobucks, but Kloz, High, Asc, Bid, you will have an error when opening orders, because Bid and Asc for these instuents are different. And Symbol() will return the symbol of the current window and no error will occur.

You can use a template from the meta editor, there is a New button at the top left. OnStart function is still used, but it's not right, and OnStart is for scripts. The right template.

//+------------------------------------------------------------------+
//|                                                    forumtest.mq4 |
//|                        Copyright 2019, MetaQuotes Software Corp. |
//|                                                  https://qstr.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright 2019, MetaQuotes Software Corp."
#property link      "https://qstr.ru"
#property version   "1.00"
#property strict
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   
  }
//+------------------------------------------------------------------+

Correct code. Your order comment is missing, and the magician is not accounted for in your code. In the warnings to the opening line note Implicit type conversion of a number to a string!!!

//+------------------------------------------------------------------+
//|                                                    forumtest.mq4 |
//|                        Copyright 2019, MetaQuotes Software Corp. |
//|                                                  https://qstr.ru |
//+------------------------------------------------------------------+
#property copyright "Copyright 2019, MetaQuotes Software Corp."
#property link      "https://qstr.ru"
#property version   "1.00"
#property strict

datetime some_time=TimeCurrent();
//extern string Symbol3 = ""; //Инструмент (""текущий по умолчанию)
extern int P=1;          //Таймфрейм
extern int MagicNumber = 100500;  // Установили магик
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   int send;
                                     
double SL=200;                                   
double TP=200;                       
double Lots=1;       

for(int i = OrdersTotal(); i >=0; i--)                                            // цикл для проверки ордеров
{
bool af=OrderSelect(i, SELECT_BY_POS,MODE_TRADES);     // OrderSelect возвращает тип bool                           
                                               // Шаг 1: OrderSelect Выбираем ордер 
                                   //(SELECT_BY_POS - по порядковому номеру), (MODE_TRADES -из отложенных и открытых)

if((OrderSymbol() == Symbol()) && (OrderMagicNumber() == MagicNumber))return; // Шаг 2: Если символ Выбранного ордера 
                                        //равен EURUSD (заменено на текущий инструмент открытого окна) ,
                                       // И если магик Выбранного ордера равен магик то выходим из функции Онстарт.
// Если же наш ордер не будет выбран из ордеров терминала, то цикл закончится и начнется выставление ордеров. 
                                                                                   
}
          

             
if ((Close[0]>High[1])) // клоз и хай здесь для текущего окна и инструмента. 
{
send=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Bid-SL*Point,Bid+TP*Point,"My order",MagicNumber,0,clrGreen); // так же здесь цены аск и бид тоже для текущего инструмента

}

if ((Close[0]<Low[1]))  
{
send=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Ask+SL*Point,Ask-TP*Point,"My order",MagicNumber,0,clrGreen); // и поинт кстати тоже.
}

return;
  }
//+------------------------------------------------------------------+
 
Valeriy Yastremskiy:

there are many errors in your example

for(int i = OrdersTotal(); i >=0; i--)  

there should be:

for(int i = OrdersTotal()-1; i >=0; i--)  

here prices are not normalized OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Bid-SL*Point,Bid+TP*Point,"My order",MagicNumber,0,clrGreen);

Here I don't understand the logic why the exit from OnTick() is necessary if the condition is false.

if((OrderSymbol() == Symbol()) && (OrderMagicNumber() == MagicNumber))return;

perhaps, we should continue the loopand just count the number of orders

Your example is very simple in logic and it would be difficult to modify it for other tasks... maybe he would like to add trailing