Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1116

 
Artyom Trishkin:

And how do you check if a position has not been opened on this bar yet?

Maybe we should modify Aleksey Vazhmikin's function a bit and add a structure to control opening of a position on a new bar in this way:

struct open_bar {
   bool     IsPositionOpened; // Flag
   int      bn;               // Bar Number
   datetime bot;              // Bar Open Time
   double   bop;              // Bar Open Price
}; 
open_bar BarOpen;

//+------------------------------------------------------------------------------------------------------------------+
//| Возвращает TRUE, если появился новый бар на текущем ТФ
//+------------------------------------------------------------------------------------------------------------------+
bool isNewBar()
  {
   datetime tm[];
   static datetime prevBarTime=0;

   if(CopyTime(_Symbol,0,0,1,tm)<0)
     {
      Print("%s CopyTime error = %d",__FUNCTION__,GetLastError());
     }
   else
     {
      if(prevBarTime!=tm[0])
        {
         prevBarTime=tm[0];
         BarOpen.IsPositionOpened=false;
         BarOpen.bn++;
         BarOpen.bot=iTime(NULL,PERIOD_CURRENT,0);
         BarOpen.bop=iOpen(NULL,PERIOD_CURRENT,0);
         return true;
        }
      return false;
     }
   return true;
  }

And then raise the control flag in the Expert Advisor when a position is successfully opened:

BarOpen.IsPositionOpened=true;

And control it before opening another position. Is it more reliable?

 
Grigori.S.B:

The second position opens immediately after the first, in the same second, the ticks differ by one.

 

Thanks for all your help. I have studied everything in detail. I have a 5 sec delay after each trade request but still not helping. The problem is just on ICMarkets demo MT5 hedge. I will add checks and output the results of status polling. The situation is aggravated by the fact that I can't reproduce the problem with myself and the client has it regularly, even though we connect to the same server.

 
Hello gentlemen! Is there anyone from Simferopol?
 
Олег Юдин:
Hello Ladies and Gentlemen! Is there anyone from Simferopol?

So you think this will somehow help you in learning MQL5 :) . This is an MQL5 programming forum, not a dating club.

 
Vladimir Karputov:

So you think this will somehow help you in learning MQL5 :) . This is an MQL5 programming forum, not a dating club.

I myself have a good understanding of mql5 programming, not perfect, but not bad!
 
Grigori.S.B:

Thank you for all your help. I have studied everything in detail. I have a 5 sec delay after each trade request, but still no help. The problem is just on ICMarkets demo MT5 hedge. I will add checks and output the results of status polling. The situation is aggravated by the fact that I can't reproduce the problem with myself and the client has it regularly, even though we connect to the same server.

I think it has something to do with the quality of the client's connection, e.g. high ping. You do have a 5 second delay, but it's just not there, as I understand from your code. What does the m_trade class return? Ticket number? Or true or false? You have a check for the result returned by this object, but imagine that because of a delay in connection with the server a positive response has not been received yet. What will be the result of executing the if statement? Probably, it will be false and as a result your loop will go to the second iteration after 5 seconds. And at last the server will finally reply, but the second iteration will already be initiated and a second request to open a similar position will be sent. The fact that there is some delta in the order opening time is shown by the fact that both orders are shifted in the chart, which means that they have been executed at different times and prices.

 
Grigori.S.B:

The situation is aggravated by the fact that I can't reproduce the problem with myself, but with the customer it occurs regularly, even though we connect to the same server.

Check on the bar, one position per symbol. Most likely you will get rid of the problem.

 
Konstantin Nikitin:

Check on the bar, one position per symbol. You will probably get rid of the problem.

There's another hitch there. In this situation it's easier to rewrite to MT4-style than to come up with a crutch.

 

Good day everyone!

Here is part of the script code for Metatrader5:

#property copyright "Copyright 2019, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
//---- показывать входные параметры
#property script_show_inputs
//---
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
CTrade         m_trade;                      // trading object
CSymbolInfo    m_symbol;                     // symbol info object
//+------------------------------------------------------------------+
//| Enum Stop or Limit                                               |
//+------------------------------------------------------------------+
enum ENUM_STOP_OR_LIMIT
  {
   stop=0,     // Buy stop and Sell stop
   limit=1     // Buy limit and Sell limit
  };
//--- input parameters
input ushort               InpUpGap          = 15;    // Gap for pending orders UP from the current price (in points)
input ushort               InpUpStep         = 30;    // Step between orders UP (in points)

input ushort               InpDownGap        = 15;    // Gap for pending orders DOWN from the current price (in points)
input ushort               InpDownStep       = 30;    // Step between orders DOWN (in points)

input ENUM_STOP_OR_LIMIT   InpPending        = stop;  // Type of pending orders

input uchar                InpUpQuantity     = 1;     // UP quantity orders
input uchar                InpDownQuantity   = 1;     // DOWN quantity orders

input double               InpLots           = 0.01;  // Lots
input ushort               InpStopLoss       = 50;    // Stop Loss (in points)
input ushort               InpTakeProfit     = 50;    // Take Profit (in points)
//---
ulong                      m_slippage=30;             // slippage

double                     ExtUpGap=0.0;
double                     ExtUpStep=0.0;

double                     ExtDownGap=0.0;
double                     ExtDownStep=0.0;

double                     ExtStopLoss=0.0;
double                     ExtTakeProfit=0.0;
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   if(InpLots<=0.0)
     {
      Print("The \"Lots\" can't be smaller or equal to zero");
      return;
     }
//---
   if(!m_symbol.Name(Symbol())) // sets symbol name
      return;
   if(!RefreshRates())
      return;

   string err_text="";
   if(!CheckVolumeValue(InpLots,err_text))
     {
      Print(err_text);
      return;
     }

//---
   if(IsFillingTypeAllowed(SYMBOL_FILLING_FOK))
      m_trade.SetTypeFilling(ORDER_FILLING_FOK);
   else
      if(IsFillingTypeAllowed(SYMBOL_FILLING_IOC))
         m_trade.SetTypeFilling(ORDER_FILLING_IOC);
      else
         m_trade.SetTypeFilling(ORDER_FILLING_RETURN);

//---
   m_trade.SetDeviationInPoints(m_slippage);
   m_trade.SetAsyncMode(true);

//---
   ExtUpGap = m_symbol.Point() * InpUpGap;
   ExtUpStep = m_symbol.Point() * InpUpStep;

   ExtDownGap = m_symbol.Point() * InpDownGap;
   ExtDownStep = m_symbol.Point() * InpDownStep;

   ExtStopLoss = m_symbol.Point() * InpStopLoss;
   ExtTakeProfit = m_symbol.Point() * InpTakeProfit;

//--- start work
   double start_price_ask=m_symbol.Ask()-ExtUpGap;
   double start_price_bid=m_symbol.Bid()+ExtDownGap;

//--- set pending orders
   for(int i=0; i<InpUpQuantity; i++)
     {
      double price_ask = start_price_ask+i*ExtUpStep;
      double price_bid = start_price_bid+i*ExtUpStep;
      if(InpPending==stop)
        {
         double sl = (ExtStopLoss==0.0)   ? 0.0 : price_ask - ExtStopLoss;
         double tp = (ExtTakeProfit==0.0) ? 0.0 : price_ask + ExtTakeProfit;
         m_trade.BuyStop(InpLots,m_symbol.NormalizePrice(price_ask),m_symbol.Name(),
         m_symbol.NormalizePrice(sl),
         m_symbol.NormalizePrice(tp));
        }
      else
        {
         double sl = (ExtStopLoss==0.0)   ? 0.0 : price_bid + ExtStopLoss;
         double tp = (ExtTakeProfit==0.0) ? 0.0 : price_bid - ExtTakeProfit;
         m_trade.SellLimit(InpLots,m_symbol.NormalizePrice(price_bid),m_symbol.Name(),
         m_symbol.NormalizePrice(sl),
         m_symbol.NormalizePrice(tp));
        }
     }

   for(int i=0; i<InpDownQuantity; i++)
     {
      double price_ask = start_price_ask-i*ExtDownStep;
      double price_bid = start_price_bid-i*ExtDownStep;
      if(InpPending==limit)
        {
         double sl = (ExtStopLoss==0.0)   ? 0.0 : price_ask - ExtStopLoss;
         double tp = (ExtTakeProfit==0.0) ? 0.0 : price_ask + ExtTakeProfit;
         m_trade.BuyLimit(InpLots,m_symbol.NormalizePrice(price_ask),m_symbol.Name(),
         m_symbol.NormalizePrice(sl),
         m_symbol.NormalizePrice(tp));
        }
      else
        {
         double sl = (ExtStopLoss==0.0)   ? 0.0 : price_bid + ExtStopLoss;
         double tp = (ExtTakeProfit==0.0) ? 0.0 : price_bid - ExtTakeProfit;
         m_trade.SellStop(InpLots,m_symbol.NormalizePrice(price_bid),m_symbol.Name(),
         m_symbol.NormalizePrice(sl),
         m_symbol.NormalizePrice(tp));
        }
     }
  }


Questions have arisen:

1. The script is supposed to set either pending limit orders at a certain distance from ask and bid, or stop orders. The limitpending orders are set without any problems but the stop ones are not. Please help me find out why the pending Buy Stop and Sell Stop orders are not being set.

2. Is there any possibility to test the script when the market is closed (e.g. on weekends)?

Sincerely, Vladimir.
Reason: