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" поместим в переменную PositionInfoMqlTick 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; //Укажем размер нашего лота//+------------------------------------------------------------------+//| Инструкции которые срабатывают один раз при запуске эксперта |//+------------------------------------------------------------------+intOnInit()
{
Trade.SetExpertMagicNumber(MagicNumber); //Занесём наш номер в переменную Trade
Lot=1; //Установим размер нашего лотаreturn(0);
}
//+------------------------------------------------------------------+//| Инструкции которые срабатывают один раз при остановке (закрытии) эксперта |//+------------------------------------------------------------------+voidOnDeinit(constint reason)
{
}
//+------------------------------------------------------------------+//| Инструкции которые срабатывают при каждом новом тике цен |//+------------------------------------------------------------------+voidOnTick()
{
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);
}
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)!
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)?
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.
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:
Thanks in advance for your help :)
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:
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!"]?
In your example, the keys are numbers, and I meant using strings as keys.
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)?
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)?