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

 
Kot:

Good afternoon!


I have an EA that does certain calculations. It uses different math operations, arrays, loops. It saves the result to a file. It has to start everything from the beginning after it has performed all the actions. It has done all the calculations once and then hangs for the second time without taking any action. Can you advise whether it is necessary to zero variables, clear arrays or something else before starting a new calculation?

Have you tried closing the file?

 
Good afternoon! I need help for a humanitarian (me) who is trying to make an indicator with the faintest knowledge of how to do it))) but have an understanding of what should appear)) So:
How to program a crutch/indicator/script (as an indicator with tabs "about program, General, Input parameters, Colors, Display") for MT4 so that it would take the data from a .csv file, for example the format ofthe source file:
EUR;TF;1.192;1.1733
EUR;TN;1.2037;1.1663
EUR;AB1;1.1906499615;1.1797479615
CHF;TF;1.0362;1.0183
CHF;TN;1.0479;1.0121
CHF;AB1;1.03484132734247;1.02549513556164


I.e.
the indicator took the recorded data from a file and put itas a line segment (TF, TA) or a colored band(EA) with the parameters of the extent equal to "one day". (from the border to the border of the vertical separators of days on МТ4), for lines selection of the line colour, line type, selection of the text colour and comment size and substitution of the comment line as "TF - 1,192" the second line "TF - 1,1733" which are taken from the corresponding lines of the file. The range is purely horizontal and from the line EUR;TF;1.192;1,1733 it takes the first digit for one slot and the second digit for the second one as the start of slot 1.192 and the end of slot 1.192.
There are also ranges, for example EA, the principle is the same from the beginning to the end of the day but the price is different and the line begins and ends with CHF;AB1;1.03484132734247;1.02549513556164 beginning is
1.03484132734247 end of the range1.02549513556164. Runs when you turn on MT4 (as a normal indicator on the gafik), every day on the chart and adds all the data exactly for the current day once, all the lines applied earlier is not removed from the chart and does not duplicate. With all this it selects and displays all of the segments and ranges for the day, only where the active window is now and in other active windows (i.e., where it is running) (i.e., it opened a pair and the indicator drew all of the segments and ranges of the current day and calmed down and so on for the pairs).

For example, how should look the tab of indicatorInput parameters:

Переменная________Значение
Funtik________//--Общие настройки--//
Draw TF________true
Draw TN _______true
Draw AB1______true
Draw AB2______false
Text caption colour _______Black
Шрифт подписей__________________Arial
Font size for text captions ________9
TF line colour ______________
Line type TF _______________
TN Line colour ______________
Line type TN _______________
Band colour AB1__________
Band colour AB2__________
File frequency in seconds ______2
File name ___________5.csv

tried to scribble myself, but do not get a damn thing although seemed easy (but I am a humanitarian, what can you do....) Help please drowning !!!!!!!!


//+------------------------------------------------------------------+
//|                                                        Funtik.mq4 |
//|                      Copyright © 2008, MetaQuotes Software Corp. |
//|                                        http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2008, MetaQuotes Software Corp."
#property link      "http://www.metaquotes.net"
 
#property indicator_chart_window
//---- input parameters
extern string    Funtik="5.csv";
//+------------------------------------------------------------------+
//| extern variables                                       |
//+------------------------------------------------------------------+
extern  bool    РисоватьTB = false      ;
extern  bool    РисоватьTN = false      ;
extern  bool    РисоватьTF = false      ;
extern  bool    РисоватьAB1 = false     ;
extern  bool    РисоватьAB2 = false     ;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
  {
//---- indicators
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function                       |
//+------------------------------------------------------------------+
int deinit()
  {
//----
 
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
  {
   int    counted_bars=IndicatorCounted();
//----
      int handle,sst=1;
     double  NameCena;
     string NameF ,NameTi,NameFT;
      bool h1;
      
   while(sst>0)
                 {
   handle=FileOpen(Funtik,FILE_CSV|FILE_READ,';');
 //  Comment ("Файл ",Funtik,"открыт");
   if(handle>=0)
    {
     NameF=FileReadString(handle);           // Читается наименование бумаги
     NameTi=FileReadString(handle);          // Читается первая котировка и подставляется в начало первого отрезка линии или диапазона
     NameCena=FileReadNumber(handle);        // Читается цена последней котировки для первого отрезка линии или диапазона
     NameFT=FileReadString(handle);          // Читается последняя котировка для диапазона
     
     Alert(NameF," ",NameTi," ",NameCena," ",NameFT);
       if(FileIsEnding(h1))
       {
     FileClose(h1);
     return(false);
     sst=0;
       }
    }
               }
     FileClose(handle);   
 
  //fComment(Funtik);
//----
   return(0);
  }
//+------------------------------------------------------------------+

 

Hello!

Please help me find a bug in the following program!!!

//+------------------------------------------------------------------+
//|test.mq4 |
//| Copyright 2018, MetaQuotes Software Corp.
//|https://www.mql5.com ||
//+------------------------------------------------------------------+
#property copyright "365_MA"
#property link "https://www.mql5.com"
#property version "1.00"
#property strict

extern Period_MA = 365; //Period MA 1
extern double Delta = 0.0010; //The distance at which the order can be opened

string Symb; //Name of the trade instrument
//int Total; //number of orders

//+------------------------------------------------------------------+
//| expert initialization function|
//+------------------------------------------------------------------+
int init()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function|
//+------------------------------------------------------------------+
int deinit()
{
//----
ObjectDelete("Obj_Label");
ObjectDelete("Obj_Label2");
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function|
//+------------------------------------------------------------------+
int start()
{



double prise = Bid;//current price
double CurrMAValue = iMA(Symb, Period(),Period_MA, 0,Mode_EMA, PRICE_CLOSE, 0); //the value of Moving Average
double Price2MA = price - CurrMAValue;//distance between MA and price
datetime NextClose = Time(0) + Period()*60*2;//time to close
int MinutesToNextClose = (NextClose - TimeCurrent())/60 + 1; //time to close in minutes

//int err;



//refresh text information on the chart

ObjectSetText ("Obj_Label", "TF" + Period() + ", " + DoubleToStr(price, 4) + ", tick " + TimeToStr(TimeCurrent(), TIME_SECONDS) + ", O@" + TimeToStr(Time[0], TIME_MINUTES) + ", NC@" + TimeToStr(NextClose, TIME_MINUTES) + " (" + MinutesToNextClose + " min)", 10,
ObjectSetText ("Obj_Label2", "Delta " + DoubleToStr(Delta,4) + ", MA value " + DoubleToStr(CurrMAValue, 4) + ", distance to MA " + DoubleToStr(Price2MA, 4), 10, "Arial", DarkGreen );
//consider price and generate alerts

if ((MathAbs(Price2MA) < Delta) && // if the distance to МА is less than delta
(Price > CurrMAValue) && // and the price is higher than MA
(Open(0) > CurrMAValue+Delta) // and the current candle opened higher than MA+Delta
(
Alert ("Price is approaching to the MA from above;)
)

if ((MathAbs(Price2MA) < Delta) && // if the distance to the MA is less than the delta
(price < CurrMAValue) && // and the price is below the MA
(Open(0) < CurrMAValue-Delta)) // and the current candle opened below the MA delta
(

Alert ("Price approached below the MA;)
)

return(0);


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

After compiling the following error

Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
Открой новые возможности в MetaTrader 5 с сообществом и сервисами MQL5
  • www.mql5.com
Задавайте вопросы по техническому анализу, обсуждайте торговые системы и улучшайте свои навыки программирования торговых стратегий на языке MQL5. Общайтесь и обменивайтесь опытом на форуме с трейдерами всего мира и помогайте ответами новичкам — наше сообщество развивается вместе с вами. Куда исчезли "Сообщения"? У меня в профиле исчез раздел...
Files:
Error.jpg  60 kb
 
berkley75:

Hello!

Please help me find a bug in the following program!!!


After compiling the following error.

//+------------------------------------------------------------------+
//|                                                         test.mq4 |
//|                        Copyright 2018, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "365_MA"
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict

extern int    Period_MA = 365;  //Период МА 1
extern double Delta = 0.0010;   //На каком расстоянии открывать ордер

string Symb;                  //Название торгового инструмента
//int Total;                  //количество ордеров

//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
 {
//----
 
//----
   return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
 {
//----
   ObjectDelete("Obj_Label");
   ObjectDelete("Obj_Label2");
//----
   return(0);
}
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
 {
   
 

double prise = Bid;                                                             //текущая цена
double CurrMAValue = iMA(Symb, Period(),Period_MA, 0,Mode_EMA, PRICE_CLOSE, 0); //значение скользящей средней
double Price2MA = price - CurrMAValue;                                          //расстояние о МА до цены
datetime NextClose = Time(0) + Period()*60*2;                                   //время до закрытия
int MinutesToNextClose = (NextClose - TimeCurrent())/60 + 1;                    //время до закрытия в минутах

//int err;



//обновление текст информации на графике

ObjectSetText ("Obj_Label", "ТФ" + Period() + ", " + DoubleToStr(price, 4) + ", тик " + TimeToStr(TimeCurrent(), TIME_SECONDS) + ", O@" + TimeToStr(Time[0], TIME_MINUTES) + ", NC@" + TimeToStr(NextClose, TIME_MINUTES) + " (" + MinutesToNextClose + " min)", 10,
ObjectSetText ("Obj_Label2", "Дельта " + DoubleToStr(Delta,4) + ", знач МА " + DoubleToStr(CurrMAValue, 4) + ", расст до МА " + DoubleToStr(Price2MA, 4), 10, "Arial", DarkGreen );
//анализ цены и выдача алертов

if ((MathAbs(Price2MA) < Delta) &&   // если расстоание до МА меньше дельты
   (Price > CurrMAValue) &&          // и цена выше МА
   (Open(0) > CurrMAValue+Delta))    // и текущая свеча открылась выше, чем МА+дельта
( 
   Alert ("Цена подощла к МА сверху");
)

if ((MathAbs(Price2MA) < Delta) &&   // если расстояние до МА меньше дельты
   (price < CurrMAValue) &&          // и цена ниже МА
   (Open(0) < CurrMAValue-Delta))    // и текущая свеча открылась ниже, чем МА-дельта
( 

   Alert ("Цена подошла к МА снизу");
)

   return(0);
}
   
   
//+------------------------------------------------------------------+


A curly bracket has been left out.

 
Please advise how to fix invalid lots amount error for FreeMarginCheck function in EA, when accidentally setting negative volume (lot) value. To have a message about wrong lot, without error message, in the tester
 
Roman Sharanov:

I need to integrate zigzag into my own indicator (now it's counting by handle)

The thing is, my indicator does not use OnCalculate().

So how do I make the zigzag work and how do I get rates_total and prev_calculated?

The rates_total is the number of bars on the chart. It is determined using the Bars function.

prev_calculated - create an analogue on your own, declare it globally (or statically) and write there the actually calculated number of bars in the current iteration. It means, after successful calculations of the indicator values, we need to record the number of current bars in it. If the calculations are unsuccessful, it's better to null it in order to recalculate the indicator values for each bar in the history at the next iteration.

 

Re: Alekseu Fedotov

What is a brace, sorry

 
berkley75:

Re: Alekseu Fedotov

What is a brace, sorry

In parentheses, the argument of the function sin(30)
In square brackets, the index of array x[25].
void start()
{
In curly braces operator block
}
 
Hello, could you please tell me how to show/remove a certain symbol in the "market overview" window?
 
STARIJ:
In parentheses the argument of the function sin(30)
in square brackets the index of array x[25]
void start()
{
In curly braces operator block
}
Thanks, still doesn't compile! Even if you put a curly brace at the end, which I noticed!!!!
Reason: