Questions from Beginners MQL5 MT5 MetaTrader 5 - page 1312

 
Alexey Belyakov:
I changed it and get error: " 'array_atr' - invalid array access "


maybe something will help - you just need to create an indicator, not an expert

- The Expert Advisor works in the same way, but it will be displayed in the tester

//+------------------------------------------------------------------+
//|                                                         тест.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
//--- plot iATR
#property indicator_label1  "iATR"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrLightSeaGreen
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- входные параметры
input int                  atr_period=14;          // период для вычисления
input string               symbol=" ";             // символ
input ENUM_TIMEFRAMES      period=PERIOD_CURRENT;  // таймфрейм
//--- индикаторный буфер
double iATRBuffer[];
//--- переменная для хранения хэндла индикатора iAC
int    handle;
//--- переменная для хранения
string name=symbol;
//--- имя индикатора на графике
string short_name;
//--- будем хранить количество значений в индикаторе Average True Range
int    bars_calculated=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- привязка массива к индикаторному буферу
   SetIndexBuffer(0,iATRBuffer,INDICATOR_DATA);
//--- определимся с символом, на котором строится индикатор
   name=symbol;
//--- удалим пробелы слева и справа
   StringTrimRight(name);
   StringTrimLeft(name);
//--- если после этого длина строки name нулевая
   if(StringLen(name)==0)
     {
      //--- возьмем символ с графика, на котором запущен индикатор
      name=_Symbol;
     }
//--- создадим хэндл индикатора
   handle=iATR(name,period,atr_period);
   if(handle==INVALID_HANDLE)
     {
      //--- сообщим о неудаче и выведем номер ошикби
      PrintFormat("Не удалось создать хэндл индикатора iATR для пары %s/%s, код ошибки %d",
                  name,
                  EnumToString(period),
                  GetLastError());
      //--- работа индикатора завершается досрочно
      return(INIT_FAILED);
     }
//--- покажем на какой паре символ/таймфрейм рассчитан индикатор Average True Range
   short_name=StringFormat("iATR(%s/%s, period=%d)",name,EnumToString(period),atr_period);
   IndicatorSetString(INDICATOR_SHORTNAME,short_name);
//--- нормальное выполнение инициализации индикатора
//---
   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[])
  {
//---- проверка количества баров на достаточность для расчета
   if(BarsCalculated(handle)<rates_total
      ||rates_total<0)
      return(0);
//---- объявления локальных переменных
   int to_copy,limit;
//---- расчеты необходимого количества копируемых данных и
//стартового номера limit для цикла пересчета баров
   if(prev_calculated>rates_total || prev_calculated<=0)// проверка на первый старт расчета индикатора
     {
      to_copy=rates_total; // расчетное количество всех баров
      limit=rates_total-1; // стартовый номер для расчета всех баров
     }
   else
     {
      to_copy=rates_total-prev_calculated+1; // расчетное количество только новых баров
      limit=rates_total-prev_calculated; // стартовый номер для расчета новых баров
     }
//---- копируем вновь появившиеся данные в массивы
   if(CopyBuffer(handle,0,0,to_copy,iATRBuffer)<=0)
      return(0);
//---- индексация элементов в массивах как в таймсериях
   ArraySetAsSeries(iATRBuffer,true);
   ArraySetAsSeries(open,true);
   ArraySetAsSeries(high,true);
   ArraySetAsSeries(low,true);
   ArraySetAsSeries(close,true);
//--- return value of prev_calculated for next call
   return(rates_total);
  }
//+------------------------------------------------------------------+
 
Alexey Belyakov:
Changed and get error: " 'array_atr' - invalid array access "


An array element is referenced with '[]'.

For example, a reference to a null element:

array_atr[0]
 
Vladimir Karputov:

An array element is referenced with '[]'.

For example, a reference to a null element:


double array_atr[];   

int ATR14;

int OnInit()
  {
ATR14=iATR(NULL,PERIOD_CURRENT,14);
  return(0);   
  }
   
void OnDeinit(const int reason)
  {
//---  
  }

void OnTick()
{

CopyBuffer(ATR14,0,0,2,array_atr);

Comment(

      "ATR14==: ",DoubleToString((array_atr[1])*100000,0),"\n");

}
Vladimir Thank you! Done!
 
Alexey Belyakov:


Vladimir Thank you! Done!

I wanted to find out what you were trying to get and I only got as far as here and didn't get it.

//+------------------------------------------------------------------+
//|                                              Alexey Belyakov.mq5 |
//|                                  Copyright 2021, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2021, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#include <Trade\Trade.mqh>
CTrade ExtTrade;
//---
int ATR14;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create ATR indicator and add it to collection
   ATR14=iATR(_Symbol,_Period,14);
   if(ATR14==INVALID_HANDLE)
     {
      printf("Error creating ATR indicator");
      return(INIT_FAILED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   OnATR14();
  }
//+------------------------------------------------------------------+
//| refresh indicators                                               |
//+------------------------------------------------------------------+
void OnATR14()
  {
   MqlRates rt[2];
//--- go trading only for first ticks of new bar
   if(CopyRates(_Symbol,_Period,0,2,rt)!=2)
     {
      Print("CopyRates of ",_Symbol," failed, no history");
      return;
     }
   if(rt[1].tick_volume>1)
      return;
//--- get current Moving Average
   double array_atr[1];
//--- get current ATR
   if(CopyBuffer(ATR14,0,0,1,array_atr)!=1)
     {
      Print("CopyBuffer from ATR failed, no data");
      return;
     }
   if(array_atr[0]>=0.00100 && rt[0].close>array_atr[0])
     {
      Print("ATR14==: BUY");
     }
   if(array_atr[0]<=0.00100 && rt[0].close>array_atr[0])
     {
      Print("ATR14==: SELL");
     }
  }
//+------------------------------------------------------------------+
 
Hi!
I am only beginning to understand the code, so please be lenient to my illiteracy in programming.
I can't cope with the translation of this piece in mql5:

int init() 
   {
   parus = MarketInfo(Symbol(), MODE_SPREAD) * Point;
   if (IsTesting() == true) rf();
   if (IsTesting() == false) rm();
   return (0);
   }

I change MarketInfo to SymbolInfoInteger and I get - so:

int init() 
   {
   parus = SymbolInfoInteger(Symbol(),SYMBOL_SPREAD_FLOAT) * Point;
   if (IsTesting() == true) rf();
   if (IsTesting() == false) rm();
   return (0);
   }

and I get errors.

possible loss of data due to type conversion

';' - open parenthesisexpected


Please help me and tell me how it should work.





 
Sprut 185:
Hi!
I am only beginning to understand a code and I ask you to be lenient to my illiteracy in programming.
I can't cope with the translation of this piece in mql5:

I change MarketInfo to SymbolInfoInteger and I get - so:

and I get errors.

possible loss of data due to type conversion

';' - open parenthesisexpected


Please help and write how it should be in fact.

   parus = SymbolInfoInteger(Symbol(),SYMBOL_SPREAD) * Point();
   if(MQLInfoInteger(MQL_TESTER) == true) rf();
   if(MQLInfoInteger(MQL_TESTER) == false) rm();

Or better like this

   parus = SymbolInfoInteger(Symbol(),SYMBOL_SPREAD) * Point();
   if(MQLInfoInteger(MQL_TESTER)) rf();
    else rm();
 
Vitaly Muzichenko:

Or better still

Thank you very much for your help !


Now I can't figure out why it says this:

int user_0 = SymbolInfoInteger(Symbol(), SYMBOL_TRADE_STOPS_LEVEL);

possible loss of data due to type conversion

What's wrong with it?


 
Sprut 185:
Thanks so much for your help !


Now I can't figure out why it says this:

possible loss of data due to type conversion

What's wrong here?


Long or bul Not int.

Документация по MQL5: Получение рыночной информации / SymbolInfoInteger
Документация по MQL5: Получение рыночной информации / SymbolInfoInteger
  • www.mql5.com
SymbolInfoInteger - Получение рыночной информации - Справочник MQL5 - Справочник по языку алгоритмического/автоматического трейдинга для MetaTrader 5
 
Valeriy Yastremskiy:

Long or Bull Not Int.

Thanks for figuring it out !!!

Now it's not clear - what's wrong - here:

trendstep = "Tredstep start on" +Trendstep_start+ " order";

error : implicit conversion from 'number' to 'string'

is there something wrong with the pluses?


 
Sprut 185:
Thanks sorted !!!

Now it's not clear - what's wrong - here:

error : implicit conversion from 'number' to 'string'

is there something wrong with the pluses?


NOT an implicit conversion. It's when you add strings to numbers, the numbers are converted to string variables. And you need an explicit one. and hopefully trendstep has a string type. )))

trendstep = "Tredstep start on" +(string) Trendstep_start+ " order";