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

 

Hmm... I hadn't thought about changing the coordinates. Thanks for the tip.

Then here's a question. There is an entry point condition. I implemented it through static variables, so that it doesn't reset to zero with every tick. Well, in some places of the chart the robot draws an entry point where there are no horizontal levels and, therefore, their intersection with MA. Please execute the code in your tester and you will see the problem. On EURUSD. Maybe this problem needs to be implemented in a different way? I'm not a pro at programming.

That is, the pattern has appeared, levels have been drawn and the robot waits for three crosses of one of the levels.

What do you think about it?

 
voron_026:

Hmm... I hadn't thought about changing the coordinates. Thanks for the tip.

Then here's a question. There is an entry point condition. I implemented it through static variables, so that it doesn't reset to zero with every tick. Well, in some places of the chart the robot draws an entry point where there are no horizontal levels and, therefore, their intersection with MA. Please execute the code in your tester and you will see the problem. On EURUSD. Maybe this problem needs to be implemented in a different way? I'm not a pro at programming.

That is, the pattern has appeared, levels have been drawn and the robot waits for three crosses of one of the levels.

What do you think about it?

Who needs it, if you don't mind my saying so? Look where the robot gets the values from and you will find another solution to the problem.

 

Help Two is giving out errors! I've highlighted the errors in red, help PLZ!



//+------------------------------------------------------------------+

//| Trailing Stop by Asyll.mq4 |

//| Copyright 2017, MetaQuotes Software Corp. |

//| https://www.mql5.com |

//+------------------------------------------------------------------+

#property copyright "Alibek Asyll"

#property link "https://www.mql4you.com"


extern int TralType = 0; // 0-Sar, 1-ATR, 2-HMA.

extern double SAR_Step = 0.02;

extern double SAR_Max = 0.2;

extern int ATR_Period = 14;

extern double ATR_K = 2.0;

extern inttern MMA_Period = 16;

extern int int MMA_Method = 3;

extern inttern MMA_Shift = 0;

datetime LBT;

//+------------------------------------------------------------------+

//| Expert initialisation function|

//+------------------------------------------------------------------+

int init()

{

//---

//---

return(0);

}

//+------------------------------------------------------------------+

//| Expert deinitialization function |

//+------------------------------------------------------------------+

int deinit()

{

//---

return(0);

}

//+------------------------------------------------------------------+

//| expert tick function |

//+------------------------------------------------------------------+

int start()


{

bool error = false;

if (LBT!=Time[0] {

if (OrdersTotal()>0) {

for (int i=o; i<OrdersTotal(); i++) {

if (OrderSelect(i,SELECT_BY_POS)&&OrderSymbol()==Symbol()&&OrderType()<2) {

double SL = OrderStopLoss();

if (OrderType()==0) {

switch (TralType) {

case 0: SL = iSAR(NULL,0,SAR_Step, SAR_Max,0);

break;

case 1: SL = High[1] - iATR(NULL,0,ATR_Period,1)*ATR_K;

break;

case 2: SL = iCustom(NULL,0, "VininI_HMA_sound&amp",HMA_Period, HMA_Method, 3, HMA_Shift,false,false,",1,0,0);

break;

}

if (SL<OrderStopLoss())

SL = OrderStopLoss();

}

if (OrderType()==1){

switch (TralType){

case 0: SL = iSAR(NUll,0,SAR_Step, SAR_Max,0);

break;

case 1: SL = Low[1] + iATR(NULL,0,ATR_Period,1)*ATR_K;

break;

case 2: SL = iCustom(NULL,0, "VininI_HMA_sound&amp",HMA_Period, HMA_Method, 2, HMA_Shift,false,false,",1,0,0);

break;

}

if (SL>OrderStopLoss())

SL = OrderStopLoss();

}

if (SL!=OrderStopLoss()) {

if (!OrderModify(OrderTicket(),OrderOpenPrice(),OrderTakeProfit(),0))

error = true;

}

}

if (!error)

LBT = Time[0];

}


return();

}

//+-------------------------------------------------------------------+

Автоматический трейдинг и тестирование торговых стратегий
Автоматический трейдинг и тестирование торговых стратегий
  • www.mql5.com
Выберите подходящую торговую стратегию и оформите подписку на нее в пару кликов. Все Сигналы сопровождаются подробной статистикой и графиками. Станьте Поставщиком торговых сигналов и продавайте подписку тысячам трейдеров по всему миру. Наш сервис позволит вам хорошо зарабатывать на прибыльной стратегии даже при небольшом стартовом капитале...
 
Asyll: Help two gives out errors! Highlighted errors in red, help PLZ!

It makes sense to use the SRC button to insert code. Report the text of the errors. Remove the text to speed up the expert:

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int init()

  {

//---

   

//---

   return(0);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

int deinit()

  {

//---

   return(0);

  }

It takes time to call these functions - and they are empty. And it would be easier to work with program text without them. Count the curly brackets. To make this easier, try the Styler in the Tools menu. Discard the empty lines.

Стилизатор - Работа с исходным кодом - Разработка программ - Справка по MetaEditor
Стилизатор - Работа с исходным кодом - Разработка программ - Справка по MetaEditor
  • www.metatrader5.com
Данная функция предназначена для оформления исходного кода в соответствии с рекомендуемым стандартом. Это позволяет сделать код более читаемым, выглядящем профессионально. Грамотно оформленный код гораздо проще анализировать в последующем как его автору, так и другим пользователям. Для того чтобы запустить стилизатор, необходимо выполнить...
 

Good day to all.

I have a simple idea that I am trying to code and test on an MT-4 tester

Open orders when the following conditions are present at the same time

1. At the opening of a one-minute candle

2 At the price I want

3. At the desired date

4.The price value must strictly coincide with the value of the day.

For example, the 27th day was a one-minute candlestick with the opening price 1.2414

I need to open an order 1) on the open candlestick 2) at 1.2414 3) but on the next day which follows after the 27th

For instance on the 28th we had a 1 minute candlestick open at 1.2438.

I have to open an order 1) on the open candlestick 2) at 1.2438 3) BUT ON THE NEXT DAY AFTER THE 28th

For instance on the 12th there was a 1 minute candlestick open at 1.2451

I need to open an order 1) on the open candlestick 2) at 1.2451 3) BUT ON THE NEXT DAY AFTER THE 12th


For realization of this idea I started to study a theme of arrays and created two one-dimensional arrays, but it does not work

I would be very grateful to you if you could fix my code to implement the above idea

I am a slowpoke, so I will be very grateful if you could write the right code, instead of explaining it in words.

This way I'll understand it much faster.

Here is my code.

double mass[3]=
{
1.2414,
1.2438,
1.2451
};
int mass1[3]=
{
27,
28,
12
};
double value = NormalizeDouble( Bid,4) ;
double S = ArrayBsearch(mass,  value,  WHOLE_ARRAY,  0, MODE_ASCEND);
int value1 = Day() ;
int S1 = ArrayBsearch(mass1,  value1, WHOLE_ARRAY,  0, MODE_ASCEND);

if(Bid  == iOpen(NULL,PERIOD_M1,0))
if(Day()!= S1)
if(NormalizeDouble ( Bid,4)== S)
{
OrderSend(Symbol(),OP_SELL,0.1,Bid ,3,Ask+400*Point,Ask-200*Point,"jfh",123 );
}
 

Hello! This code is intended to move the signal levels when the price moves beyond the upper or lower level, but it doesn't happen. Please tell me what the error is.

/-------------------------выход цены за пределы сигнальных уровней-----------------------------------------------------------------------------------------------
if(Bid>=priceA){                                                                                   //если цена вышла за верхнею границу, то переместить сердцевину в новое положение
 ObjectsDeleteAll();
 OR=0;                                                                                             //переменная ордера обнуляется для поиска ситуации открытия новых ордеров
 }                                                                                                 
if(Bid<=priceB){                                                                                   //если цена вышла за нижнею границу, то переместить сердцевину в новое положение
 ObjectsDeleteAll();
 OR=0;                                                                                             //переменная ордера обнуляется для поиска ситуации открытия новых ордеров
 } 
 //----------------------------------------------------------------------------------------------------------------------------------------------------------------
 price=iHigh(Symbol(),PERIOD_M15,0);                                                               //Сигнальный уровень О(Сердцевина)
ObjectCreate("UrO",OBJ_HLINE,0,0,price);
ObjectSet("UrO",OBJPROP_COLOR,clrYellowGreen);                               
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------
 priceA=price+30*Point;                                                                            //Сигнальный уровень А(Максимум)
ObjectCreate("UrA",OBJ_HLINE,0,0,priceA);
ObjectSet("UrA",OBJPROP_COLOR,clrDarkSlateBlue); 
//---------------------------------------------------------------------------------------------------------------------------------------------------------------- 
 priceB=price-30*Point;                                                                            //Сигнальный уровень B(Минимум)
ObjectCreate("UrB",OBJ_HLINE,0,0,priceB); 
ObjectSet("UrB",OBJPROP_COLOR,clrOrangeRed); 
 
