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

 
neverness:

I've already described the simplest task.

Open MetaEditor.

Click File->Create.

In the pop-up field select Indicator.

...

But this code is not accepted by MQL translator.

I will answer in about 20 minutes

 
neverness:

What are you children doing, really, stirring up the waters?

Nobody's making a fuss. The situation is finally beginning to clear up a bit. It turns out that you call a script a function that cannot be placed in the body of the main code.

Also do not forget that MT is intended to work with money that must be protected from the attacks of third parties. Hence most of the limitations of the language.

neverness:

I have already described a simple task.

Open MetaEditor.

Click File->Create.

In the pop-up field select Indicator.

In the Indicator OnCalculate() field embed any script object with the OnStart() event.

I personally don't know how to do it. Well, for example like this:

int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
for(int i = 1; i < 100;i++)

{

if(open[i] > Max)

{

OnStart()

And here we write a script for building the object we are interested in. For example, an ellipse or a letter on a chart or something else

} //if(open)

} //for(int i)
//--- return value of prev_calculated for next call
return(rates_total)
} // OnCalculate

That should look something like this.

But the MQL translator does not perceive such a code.

It should look something like this

int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
for(int i = 1; i < 100;i++)
      {
      if(open[i] > Max)
            {
            
           if(int  ObjectFind(chart_id, /* идентификатор графика*/ object_name/* имя объекта*/) < 0)
            ObjectCreate(Здесь параметры функции согласно документации.
                         Например, эллипса, или буквы на графике, или еще чего-нибудь);
               
            }  //if(open)
      }  //for(int i)  
//--- return value of prev_calculated for next call
   return(rates_total);
  } // OnCalculate
 
Vitaly Muzichenko:

In about 20 minutes I'll answer.

It took a long time to upload the video - over 40 minutes.


//+------------------------------------------------------------------+
//|                                                          Set.mq5 |
//|                                                   Copyright 2018 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2018"
#property version   "1.00"
#property indicator_chart_window
#property indicator_plots 0

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
 {
  EllipseCreate(0, "Ellipse", 0, 0, 0, 0, 0, 0, 0, clrRed, STYLE_SOLID, 1, true, true);
//--- indicator buffers mapping
   return(INIT_SUCCEEDED);

 }
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
//---
 ArraySetAsSeries(time,true);
 ArraySetAsSeries(open,true);
 // ....
  ObjectMove(0, "Ellipse",0,time[1],open[5]);
  ObjectMove(0, "Ellipse",1,time[10],open[15]);
  ObjectMove(0, "Ellipse",2,time[20],open[25]);
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+

bool EllipseCreate(const long            chart_ID=0,        // ID графика 
                   const string          name="Ellipse",    // имя эллипса 
                   const int             sub_window=0,      // номер подокна  
                   datetime              time1=0,           // время первой точки 
                   double                price1=0,          // цена первой точки 
                   datetime              time2=0,           // время второй точки 
                   double                price2=0,          // цена второй точки 
                   datetime              time3=0,           // время третьей точки 
                   double                price3=0,          // цена третьей точки 
                   const color           clr=clrRed,        // цвет эллипса 
                   const ENUM_LINE_STYLE style=STYLE_SOLID, // стиль линий эллипса 
                   const int             width=1,           // толщина линий эллипса 
                   const bool            fill=false,        // заливка эллипса цветом 
                   const bool            back=false,        // на заднем плане 
                   const bool            selection=true,    // выделить для перемещений 
                   const bool            hidden=true,       // скрыт в списке объектов 
                   const long            z_order=0)         // приоритет на нажатие мышью 
  { 
//--- установим координаты точек привязки, если они не заданы 
  // ChangeEllipseEmptyPoints(time1,price1,time2,price2,time3,price3); 
//--- сбросим значение ошибки 
   ResetLastError(); 
//--- создадим эллипс по заданным координатам 
   if(!ObjectCreate(chart_ID,name,OBJ_ELLIPSE,sub_window,time1,price1,time2,price2,time3,price3)) 
     { 
      Print(__FUNCTION__, 
            ": не удалось создать эллипс! Код ошибки = ",GetLastError()); 
      return(false); 
     } 
//--- установим цвет эллипса 
   ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr); 
//--- установим стиль линий эллипса 
   ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style); 
//--- установим толщину линий эллипса 
   ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width); 
//--- включим (true) или отключим (false) режим заливки эллипса 
   ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill); 
//--- отобразим на переднем (false) или заднем (true) плане 
   ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back); 
//--- включим (true) или отключим (false) режим выделения эллипса для перемещений 
//--- при создании графического объекта функцией ObjectCreate, по умолчанию объект 
//--- нельзя выделить и перемещать. Внутри же этого метода параметр selection 
//--- по умолчанию равен true, что позволяет выделять и перемещать этот объект 
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection); 
   ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection); 
//--- скроем (true) или отобразим (false) имя графического объекта в списке объектов 
   ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden); 
//--- установим приоритет на получение события нажатия мыши на графике 
   ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order); 
//--- успешное выполнение 
   return(true); 
  } 
Files:
Set.mq5  10 kb
 
Vitaly Muzichenko:

It took a long time to load the video - more than 40 minutes.

I also sometimes mix up forum sections and write an answer to a question on mql4 in mql5.

In principle, in this case nothing will change except the file extension, but in mql4 it will be superfluous

 ArraySetAsSeries(time,true);
 ArraySetAsSeries(open,true);

and even completely unnecessary and useless.

 
neverness:

What are you children doing, really, stirring up the waters?

Just go into the MetaEditor, and type in the command: File->Create...

This will bring up a form with different dummy files.

In particular, it will be dummy files:

- Expert Advisor

- Custom indicator

- Script

- Library, etc.

We are interested in the first three items: Expert Advisor, Custom Indicator and Script.

Let's compare these dummies:

In Expert Advisor we have events:

-OnInit(), OnDeinit(), OnTick(), OnTimer, OnChartEvent() ... everything, no more.

In the script we have the events:

- OnStart() ... that's it, no more.

in the indicator we have events:

- OnInit(), OnCalculate(), OnTimer, OnChartEvent() ... everything, no more.

The natural question here is how to make the connection between these objects.

It turns out that there is and can be no connection between them in MQL, because the data streams between these objects are completely separated and there is no connection between them.

Moreover, I am surprised by the fact that the creators of MQL give us this fact as a "good".

And if, for example, in C++ I can easily call the BASIC translator or Javascript or any other translator and switch, for example, to Android programming environment,

in the framework of MQL, I can't even create a so-called "script" in "indicator" environment, because indicator environment doesn't accept OnStart() command.

What kind of freak is this?

And there are more than enough of such ugly things in MQL.

They are at every step.

I read the description of MQL - and I'm surprised, because there's nothing else to do.

All the while the creators of MQL loudly proclaim that MQL is a descendant of C++.

Of course, I'm sorry, but I want to ask MQL creators: - Heir to what? - In its ugliness?


I unintentionally compare MQL with the famous 1C programming environment. They also claim to be the heirs of C++.

But everything is made much more decently there.

And the graphical objects, and communication between modules and much more.

And what's there in MQL?

No built-in classes, no thread-related objects... and nothing at all.

And I haven't said anything about the mathematical shell of the terminal!!!

That's a whole separate topic for surprises!!!

Why don't you just read a bit of Help and find all those things you're saying don't exist, read about built-in classes in SB, learn how to ask for help politely (you did ask for help) and learn how not to be rude to people who are trying to help you (note this disinterestedly)...

In general - ban you for 24 hours for trolling, rudeness and begging (you have not shown a line of your code to prove all your statements, but impudently require people who have responded to your question and statements, they will provide you with working code for your needs - it's not usual here - they help, not do for you, note - the simplest code)

No offense - the one who comes to us with nothing will be killed by something unintelligible.

Moreover, I warned you to turn down the heat:

 

how to install mt4 on macOS? help please!

 

Exclusively in a virtual machine. I have Parallel's expensive but convenient and reliable.

https://www.parallels.com/ru/products/desktop/

Запуск Windows на Mac — виртуальная машина Parallels Desktop 14 для Mac
  • www.parallels.com
Можно запустить Windows параллельно с macOS® (перезагрузка не требуется) на компьютерах MacBook®, MacBook Pro®, iMac®, iMac Pro®, Mac mini® или Mac Pro®. Предоставляйте общий доступ к файлам и папкам, копируйте и вставляйте текст и изображения, перетаскивайте файлы между приложениями Mac и Windows. Удобная настройка Parallels Desktop...
 

I'm asking for help. The questions are:

1. The program does not set stop losses on both buy and sell in test mode. But modification of pending orders goes well.

2. It does not start in real time on account.

Please, help.

I also would like to request to point out any errors that may have occurred while writing the program.

Many thanks in advance.

Program code:

.input int Percent=50;

input int MAGICNUMBER=413;

//Introduction of indicator constants and oscillators for the long-term charts

input int Signal_Period_long_term=6;

input int Fast_EMA_Period_long_term=12;

input int Slow_EMA_Period_long_term=24;

//Impact parameters of indicators and oscillators constants for short-term charts

input int Stochastic_Kperiod_short_term=5;

input int Stochastic_Dperiod_short_term=3;

input int Stochastic_slowing_short_term=3;

input ENUM_TIMEFRAMES PERIODs_short_term=PERIOD_M5;

input ENUM_TIMEFRAMES PERIODs_long_term=PERIOD_H1;

//-----------------------------------------------------------------------------------------

//common variables and their types

static datetime New_Time;//time of current bar

static datetime Time_Local;

double Margin_Percent; //Opening means for opening of orders

double Lots;//Determination of total number of lots

double Lots_Volume;

//Variables and types for the long-term chart

double MacdCurrent_long_term;//MACD parameters of the main line of the current bar

double MacdPrevious_long_term;//MACD parameters of the main line of the previous bar

double SignalCurrent_long_term;

//Variables and types for the short-term chart

double Stochastic_Current_short_term_main;//Stochastic parameters of the current bar on the 5-minute chart

double Stochastic_Previous_short_term_main;//Stochastic parameters of the previous bar on the 5-minute chart

double Stochastic_Current_short_term_signal;//Stochastic parameters of the current bar in the 5-minute chart

double Stochastic_Previous_short_term_signal;//Stochastic parameters of the previous bar in the 5-minute chart

double StopLoss_BUY;

double StopLoss_SELL;

double Price_BUY;

double Price_SELL;

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

//| Expert initialisation function |

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

int OnInit()

{

//---


//---

return(INIT_SUCCEEDED);

}

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

//| Expert deinitialization function |

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

void OnDeinit(const int reason)

{

//---


}

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

//| expert tick function |

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

void OnTick()

{

int ticket,cnt;

int total=OrdersTotal();// Determination of the number of orders

bool New_Bar=false; // Flag new bar


//Defining the variable values for the long-term chart

MacdCurrent_long_term=iMACD(NULL,PERIODs_long_term,Fast_EMA_Period_long_term,Slow_EMA_Period_long_term,Signal_Period_long_term,PRICE_TYPICAL,MODE_MAIN,1);

MacdPrevious_long_term=iMACD(NULL,PERIODs_long_term,Fast_EMA_Period_long_term,Slow_EMA_Period_long_term,Signal_Period_long_term,PRICE_TYPICAL,MODE_MAIN,2);

SignalCurrent_long_term=iMACD(NULL,PERIODs_long_term,Fast_EMA_Period_long_term,Slow_EMA_Period_long_term,Signal_Period_long_term,PRICE_TYPICAL,MODE_SIGNAL,1);

//Determination of variable values for the short-term chart

Stochastic_Current_short_term_main=iStochastic(NULL,PERIODs_short_term,Stochastic_Kperiod_short_term,Stochastic_Dperiod_short_term,Stochastic_slowing_short_term,MODE_SMA,0,MODE_MAIN,1);

Stochastic_Previous_short_term_main=iStochastic(NULL,PERIODs_short_term,Stochastic_Kperiod_short_term,Stochastic_Dperiod_short_term,Stochastic_slowing_short_term,MODE_SMA,0,MODE_MAIN,2);

Stochastic_Current_short_term_signal=iStochastic(NULL,PERIODs_short_term,Stochastic_Kperiod_short_term,Stochastic_Dperiod_short_term,Stochastic_slowing_short_term,MODE_SMA,0,MODE_SIGNAL,1);

Stochastic_Previous_short_term_signal=iStochastic(NULL,PERIODs_short_term,Stochastic_Kperiod_short_term,Stochastic_Dperiod_short_term,Stochastic_slowing_short_term,MODE_SMA,0,MODE_SIGNAL,2);

//Definition of common variables

Price_BUY=iHigh(NULL,PERIODs_short_term,1)+MarketInfo(NULL,MODE_STOPLEVEL)*MarketInfo(NULL,MODE_POINT);

Price_SELL=iLow(NULL,PERIODs_short_term,1)-MarketInfo(NULL,MODE_STOPLEVEL)*MarketInfo(NULL,MODE_POINT);

StopLoss_BUY=iLow(NULL,PERIODs_short_term,1)-MarketInfo(NULL,MODE_STOPLEVEL)*MarketInfo(NULL,MODE_POINT);

StopLoss_SELL=iHigh(NULL,PERIODs_short_term,1)+MarketInfo(NULL,MODE_STOPLEVEL)*MarketInfo(NULL,MODE_POINT);

Margin_Percent=AccountFreeMargin()*Percent/100;

Lots=NormalizeDouble(Margin_Percent/MarketInfo(Symbol(),MODE_MARGINREQUIRED),2);

Lots_Volume=NormalizeDouble(MathFloor(Lots)+MarketInfo(Symbol(),MODE_LOTSTEP),2);

//-----------------------------------------------------------------------------------------------------------------------

//----- Определение нового бара------------------------------------------------------------------------------------------

New_Time=TimeCurrent();

Print("Time=",TimeCurrent();

Print("Bar open time =",iTime(NULL,PERIODs_short_term,0));

if(iTime(NULL,PERIODs_short_term,0)==New_Time) // Compare times

{

if(iVolume(NULL,PERIODs_short_term,0)<=2) //compare volume

Print("Bar volume =",Volume[0]);

if(iBarShift(NULL,PERIODs_short_term,TimeCurrent())==0)//Check the bar index

Print("Bar index =",iBarShift(NULL,PERIODs_short_term,TimeCurrent());

New_Bar=true; // A new bar is caught

Print("New_Bar");

}

else if(New_Bar==false) // If the bar is not new...

{

Print("Bar is not new");

return;

}

//---Check for availability of funds for opening the minimum lot

if(Margin_Percent<MarketInfo(Symbol(),MODE_MARGINREQUIRED)*(MarketInfo(Symbol(),MODE_MINLOT))

{

Print("Not enough funds. Free funds = ",AccountFreeMargin());

return;

}

//---Determination of lots number

if(Lots>Lots_Volume)

{

Lots=NormalizeDouble(Lots_Volume,2);

Print("Number of lots : ",Lots);

}

else if(Lots<Lots_Volume)

{

Lots=NormalizeDouble(MathFloor(Lots),2);

Print("Number of lots : ",Lots);

}

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

//| Conditions for opening of orders if the number of orders is equal to zero |

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

if(total<1)

{


if(MacdCurrent_long_term<0 && MacdCurrent_long_term>SignalCurrent_long_term)

Print("Condition is true for BUY");

{

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

//| Condition for opening a long BUY position only |

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

if(Stochastic_Current_short_term_main<Stochastic_Current_short_term_signal && Stochastic_Previous_short_term_main>=Stochastic_Previous_short_term_signal)

{

ticket=OrderSend(Symbol(),OP_BUYSTOP,Lots,Price_BUY,3,0,0,NULL,MAGICNUMBER,0,Blue);

if(ticket>0)//check position opened

{

if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))

{

Print("BUY order open : ",OrderOpenPrice());

return;

}

else Print("BUY order open error : ",GetLastError());

return;

}

}

}

if(MacdCurrent_long_term>0 && MacdCurrent_long_term<SignalCurrent_long_term)

Print("Condition is true for SELL");

{

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

//| Condition for opening of short SELL positions only |

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

if(Stochastic_Current_short_term_main>Stochastic_Current_short_term_signal && Stochastic_Previous_short_term_main<=Stochastic_Previous_short_term_signal)

{

ticket=OrderSend(Symbol(),OP_SELLSTOP,Lots,Price_SELL,3,0,0,NULL,MAGICNUMBER,0,Green);

if(ticket>0)//check position opened

{

if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))

{

Print("SELL order open : ",OrderOpenPrice());

return;

}

else Print("Error opening SELL order : ",GetLastError());

return;

}

}

}

}


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

//| Order modification conditions |

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


for(cnt=0;cnt<total;cnt++)

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

//| |

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

{

if(!OrderSelect(cnt,SELECT_BY_POS,MODE_TRADES))

continue;

if(OrderMagicNumber()==MAGICNUMBER && // check the magic number of the order

OrderSymbol()==Symbol()) // check for the order symbol

{

//--- long position opened

if(OrderType()==OP_BUYSTOP)

{

if(OrderOpenPrice()<Price_BUY && Ask<Price_BUY)

{

if(OrderModify(OrderTicket(),Price_BUY,0,0,0,Blue))

Print("Price_BUY order has been successfully modified.");

else Print("Error modifying the BUYStop order. Error code=",GetLastError());

return;

}

else Print("Modification price is higher than order price");

return;

}

if(OrderType()==OP_SELLSTOP)

{

if(OrderOpenPrice()<Price_SELL && Bid>Price_SELL)

{

if(OrderModify(OrderTicket(),Price_SELL,0,0,0,Green))

Print("Price_SELL order has been successfully modified.");

else Print("Error modifying the order SELLStop. Error code=",GetLastError();

return;

}

}

if(OrderType()==OP_BUY)

{

if(OrderStopLoss()<StopLoss_BUY && StopLoss_BUY<Ask)

{

if(OrderModify(OrderTicket(),OrderOpenPrice(),StopLoss_BUY,0,0,Blue))

Print("Price_BUY order price successfully modified.");

else Print("Error modifying the BUY order. Error code=",GetLastError());

return;

}

}

if(OrderType()==OP_SELL)

{

if(OrderStopLoss()>StopLoss_SELL && StopLoss_SELL>Bid)

{

if(OrderModify(OrderTicket(),OrderOpenPrice(),StopLoss_SELL,0,0,Green))

Print("Price_SELL order price successfully modified.");

else Print("Error modifying the SELL order. Error code=",GetLastError();

return;

}

}

}

}


}

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

 

Help fix a bug in the indicator, it does not draw high and low of the day when it is on the last candle of the hour.

https://prnt.sc/kut6xo

https://prnt.sc/kut79b

Скриншот
Скриншот
  • prnt.sc
Снято с помощью Lightshot
Files:
 
Michail_David:

I'm asking for help. The questions are:

1. The program does not set stop losses on both buy and sell in test mode. But modification of pending orders goes well.

2. It does not start in real time on account.


This is how

 if(OrderType()==OP_SELL)

           {

            if(OrderStopLoss()!= StopLoss_SELL && StopLoss_SELL>Bid)

will modify AND code, insert it correctly (Alt+S).

Reason: