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

 
Shockeir #:
Hello Colleagues, could you please advise a newbie how to get the current value (at the moment) of an indicator and not the value from the previous bar? The EA only triggers when the previous bar finishes, and I need it earlier.

Perhaps a more detailed description of the situation and what is not working for you would be more helpful.

 
Andrey Sokolov #:

Perhaps a more detailed description of the situation and what you yourself are unable to do will yield more results.

The indicator is a standard Stochastic. The Expert Advisor should trigger at the intersection of K and D lines. At the very crossing until a new bar appears, nothing happens. When a new bar appears, if the condition is still fulfilled, then action occurs. As far as I understand, it is because the last value in the indicator buffers is the value calculated at the last completed bar. So, I would like the triggering to take place on an unfinished bar.

 
Shockeir #:

The indicator is a standard Stochastic. The Expert Advisor should be triggered at the intersection of K and D lines. At the very crossing, until a new bar appears, nothing happens. As soon as a new bar appears, if the condition is still fulfilled, then action occurs. As far as I understand, it happens because the last value in the indicator buffers is the value calculated at the last completed bar. So, I would like the action to be triggered on an unfinished bar.

The last candle has an index of 0.

So, how have you tried to solve this problem? Have you read the help? What exactly is not working?

 
Andrey Sokolov #:

Can you put in the code? At least make it clear what language you're using.

//+------------------------------------------------------------------+
//|                                                      ProjectName |
//|                                      Copyright 2020, CompanyName |
//|                                       http://www.companyname.net |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"

//--- input parameters
input double   crossDepthOpen=7;    //Глубина пересечения K и D для открытия
input double   crossDepthClose=-2;  //Глубина пересечения K и D для закрытия
input double   closeCoef=5;         //Коэффициент изменения глубины закрытия
input int      k_period=8;          //Период K
input int      d_period=3;          //Период В
input int      slowing=3;           //Сглаживание
input double   tp_1=20;             //Тейк
input double   sl_1=60;             //Лосс
input double   maxPos=2.0;          //Размер лота

int      stoch_handle;
double   k_buffer[1];
double   d_buffer[1];
double   TKP;
double   STL;
double   CDO;
double   CDC;
int      lossCount=0;
int      profitCount=0;
int      EA_magic=12345;


//| Expert initialization function

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int OnInit()
  {
   TKP=tp_1;
   STL=sl_1;

   stoch_handle=iStochastic(_Symbol,PERIOD_CURRENT,k_period,d_period,slowing,MODE_EMA,STO_LOWHIGH);
   if(stoch_handle<0)
     {
      Alert("Ошибка при создании индикаторов ",GetLastError());
      return(0);
     }
   return(INIT_SUCCEEDED);
  }

//| Expert tick function

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
  {
   CDO=crossDepthOpen;
   CDC=crossDepthClose;
   MqlTick latestPrice;
   MqlTradeResult mResult;
   MqlTradeRequest mRequest;
   ZeroMemory(mRequest);
   SymbolInfoTick(_Symbol,latestPrice);
   ArraySetAsSeries(k_buffer,true);
   ArraySetAsSeries(d_buffer,true);
   if(CopyBuffer(stoch_handle,0,0,1,k_buffer)<0)
     {
      Alert("Не удалось скопировать в буфер K",GetLastError());
      return;
     }
   if(CopyBuffer(stoch_handle,1,0,1,d_buffer)<0)
     {
      Alert("Не удалось скопировать в буфер D",GetLastError());
      return;
     }

   bool buyFullOpened=false;
   bool buyPartOpened=false;
   bool sellFullOpened=false;
   bool sellPartOpened=false;

//Состояние позиций
   if(PositionSelect(_Symbol)==true)
     {
      if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
        {
         if(PositionGetDouble(POSITION_VOLUME)>=maxPos)
           {
            buyFullOpened=true;
           }
         else
           {
            buyPartOpened=true;
           }
        }
      else
         if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
           {

            if(PositionGetDouble(POSITION_VOLUME)>=maxPos)
              {
               sellFullOpened=true;
              }
            else
              {
               sellPartOpened=true;
              }
           }
     }
//состояние позиций конец

//Условия изменения позиций
   bool buyOpenCondition=k_buffer[0]>((d_buffer[0])+CDO);
   bool buyCloseCondition=k_buffer[0]<((d_buffer[0])-CDC);
   bool buyTPCondition=latestPrice.bid>(PositionGetDouble(POSITION_PRICE_OPEN)+TKP*_Point);
   bool buySLCondition=latestPrice.bid<(PositionGetDouble(POSITION_PRICE_OPEN)-STL*_Point);
   bool sellOpenCondition=k_buffer[0]<((d_buffer[0])-CDO);
   bool sellCloseCondition=k_buffer[0]>((d_buffer[0])+CDC);
   bool sellTPCondition=latestPrice.ask<(PositionGetDouble(POSITION_PRICE_OPEN)-TKP*_Point);
   bool sellSLCondition=latestPrice.ask>(PositionGetDouble(POSITION_PRICE_OPEN)+STL*_Point);
//Условия изменения позиций конец

//Проверка и выполнение действий
   if(buyOpenCondition)
     {
      if(!buyFullOpened && !buyPartOpened && !sellPartOpened && !sellFullOpened)
        {
         Print("Покупка по сигналу");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.ask,_Digits);
         mRequest.sl = 0; //NormalizeDouble(latestPrice.ask - STL*Point(),_Digits);
         mRequest.tp = 0; //NormalizeDouble(latestPrice.ask + TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_BUY;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = maxPos;
         OrderSend(mRequest,mResult);
         Print("Открыто ",PositionGetDouble(POSITION_VOLUME)," по ", PositionGetDouble(POSITION_PRICE_OPEN));
        }
     }
//Условия покупки
   if(sellTPCondition)
     {
      if(sellFullOpened)
        {
         Print("Тейк-профит шорта");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.ask,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.ask - STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.ask + TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_BUY;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = MathRound(PositionGetDouble(POSITION_VOLUME)/2);
         OrderSend(mRequest,mResult);
         ++profitCount;
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }

   if(sellSLCondition)
     {
      if(sellFullOpened || sellPartOpened)
        {
         Print("Стоп-лосс шорта");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.ask,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.ask - STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.ask + TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_BUY;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = PositionGetDouble(POSITION_VOLUME);
         OrderSend(mRequest,mResult);
         ++lossCount;
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }

   if(sellCloseCondition)
     {
      if(sellFullOpened || sellPartOpened)
        {
         Print("Закрытие шорта по сигналу");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         Print(k_buffer[0]," ",d_buffer[0]);
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.ask,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.ask - STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.ask + TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_BUY;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = PositionGetDouble(POSITION_VOLUME);
         OrderSend(mRequest,mResult);
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }

//Условия продажи
   if(sellOpenCondition)
     {
      if(!sellFullOpened && !buyPartOpened && !sellPartOpened && !buyFullOpened)
        {
         Print("Продажа по сигналу");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         Print(k_buffer[0]," ",d_buffer[0]);
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.bid,_Digits);
         mRequest.sl = 0; //NormalizeDouble(latestPrice.bid + STL*_Point,_Digits);
         mRequest.tp = 0; //NormalizeDouble(latestPrice.bid - TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_SELL;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = maxPos;
         OrderSend(mRequest,mResult);
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }
   if(buyTPCondition)
     {
      if(buyFullOpened)
        {
         Print("Тейк-профит лонга");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.bid,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.bid + STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.bid - TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_SELL;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = MathRound(PositionGetDouble(POSITION_VOLUME)/2);
         OrderSend(mRequest,mResult);
         ++profitCount;
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }

   if(buySLCondition)
     {
      if(buyFullOpened || buyPartOpened)
        {
         Print("Стоп-лосс лонга");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         Print(k_buffer[0]," ",d_buffer[0]);
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.bid,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.bid + STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.bid - TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_SELL;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = PositionGetDouble(POSITION_VOLUME);
         OrderSend(mRequest,mResult);
         ++lossCount;
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }

   if(buyCloseCondition)
     {
      if(buyFullOpened || buyPartOpened)
        {
         Print("Закрытие лонга по сигналу");
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
         Print("Цена открытия ", PositionGetDouble(POSITION_PRICE_OPEN));
         Print(k_buffer[0]," ",d_buffer[0]);
         mRequest.action = TRADE_ACTION_DEAL;
         mRequest.symbol = _Symbol;
         mRequest.price = NormalizeDouble(latestPrice.bid,_Digits);
         mRequest.sl = 0;//NormalizeDouble(latestPrice.bid + STL*_Point,_Digits);
         mRequest.tp = 0;//NormalizeDouble(latestPrice.bid - TKP*_Point,_Digits);
         mRequest.magic = EA_magic;
         mRequest.type = ORDER_TYPE_SELL;
         mRequest.type_filling = ORDER_FILLING_FOK;
         mRequest.deviation=100;
         mRequest.volume = PositionGetDouble(POSITION_VOLUME);
         OrderSend(mRequest,mResult);
         Print("Текущий объем позиций ",PositionGetDouble(POSITION_VOLUME));
        }
     }
  }
//+------------------------------------------------------------------+
//| Trade function                                                   |
//+------------------------------------------------------------------+
void OnTrade()
  {
//---

  }
//+------------------------------------------------------------------+


//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   IndicatorRelease(stoch_handle);
   Print("loss ",lossCount);
   Print("profit ",profitCount);
  }
//+------------------------------------------------------------------+
Andrey Sokolov #:

Can you put in the code? At least make it clear in what language you're doing it in.

 

Forum on trading, automated trading systems & strategy testing

Any questions from newbies on MQL4 and MQL5, help and discussion on algorithms and codes

GlaVredFX, 2022.01.17 22:52

ClosePosWithMaxProfitInCurrency

You cannot use this function anymore. It does not fit. If this function exists, it should be replaced by the function which closes one order opened first.

I do not understand the variables buySignal andsellSignal prescribed at the global level. But when I try to compile it, it gives me the following error

'sellSignal' - some operator expected   

expression has no effect        

'buySignal' - some operator expected    

expression has no effect        



How have you registered them and where does the compiler interfere? I can not guess. You need the source code to understand it.
 
Shockeir #:
Hello Colleagues, can you please advise a newbie how to get the current value (at the moment) of the indicator, not the value from the previous bar? The EA only triggers when the previous bar finishes, and I need it earlier.

The arrays k_buffer[0] and d_buffer[0] contain the latest indicator values. What is the problem with outputting them and seeing them yourself?

 
Andrey Sokolov #:

The arrays k_buffer[0] and d_buffer[0] contain the latest indicator values. What's the problem with outputting them and seeing them yourself?

Yes, indeed, apparently my mistake is elsewhere. Thank you!

 
Andrey Sokolov #:

What exactly is not working out in the code abbreviation?

I've already written. If certain conditions are met, several orders will be closed. They are placed on different currency pairs and in different directions. Here is a piece of code.

 if ( NormalizeDouble((MaxOpenSell(2) + MaxOpenBuy(2) + MinOpenSell(2))*Point,Digits) >= Profit1 && FindLastSell() >= Block 
         && FindLastBuy() >= 1 && MaxOpenSell(2) > 0 && MA1 < MA2)
      {
         LockTicket = 0;
         CalProfHis = 0;
         bool close =  OrderClose((int)MaxOpenSell(5),MaxOpenSell(3), Ask, Slippage, clrPink);
              close =  OrderClose((int)MinOpenSell(5),MinOpenSell(3), Ask, Slippage, clrPink);
              close =  OrderClose((int)MaxOpenBuy(5),MaxOpenBuy(3), Bid, Slippage, clrBlue);
      }

I close three orders in it.

However, my brokerage company sometimes misses them, I suppose because of many signals at a time. So, I can check each order and repeat it if I fail.
The question is how to do it correctly and competently, and not to write a huge code. I am sure there is a short way, that is why I am asking you, my senior programmers.

 
makssub #:

So I can write a check for each order, and repeat it if it fails.
The question is: how to do it correctly and competently, and not to write huge code. I'm sure there is a short way, so I'm asking you, our senior programmers.

The option I suggested does not suit you?

This is the forum for trading, automated trading systems and strategy testing.

Any questions from newbies on MQL4 and MQL5, or any tips and discussion on algorithms and codes

Mihail Matkovskij, 2022.01.17 10:35

If exit/close condition occurs, add the ticks to the array. Then, if the array is not empty, loop through it, calling OrderClose for each ticket. Then check existence of each ticket, and remove it from the list (array). Repeat these actions at 1-3 second intervals until the list is empty.


 
Polycysticism is everything