Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1225

 
Vitaly Muzichenko:

For all. More precisely, it displays in the chart window the number of bars specified in the setting, and does not depend on the timeframe

P.S. I've never changed this value, but I've just checked it and saw that it cannot be set less than 1000.

So you need to check withiBars()?

 

Good afternoon. The script isn't working for some reason.

What's the problem?


//+------------------------------------------------------------------+
//|                                                         test.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
   
   if(!ChartSetInteger(0,CHART_IS_MAXIMIZED,true))
     {
      //--- выведем сообщение об ошибке в журнал "Эксперты"
      Print(__FUNCTION__+", Error Code = ",GetLastError());
      //return(false);
     };


  }
//+------------------------------------------------------------------+
 
Comments not related to this topic have been moved to "Questions from MQL4 MT4 MetaTrader 4 beginners".
 

Hello friends!

Questions:

1. Are Sell Stop Limit orders placed on the broker side or on the terminal side?

2. When I close the programme, will this order be triggered when the conditions are met?

Trading on the MICEX share market. Thank you in advance!

Акции: новости и аналитика фондовых рынков - Блоги трейдеров и аналитика финансовых рынков
Акции: новости и аналитика фондовых рынков - Блоги трейдеров и аналитика финансовых рынков
  • www.mql5.com
Акция — это ценная бумага, которая выпускается каким-либо предприятием (акционерным обществом) и дает ее владельцу права на получение части прибыли от этого предприятия в виде дивидендов. Также
 

Good afternoon, dear programmers. Question on MQL5

How to implement position control in MetaTrader 5? I want to have only one open position on one bar, i.e. the position should be closed no matter where - on which bar, but the opening should be on one bar only.

This code is completely ignored. What is the error?

if (OrderSelect(HistoryDealsTotal()-1))

{
datetime Cu=PositionsTotal();
int hd=iBarShift(Symbol(),_Period,Cu);
if (hd<=1)
{
return;
}
}



Совершение сделок - Торговые операции - Справка по MetaTrader 5
Совершение сделок - Торговые операции - Справка по MetaTrader 5
  • www.metatrader5.com
Торговая деятельность в платформе связана с формированием и отсылкой рыночных и отложенных ордеров для исполнения брокером, а также с управлением текущими позициями путем их модификации или закрытия. Платформа позволяет удобно просматривать торговую историю на счете, настраивать оповещения о событиях на рынке и многое другое. Открытие позиций...
 
Alexey Belyakov:

Good afternoon, dear programmers. Question on MQL5

How to implement position control in MetaTrader 5? So that on one bar there is only one open position. It means that the position is closed no matter where - on which bar, but the opening should be on one bar only.

The easiest way is to save the time of the bar opening, on which the position is opened in the global variable and then, when opening a new position, check the time of the bar opening if the value is higher than the saved value, then open a position.

 
Alexey Belyakov:

Good afternoon, dear programmers. Question on MQL5

How to implement position control in MetaTrader 5? I want to have only one open position on one bar, i.e. the position should be closed no matter where - on which bar, but the opening should be on one bar only.

This code is completely ignored. What is the error?



Error: You have mixed up the flies and the cutlets - you have mixed up the REMOTE ORDERS and the POSITIONS.

To avoid confusion, please read the reference:General Principles


The simple way above is to remember the open time of the current bar when you open a position. Then if you want to open a new position, you check the saved time and the open time of the current bar.

Storing the time of opening a position is convenient inOnTradeTransaction:

//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
  {
//--- get transaction type as enumeration value
   ENUM_TRADE_TRANSACTION_TYPE type=trans.type;
//--- if transaction is result of addition of the transaction in history
   if(type==TRADE_TRANSACTION_DEAL_ADD)
     {
      if(HistoryDealSelect(trans.deal))
         m_deal.Ticket(trans.deal);
      else
         return;
      if(m_deal.Symbol()==m_symbol.Name() && m_deal.Magic()==InpMagic)
        {
         if(m_deal.DealType()==DEAL_TYPE_BUY || m_deal.DealType()==DEAL_TYPE_SELL)
           {
            if(m_deal.Entry()==DEAL_ENTRY_IN || m_deal.Entry()==DEAL_ENTRY_INOUT)
               m_last_deal_in=iTime(m_symbol.Name(),InpTimeFrame,0);
            int size_need_position=ArraySize(SPosition);
            if(size_need_position>0)
              {
               for(int i=0; i<size_need_position; i++)
                 {
                  if(SPosition[i].waiting_transaction)
                     if(SPosition[i].waiting_order_ticket==m_deal.Order())
                       {
                        Print(__FUNCTION__," Transaction confirmed");
                        SPosition[i].transaction_confirmed=true;
                        break;
                       }
                 }
              }
           }
        }
     }
  }

and reconcile the time when the signal is triggered:

//+------------------------------------------------------------------+
//| Search trading signals                                           |
//+------------------------------------------------------------------+
bool SearchTradingSignals(void)
  {
   if(m_prev_bars==m_last_deal_in) // on one bar - only one deal
      return(true);


Example taken fromOHLC Check 2 code

Общие принципы - Торговые операции - Справка по MetaTrader 5
Общие принципы - Торговые операции - Справка по MetaTrader 5
  • www.metatrader5.com
Перед тем как приступить к изучению торговых функций платформы, необходимо создать четкое представление об основных терминах: ордер, сделка и позиция. — это распоряжение брокерской компании купить или продать финансовый инструмент. Различают два основных типа ордеров: рыночный и отложенный. Помимо них существуют специальные ордера Тейк Профит и...
 

It's a bit tricky.... somehow. No problem at the first stage " remember the opening time of the current bar"

There you go:

if (PositionsTotal()==1)  // Здесь проверяю, что открыта одна позиция
{
datetime Cu=iTime(NULL,_Period,0);        // Здесь в переменную - время открытия бара при открытой позиции

But here " you check the saved time and the opening time of the current bar." problem.

I've done about the same thing. Look at this:

if (PositionsTotal()==1)  // Здесь проверяю, что открыта одна позиция (или была открыта, неважно, любое торговое действие)
{
datetime Cu=iTime(NULL,_Period,0);        // Здесь в переменную - время открытия бара при открытой позиции
int hd=+iBarShift(Symbol(),_Period,Cu)+1;    // Здесь в переменную - бар на котором произошло открытие позиции 
if (hd>=1)                                //Здесь проверяем - если этих баров, больше чем один, то.......   
{
return; //....то зацикливанием программу, НО проблема только в return
}
}

All I need to do here is to loop a walk like "return(-1)" But I can't assign an expression to the return because of the void. How do I get around this? How to loop but not return?

Документация по MQL5: Константы, перечисления и структуры / Торговые константы / Свойства позиций
Документация по MQL5: Константы, перечисления и структуры / Торговые константы / Свойства позиций
  • www.mql5.com
Тикет позиции. Уникальное число, которое присваивается каждой вновь открытой позиции. Как правило, соответствует тикету ордера, в результате которого она была открыта, за исключением случаев изменения тикета в результате служебных операций на сервере. Например, начисления свопов переоткрытием позиции. Для нахождения ордера, которым была открыта...
 
datetime PR=iTime(NULL,_Period,0);  // проверяю время открытие бара
if (PositionsTotal()==1)  
{
datetime TK=iTime(NULL,_Period,0);  // время открытия бара при открытой позиции                        
if (PR==TK)                         // сравниваю
{
return(true);  // НЕ катит true - ошибка 
}
}


That didn't work either.

 
Alexey Belyakov:

It's a bit tricky.... somehow. No problem at the first stage " remember the opening time of the current bar"

There you go:

But here " you reconcile the saved time and the opening time of the current bar." problem.

I've done about the same thing. Look at this:

All I need to do here is to loop a walk like "return(-1)" But I can't assign an expression to the return because of the void. How do I get around this? How to loop but not return?

The treatment for looping programs is cutting their arms around their necks. So that you don't have to do it again in the future.


Here's what you need - the whole program body, you just need to formalize signal reception:

//+------------------------------------------------------------------+
//|                              Example One position on one bar.mq5 |
//|                        Copyright 2020, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
#include <Trade\DealInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
CDealInfo      m_deal;                       // object of CDealInfo class
//--- input parameters
input ulong    InpMagic             = 200;      // Magic number
//---
datetime m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
datetime m_last_deal_in             = 0;        // "0" -> D'1970.01.01 00:00';
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
   RefreshRates();
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(m_symbol.Name(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;
   if(!RefreshRates())
     {
      m_prev_bars=0;
      return;
     }
//--- search for trading signals
   if(!SearchTradingSignals())
     {
      m_prev_bars=0;
      return;
     }
  }
//+------------------------------------------------------------------+
//| TradeTransaction function                                        |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
                        const MqlTradeRequest &request,
                        const MqlTradeResult &result)
  {
//--- get transaction type as enumeration value
   ENUM_TRADE_TRANSACTION_TYPE type=trans.type;
//--- if transaction is result of addition of the transaction in history
   if(type==TRADE_TRANSACTION_DEAL_ADD)
     {
      if(HistoryDealSelect(trans.deal))
         m_deal.Ticket(trans.deal);
      else
         return;
      if(m_deal.Symbol()==m_symbol.Name() && m_deal.Magic()==InpMagic)
        {
         if(m_deal.DealType()==DEAL_TYPE_BUY || m_deal.DealType()==DEAL_TYPE_SELL)
           {
            if(m_deal.Entry()==DEAL_ENTRY_IN || m_deal.Entry()==DEAL_ENTRY_INOUT)
               m_last_deal_in=iTime(m_symbol.Name(),Period(),0);
           }
        }
     }
  }
//+------------------------------------------------------------------+
//| Search trading signals                                           |
//+------------------------------------------------------------------+
bool SearchTradingSignals(void)
  {
   if(m_prev_bars==m_last_deal_in) // on one bar - only one deal
      return(true);
//--- signal
//---
   return(false);
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");
      return(false);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+


The variable'm_prev_bars' stores the open time of the current bar and the variable'm_last_deal_in' stores the open time of the bar at which the position was opened.

These two variables are compared in the block for getting signals'SearchTradingSignals'.

Reason: