Questions from Beginners MQL5 MT5 MetaTrader 5 - page 389

 

Good day to all.

I've started to study MQL5 programming not so long ago, got acquainted with documentation and watched some webinars on youtube. I managed to make some humble steps :) I've been working on it for three days now :( I would like to ask the professionals for some help.

The general concept is as follows: first, we get the Ask and Bid prices (I used MqlTick and SymbolInfoTick for this purpose), then we look whether there is an open deal or not (I used PositionsTotal for this purpose), if there are no open positions, we open a position at Ack or Bid prices according to a certain condition. Namely, if we had a previous trade to buy and it turned out to be positive (we bought low and closed high), we will open a new position to buy... That is in general terms :) The problem is that I can not get information about what was the type of last transaction and consequently at what price it opened and at what price it closed ...

Here is the code I wrote:

//+------------------------------------------------------------------+

//|                                                  SOVETNIK_01.mq5 |

//|                                                   Tokarev Sergey |

//|                                             https://www.mql5.com |

//+------------------------------------------------------------------+

#property copyright "Tokarev Sergey"

#property link      "https://www.mql5.com"

#property version   "1.00"



//Мои подключаемые библиотеки

#include<Trade\Trade.mqh>           //Библиотека для структуры "CTrade", она отвечает за выполнение всех торговых операций

#include <Trade\PositionInfo.mqh>   //Библиотека для структуры "CPositionInfo" она выдаёт информацию по всем нашим позициям



//переменные для подключаемых классов и структур опишем тут

CTrade Trade;                 //Значение структуры "CTrade" поместим в переменную Trade

CPositionInfo PositionInfo;   //Значение структуры "CPositionInfo" поместим в переменную PositionInfo

MqlTick last_tick;            //В переменной last_tick будут храниться цены последнего пришедшего тика, для этого используем структуру "MqlTick"

MqlTradeRequest request;

MqlTradeResult result;

//глобальные переменные

double SL;                           //Переменная необходимая для преобразования размера StopLoss в зависимости от типа брокера

double TP;                           //Переменная необходимая для преобразования размера TakeProfit в зависимости от типа брокера

double Ask;                          //Переменная в которой будем хранить значения цены спроса

double Bid;                          //Переменная в которой будем хранить значение цены предложения

int MagicNumber=123456;    //Зададим MagicNumber для идентификации своих ордеров

int N;                     //В переменную N мы занесём кол-во открытых позиций                  

int Lot;                    //Укажем размер нашего лота

//+------------------------------------------------------------------+

//| Инструкции которые срабатывают один раз при запуске эксперта                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

   Trade.SetExpertMagicNumber(MagicNumber);        //Занесём наш номер в переменную Trade

   Lot=1;                                                  //Установим размер нашего лота

   return(0);

  }

//+------------------------------------------------------------------+

//| Инструкции которые срабатывают один раз при остановке (закрытии) эксперта                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

  }

//+------------------------------------------------------------------+

//| Инструкции которые срабатывают при каждом новом тике цен                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

   SymbolInfoTick(_Symbol,last_tick);   //Заполняем переменную last_tick последними ценами текущего символа, для этого используем "SymbolInfoTick"

   //Обновляем переменные Ask и Bid для дальнейшего использования

   Ask=last_tick.ask;

   Bid=last_tick.bid;

   Print("Цена ПРОДАЖИ = ",Ask);

   Print("Цена ПОКУПКИ = ",Bid);

//Определим существует ли открытая позиция или нет

   N=PositionsTotal();

   Print("Кол-во открытых позиций: ",N); 

   if(N==0)

      {

      //Если позиции нет то определим какая сделка была крайней

      HistorySelect(0,TimeCurrent());        //Загружаем историю наших сделок

      ulong last_deal_ticket;                   //Объявим переменную для тикета последней сделки

      ulong deals=HistoryOrdersTotal();      //Обяъвим переменную "deals" куда выгрузим количество наших сделок в целом из истории

      last_deal_ticket=HistoryDealGetTicket((int)deals-1); //получим тикет крайней сделки

      Print("Ticket крайней сделки: ",last_deal_ticket);

      long deal_type=HistoryDealGetInteger(last_deal_ticket,DEAL_TYPE); //Тут получить должны тип крайней сделки из истории

      Print ("Тип крайней ",deal_type);      

      //Если была на продажу то покупаем

      if (deal_type==BUY)

         {

         //Открываем наш ордер на покупку

         Trade.Buy(Lot,Symbol(),Ask,SL,TP);

         Print("Мы купили по цене: ",Ask);

} 

 

Thanks in advance for your help :)

Автоматический трейдинг и тестирование торговых стратегий
Автоматический трейдинг и тестирование торговых стратегий
  • www.mql5.com
MQL5: язык торговых стратегий для MetaTrader 5, позволяет писать собственные торговые роботы, технические индикаторы, скрипты и библиотеки функций
 
Karputov Vladimir:
I moved away from paper books a long time ago, as well as from pirate books in electronic form. I got used to it.

You can't live beautifully.

I have newcomers asking me what to read and I don't remember what I have.

 

Good day to all!

I need to get from the input field in the EA window the timeframe selected by the user from the drop-down list. How to use it in the function, I'm struggling with it for the second day in a row, please advise me)!

Code:

input enum timeFrame {
Hour_1 = 60,
Hour_4 = 240,
Day_1 = 1440,
Week_1 = 10080!

};


iADX(currencySelect, THIS IS HOW TO INSTALL SELECTED DATA!, ADXparam, PRICE_CLOSE, MODE_MINUSDI,2)


Thank you!

 
Сергей Михеев:

Inserting the code correctly in the forum

Here's a sample script, applying your enumeration:

//+------------------------------------------------------------------+
//|                                                       Primer.mq5 |
//|                        Copyright 2015, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
#property script_show_inputs
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
enum timeFrame
  {
   Hour_1 = 60,
   Hour_4 = 240,
   Day_1=1440,
   Week_1=10080
  };
input timeFrame MyTimeFrame=Hour_1;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   Print(MyTimeFrame);
  }
//+------------------------------------------------------------------+
 
Karputov Vladimir:

Inserting the code correctly in the forum

Here's a sample script, using your listing:

Thank you!

And more, please tell me, is there a construction in MQ4 like associative array with text keys, for example: Array["Here is the key!"]?

 
Сергей Михеев:

Thank you!

Also, could you please tell me if MQ4 has a construction like associative array with text keys, for example: Array["Here is the key!"]?

//+------------------------------------------------------------------+
//|                                                         Test.mq5 |
//|                        Copyright 2015, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
#define  Number                1
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnStart()
  {
   int Arr[]={ 12,15,4 };
   Print(Arr[Number]);
  }
//+------------------------------------------------------------------+
 
Karputov Vladimir:
In your example the keys are numbers and I meant using strings as a key.
 
Сергей Михеев:
In your example, the keys are numbers, and I meant using strings as keys.
The array elements are accessed by index. The index is an integer int type.
 

Hello!

Can you please advise how to get information about open and closed trades in MQL EA code (what price was opened, what were the TP and SL)? at least for the last 1.

And is there any built-in function or library that returns an array with n last values of moving average(preferably weighted or exponential)?

 
Alex317:

Hello!

Can you please advise how to get information about open and closed trades in MQL EA code (what price was opened, what were the TP and SL)? at least for the last 1.

And is there any built-in function or library that returns an array with n last values of moving average(preferably weighted or exponential)?

Please always specify which version of MQL4 or MQL5 your question is for.
Reason: