[Archive!] Any rookie question, so as not to clutter up the forum. Professionals, don't pass it by. Couldn't go anywhere without you - 2. - page 497

 
Please advise how to open an order on a new bar only once ????
 

embed code in the EA, I had something like this until I deleted it, I was using hourly timeframe

orderselect - select the last order in the history

take the time of its closing and pull out the closing hour

and before opening the order, set a condition that the current hour is NOT equal to the time of order closing from the history

 

Please help me with this problem, my TP variable is zeroed after the second price update, i.e., the advisor opens an order, and TP and Bid are both not equal to zero, then the price is updated again and TP is zero, although there is no such command in the code, I had a problem with pulling SL up, but now it turns out that the problem is in the definition of TP

int start()
{
//----
double TP;
double SL;
if (OrdersTotal()==0)
{
OrderSend(Symbol(),OP_BUY,0.01,Ask,3,0,Bid+4*Point);
OrderSelect(OrdersTotal()-1,SELECT_BY_POS);
TP=OrderTakeProfit();
}
Alert ("TP=" + TP);
Alert ("Bid=" + Bid);
if (OrdersTotal()>0)
{
if (TP-Bid<3*Point)
{
Alert ("Approaching TP by 1 or 2");
Alert ("TP=" + TP);
Alert ("Bid=" + Bid);
}
}
//----
return(0);
}

 
LazarevDenis:

Please help me with this problem, my TP variable is zeroed after the second price update, i.e., the EA opens an order and displays values of TP and Bid, both are not equal to zero, then the price is updated again and TP is zero, although in the code, no such commands, I had a problem with pulling SL up, but now it turns out that the problem is in the definition of TP

double TP, SL;


int start()
{
//----

if (OrdersTotal()==0)
{
OrderSend(Symbol(),OP_BUY,0.01,Ask,3,0,Bid+4*Point);
OrderSelect(OrdersTotal()-1,SELECT_BY_POS);
TP=OrderTakeProfit();
}
Alert ("TP=" + TP);
Alert ("Bid=" + Bid);
if (OrdersTotal()>0)
{
if (TP-Bid<3*Point)
{
Alert ("Приблизился к ТП на 1 или 2");
Alert ("TP=" + TP);
Alert ("Bid=" + Bid);
}
}
//----
return(0);
}
Try it this way...
 
VOLDEMAR:
Please advise how to open an order on a new bar only once ????

Read here: https://www.mql5.com/ru/forum/134437
 
Cmu4, thank you very much, you've been very helpful
 

Hello all!

There are two signals in the strategy: a primary and a secondary one. A trade is opened when the second signal appears no later than 12 hours later. Question: How can I teach my Expert Advisor not to react to the signal, if it appears after 12 hours? Please, if you can give a concrete code example

 
demlin:

Hello all!

There are two signals in the strategy: a primary and a secondary one. A trade opens when the second signal appears no later than 12 hours later. Question: How can I teach my Expert Advisor not to react to the signal, if it appears after 12 hours? Please, if you can give me an example of the code


Hi Dmitry. For my part I am ready to offer you the following variant. For analogy, see the triggering of the trading criteria of this article - there are also two signals - namely - see after the second figure "The first thing to wait for on the DeMarker chart is the moment when the DeMarker crosses the fast and slow MA lines around 0.7 for a short position. This is the first preliminary signal. Then we wait for the crossing of the MA lines themselves. This is the main signal, after which the Taichi indicator readings can be taken. If the MA lines are not crossed, it is considered a false signal and the price movement will continue. Here is how it is implemented in my code - in the included inclusion of owls that are responsible for triggering of trade criteria.

The main trick is to work through the two below (at the end of) the inclusion by setting and resetting flags when one or the other trade criterion is triggered.

//--------------------------------------------------------------------
// Criterion.mqh
// 
//--------------------------------------------------------------- 1 --
// Функция вычисления торговых критериев.
// Возвращаемые значения:
// 10 - открытие Buy  
// 20 - открытие Sell 
// 0  - значимых критериев нет
// 
//--------------------------------------------------------------- 2 --
// Внешние переменные:
extern string A5 = "Параметры";
//extern int       Period_K = 5;            // Период K
//extern int       Period_D = 3;            // Период D
//extern int       Slowing = 3;             // Замедление

extern int Tenkan=9;
extern int Kijun=26;
extern int Senkou=52;
extern int FlatSE=7;

extern int DeMarker=25;
extern int FastMA=14;
extern int SlowMA=25;
extern double DeMarker_OpenLevel_Sell = 0.7;
extern double DeMarker_OpenLevel_Buy = 0.7;
 bool   DeMarker_Buy_signal=false, DeMarker_Sell_signal=false,
       MA_Buy_signal=false, MA_Sell_signal=false;



extern int t_trend_period =6; // для оптимизации по всем периодам от 0 до 7 шаг 1
                              // на каком ТФ работаем: 1-М1, 2-М5, 3-М15, 4-М30, 5-Н1, 6 - Н4, 7-день
 

//--------------------------------------------------------------- 3 --
int Criterion()                        // Пользовательская функция
  {
  //--------------------------------------------------------------- 4 --
 int trend_period=GetPeriod(t_trend_period); // для выбора оптимального значения рабочего ТФ

   // Параметры технич. индикат:
                 
double Taichi_1 = iCustom (Symbol(), trend_period, "Cronex Taichi",Tenkan, Kijun, Senkou, FlatSE, 0, 1);
double TaichiFor_1 = iCustom (Symbol(), trend_period, "Cronex Taichi", Tenkan, Kijun, Senkou, FlatSE, 3, 1);
double Signal_1 = iCustom (Symbol(), trend_period, "Cronex Taichi", Tenkan, Kijun, Senkou, FlatSE, 1, 1);
double SSignal_1 = iCustom (Symbol(), trend_period, "Cronex Taichi", Tenkan, Kijun, Senkou, FlatSE, 2, 1);

double FlatBuffer1 = iCustom (Symbol(), trend_period, "Cronex Taichi", Tenkan, Kijun, Senkou, FlatSE, 4, 1);
double FlatBuffer2 = iCustom (Symbol(), trend_period, "Cronex Taichi", Tenkan, Kijun, Senkou, FlatSE, 5, 1);

double DeMarker_1 = iCustom (Symbol(), trend_period, "Cronex DeMarker",DeMarker, FastMA, SlowMA, 0, 1);
double DeMarker_2 = iCustom (Symbol(), trend_period, "Cronex DeMarker",DeMarker, FastMA, SlowMA, 0, 2);

double FastMA_1 = iCustom (Symbol(), trend_period, "Cronex DeMarker", DeMarker, FastMA, SlowMA, 1, 1);
double FastMA_2 = iCustom (Symbol(), trend_period, "Cronex DeMarker", DeMarker, FastMA, SlowMA, 1, 2);

double SlowMA_1 = iCustom (Symbol(), trend_period, "Cronex DeMarker", DeMarker, FastMA, SlowMA, 2, 1);
double SlowMA_2 = iCustom (Symbol(), trend_period, "Cronex DeMarker", DeMarker, FastMA, SlowMA, 2, 2);

//--------------------------------------------------------------- 5 --
   // Вычисление торговых критериев
   
   if(( (type_op_DeMarker(DeMarker_1,DeMarker_2,FastMA_1, FastMA_2, SlowMA_1, SlowMA_1)==OP_BUY) || (DeMarker_Buy_signal == true && DeMarker_Sell_signal==false)) &&  // когда DeMarker пересекает медленую (выше уровня бай (0.7)) для лонг
      ( (type_op_MA (DeMarker_1,DeMarker_2,FastMA_1, FastMA_2, SlowMA_1, SlowMA_1)==OP_BUY) || (MA_Buy_signal==true && MA_Sell_signal==false)) && // пересечение МА DeMarkers
   
   
      (iClose(Symbol(), trend_period,1) > Taichi_1 && Taichi_1 > TaichiFor_1 && Signal_1 > SSignal_1 && FlatBuffer1==0 && FlatBuffer2==0))
     
         {
           Print ("Taichi_1 = ", Taichi_1, "TaichiFor_1 = ",TaichiFor_1, "Signal_1 = ", Signal_1, "SSignal_1 = ",SSignal_1, "FlatBuffer1 = ", FlatBuffer1, "FlatBuffer2 = ", FlatBuffer2);
           Print ("DeMarker_1 = ", DeMarker_1, "DeMarker_2 = ",DeMarker_2, "FastMA_1 = ", FastMA_1, "FastMA_2 = ",FastMA_2, "SlowMA_1 = ", SlowMA_1, "SlowMA_2 = ", SlowMA_2);
           return(10);                      // Открытие Buy    
         }
        
   if(( (type_op_DeMarker(DeMarker_1,DeMarker_2,FastMA_1, FastMA_2, SlowMA_1, SlowMA_1)==OP_SELL) || (DeMarker_Buy_signal==false && DeMarker_Sell_signal==true)) &&  // когда DeMarker пересекает медленую (ниже уровня селл) для шорт
      ( (type_op_MA (DeMarker_1,DeMarker_2,FastMA_1, FastMA_2, SlowMA_1, SlowMA_1)==OP_SELL) || (MA_Buy_signal==false && MA_Sell_signal==true)) && // пересечение МА DeMarkers
        
      (iClose(Symbol(), trend_period,1) < Taichi_1 && Taichi_1 < TaichiFor_1 && Signal_1 < SSignal_1 && FlatBuffer1==0 && FlatBuffer2==0))
        {
           Print ("Taichi_1 = ", Taichi_1, "TaichiFor_1 = ",TaichiFor_1, "Signal_1 = ", Signal_1, "SSignal_1 = ",SSignal_1, "FlatBuffer1 = ", FlatBuffer1, "FlatBuffer2 = ", FlatBuffer2);
           Print ("DeMarker_1 = ", DeMarker_1, "DeMarker_2 = ",DeMarker_2, "FastMA_1 = ", FastMA_1, "FastMA_2 = ",FastMA_2, "SlowMA_1 = ", SlowMA_1, "SlowMA_2 = ", SlowMA_2);
           return(20);  
        }                       // Открытие Sell 
  
//--------------------------------------------------------------- 6 --
   return(0);                          // Выход из пользов. функции
  }
//--------------------------------------------------------------- 7 --

//для оптимизации по всем ТФ
int GetPeriod(int period)
{int periodres;
 switch(period)
  {
   case 1: periodres=1;break;
   case 2: periodres=5;break;
   case 3: periodres=15;break;
   case 4: periodres=30;break;
   case 5: periodres=60;break;
   case 6: periodres=240;break;
   case 7: periodres=1440;break;
   case 8: periodres=10080;break;
   default: periodres=1;break;
  }
return(periodres);
} 


int type_op_DeMarker(double D1, double D2, double F1, double F2, double S1,double S2)// Функция - условия для входа в рынок и сохранения их через переменные Buy_signal и Sell_signal (даже после их сработки - до отмены
               // противоположными сигналами)
               
{
      
     if (D2-S2 < 0 && D1-S1 > 0 && D1 > F1  && D1 < DeMarker_OpenLevel_Buy)
          {
             DeMarker_Buy_signal=true;
             DeMarker_Sell_signal=false;
             return(OP_BUY);
          } 
  
      if (D2-S2 > 0 && D1-S1 < 0 && D1 < F1 && D1 > DeMarker_OpenLevel_Sell)                                                                                   
          {
             DeMarker_Buy_signal=false;
             DeMarker_Sell_signal=true;
             return(OP_SELL);
          }   
   else return(-1);
     
}

int type_op_MA(double d1, double d2, double f1, double f2, double s1,double s2) // условия для входа в рынок и сохранения их через переменные Buy_signal и Sell_signal (даже после их сработки - до отмены
               // противоположными сигналами)
               

  {
          
     if (f2 - s2 < 0 && f1 - s1 > 0)
          {
             MA_Buy_signal=true;
             MA_Sell_signal=false;
             return(OP_BUY);
          } 
  
      if (f2-s2 > 0 && f1-s1 < 0)                                                                                                               
          {
             MA_Buy_signal=false;
             MA_Sell_signal=true;
             return(OP_SELL);
          }   
   else return(-1);

  }

You will additionally save the current time when the main criterion is triggered using TimeCurrent, i.e. you will specify an expression of type x = TimeCurrent beforereturn(OP_BUY); orreturn(OP_SELL); where x is a global variable of datetime type by analogy in the firstint_op_DeMarker function. Then do the same with the secondint type_op_MA function... - there you memorize variable y = TimeCurrent;

Then in the block of trade criteria calculation you compare the value of these two variables with the plus sign (it turns out that you don't need the analogue of working with UTC values - instead you take a comparison of time of receipt of your two trade signals):

 // Вычисление торговых критериев
   
   if(( (type_op_DeMarker(DeMarker_1,DeMarker_2,FastMA_1, FastMA_2, SlowMA_1, SlowMA_1)==OP_BUY) || (DeMarker_Buy_signal == true && DeMarker_Sell_signal==false)) &&  // когда DeMarker пересекает медленую (выше уровня бай (0.7)) для лонг
      ( (type_op_MA (DeMarker_1,DeMarker_2,FastMA_1, FastMA_2, SlowMA_1, SlowMA_1)==OP_BUY) || (MA_Buy_signal==true && MA_Sell_signal==false)) && // пересечение МА DeMarkers
   
   
      ((x+43200) < y )) //43200 - это количество секунд в 12-ти часах
     
         {
           Print ("Время сработки первого условия х(в секундах) = ", х, " Время сработки второго условия y (в секундах) = ", y);
           Print ("DeMarker_1 = ", DeMarker_1, "DeMarker_2 = ",DeMarker_2, "FastMA_1 = ", FastMA_1, "FastMA_2 = ",FastMA_2, "SlowMA_1 = ", SlowMA_1, "SlowMA_2 = ", SlowMA_2);
           return(10);                      // Открытие Buy    
         }

P.S. Plus I am sending you a function for the possibility to optimize the value of the working TF.

P.P.S. This is how this code structure is organized in my code. I do not exclude that there are much better code variants for fulfilling such conditions of the EA. :-)))

 

How do I calculate a profit on one currency pair in my EA?

For example, I have seven buy orders open on euros at different prices. How do I calculate a profit on euros without affecting other orders on other pairs? ????

 

use SelectOrder to scan all open orders

check the required pair (OrderSymbol)

then add the profit to any variable if it is the required OrderProfit

here is a link with useful functions https://docs.mql4.com/ru/trading/OrderSelect

on the left side there is a menu with operations, all of them are described there