ANDREY: For example, on the 27th there was a one-minute candle with the open price 1.2414

I need to open an order 1) at the opening of a candle 2) at 1.2414 3) BUT ON THE LAST DAY AFTER THE 27th

Here is my code.

First, it is hardly reasonable to normalize an already normalized BID, unless the instructor tells you to

Secondly, what do we get? On the 27th, the price appeared and you urgently enter the data into the array, to trigger it on the 28th? And what if on the 28th something urgent happens? You're putting data into an array that's hard to calculate. Your data should be computable. I suggest debugging your EA in steps. 1) Determine the required price and display it using the Alert() function. If you are sure that it is correct, calculate and display the next one... and so on to the end. It is too early to write the whole code beforehand as it will have to be modified as the debugging progresses. What do you think of this technology from simple to complex?

 
vikzip: The code was written to move the signal levels when the price goes above or below the upper or lower level, but this does not happen.

Let us have a look at what is written here. First, the lines should be shorter. They will fit better on the screen and the compiler will work faster.

/-------------------------выход цены за пределы сигнальных уровней-------------------------------------------------
if(Bid>=priceA){                  //если цена вышла за верхнею границу, то переместить сердцевину в новое положение
 ObjectsDeleteAll();
 OR=0;                            //переменная ордера обнуляется для поиска ситуации открытия новых ордеров
 }
if(Bid<=priceB){                  //если цена вышла за нижнею границу, то переместить сердцевину в новое положение
 ObjectsDeleteAll();
 OR=0;                            //переменная ордера обнуляется для поиска ситуации открытия новых ордеров
 } 
 //----------------------------------------------------------------------------------------------------------------
If the BID is bigger, you have to do something. Then if BID is less, the same thing must be done. You can phrase it shorter: If the price is more or less, then ...
You write something in the comments about moving something, but all you do is delete all the objects. Your 10 lines are replaced by four.
if((Bid>=priceA) ||(Bid<=priceB)){     //если цена вышла за одну из ГРАНИЦ, то удалить все объекты и очистить признак поиска
   ObjectsDeleteAll();
   OR=0;                               // А это для чего?????????????????
} 

But !!! The OR sign should be used somewhere else, shouldn't it? It seems that instead of zeroing this OR, we should create new objects here. Or even easier - instead of deleting objects, just move them to a new location - it's only 3 lines of code. Or does the instructor require more?

if((Bid>=priceA) ||(Bid<=priceB)){     //если цена вышла за одну из ГРАНИЦ, сдвинуть уровни
  ObjectSet("UrO",OBJPROP_PRICE1,iHigh(Symbol(),PERIOD_M15,0));   // Так что ли???
   Objectsset( аналогично)
   Objectsset(     )
}
From simple to false or vice versa?
 
STARIJ:

Firstly, normalising an already normalised BID is hardly advisable, unless the teacher tells you to

Secondly, what do we have here? On the 27th a price occurs and you urgently enter the data into the array, so that it works on the 28th? And what if there is an urgent situation on the 28th? You're putting data into an array that's hard to calculate. Your data should be computable. I suggest debugging your EA in steps. 1) Determine the required price and display it using the Alert() function. If you are sure that it is correct, calculate and display the next one... and so on to the end. It is too early to write the whole code beforehand as it will have to be modified as the debugging progresses. What do you think of this technology from simple to complex?

Thank you very much for the hint.

But it seems to me that in your reasoning you are assuming that I am trying to write a TRUE EA.

I'm sorry I didn't tell you that's not the case.

I try to test the presence of some regularity, correlation between the above parameters, that is, to confirm or reject the idea, which may be the basis for a TORKING Expert Advisor.

Therefore I will be grateful to you if you correct my code, so that everything would be in accordance with my above idea.

And your comments will of course be useful to me when I am writing a trading Expert Advisor.

Thank you

 
ANDREY:

Thank you very much for the tip.

But the way I see it is that in your reasoning you are assuming that I am trying to write a TRUE EA.

I'm sorry I didn't tell you that's not the case.

I try to test the presence of some regularity, correlation between the above parameters, that is, to confirm or reject the idea, which may be the basis for a TORKING Expert Advisor.

Therefore I will be grateful to you if you correct my code, so that everything would be in accordance with my above idea.

Your comments will of course be useful to me when I am writing a trading Expert Advisor.

Thank you

Sorry for the intrusion. But... In what way should the logic of drawing lines be different for a trading and non-trading EA?

When you're at work, do you look at the watch on your hand differently compared to how you look at it at home?

Reason: