Questions from Beginners MQL5 MT5 MetaTrader 5 - page 74

 
Hello! I tried to create an indicator that uses 2 symbols (EURUSD and GBPUSD for example), it doesn't draw (gives an error 4806) ... I get indicator handles in the OnInit function (iRSI for example) of each symbol, I copy indicator data to buffers and perform further operations with them ...It receives indicator data for one symbol (the same symbol that coincides with the symbol on the chart, to which I attach the indicator) it is ok, but the indicator data for the second symbol is not received ... I.e. it receives data only for the symbol that coincides with the symbol on the chart, to which it is attached ... what am I doing wrong?
 
FinEngineer:
Hello! I tried to create an indicator that uses 2 symbols (EURUSD and GBPUSD for example), it doesn't draw (gives an error 4806) ... I get indicator handles in the OnInit function (iRSI for example) of each symbol, I copy indicator data to buffers and perform further operations with them ...It receives indicator data for one symbol (the same symbol that coincides with the symbol on the chart, to which I attach the indicator) it is ok, but indicator data for the second symbol is not received ... i.e., it receives data only for the symbol that coincides with the symbol on the chart, to which the indicator is attached ... what am I doing wrong?
So show me the part of the code that caused the problem.
 

I'm posting the whole code, because nothing works, on mql4 everything was much easier, maybe it's just because I'm not used to it... these handles and auxiliary buffers are killing my brain.

I think the meaning is clear (difference in rsi of 2 correlating symbols), please help....point out the errors?

#property copyright "Copyright 2012, MetaQuotes Software Corp.
#property link "http://www.mql5.com"
#property version "1.00"

//---- indicator rendering properties
#property indicator_buffers 3
#property indicator_label1 "Pair_delta_RSI"
#property indicator_type1 DRAW_LINE
#property indicator_color1 Red
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
#property input parameters
input string Symbol1_Name = "EURUSD";
input string Symbol2_Name = "GBPUSD";
input int PeriodRSI=7;
input bool Inversia=false;
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE;

doubleRSI_Buffer[];
double RSI1_Buffer[];
double RSI2_Buffer[];

int RSI1_Handle;
int RSI2_Handle;

int OnInit()
{
SetIndexBuffer(0,DeltaRSI_Buffer,INDICATOR_DATA);
SetIndexBuffer(1,RSI1_Buffer,INDICATOR_CALCULATIONS);
SetIndexBuffer(2,RSI2_Buffer,INDICATOR_CALCULATIONS);

RSI1_Handle=iRSI(Symbol1_Name,0,PeriodRSI,PRICE_CLOSE);//Get indicator handles
RSI2_Handle=iRSI(Symbol2_Name,0,PeriodRSI,PRICE_CLOSE);
return(0);
}

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 &TickVolume[],
const long &Volume[],
const int &Spread[])
{
int calculated=BarsCalculated(RSI1_Handle);
if(calculated<rates_total)
{
Print("Not all data of RSI1_Handle is calculated (",calculated, "bars ). Error",GetLastError());
return(0);
}
calculated=BarsCalculated(RSI2_Handle);
if(calculated<rates_total)
{
Print("Not all data of RSI2_Handle is calculated (",calculated, "bars ). Error",GetLastError());
return(0);
}
//--- we can copy not all data
int to_copy;
if(prev_calculated>rates_total || prev_calculated<0) to_copy=rates_total;
else
{
to_copy=rates_total-prev_calculated;
if(prev_calculated>0) to_copy++;
}
//receive RSI1 buffer
if(CopyBuffer(RSI1_Handle,0,0,to_copy,RSI1_Buffer)<=0)
{
Print("Getting RSI1 is failed! Error",GetLastError());
return(0);
}
//Get RSI2 buffer
if(CopyBuffer(RSI2_Handle,0,0,to_copy,RSI2_Buffer)<=0)
{
Print("Getting RSI2 is failed! Error",GetLastError());
return(0);
}
//---
int limit;
if(prev_calculated==0)
limit=0;
else limit=prev_calculated-1;
//calculate delta rsi indicator
for(int i=limit;i<rates_total; i++)
DeltaRSI_Buffer[i]=RSI1_Buffer[i]-RSI2_Buffer[i];
return(rates_total);
}

Automated Trading and Strategy Testing
Automated Trading and Strategy Testing
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
 

error #1

failure to use the SRC key

 

Such an error occurs, for example, if you take a standard custom MACD indicator and change the following line

ExtFastMaHandle=iMA(NULL,0,InpFastEMA,0,MODE_EMA,InpAppliedPrice);

to

ExtFastMaHandle=iMA("EURUSD",0,InpFastEMA,0,MODE_EMA,InpAppliedPrice);

If MACD is attached to EURUSD chart, everything will be drawn, if it's attached to another chart - error 4806 will appear... How can I make it so that in this indicator I can use as many symbols as I want?

If you know how to make the previously posted indicator work, I'd be very grateful.

 
mario065:

Lester: Here I put a template, inside there is a modification showing how to crawl.

https://www.mql5.com/ru/forum/6343/page73

If you don't want to, you have to count the variables correctly.

I've got the idea of Schablon file with mixed success, brought it to my conditions a bit and it works. However there is a significant deadlock for me - they are set on the next candle, not on a tick. Here is the part of the EA.

  double buy_trail = 0;
  double sel_trail = 0;
  double SL,T_P,Open;
  ulong L_S;
  
  if(PositionSelect(_Symbol))
  {
     Open = PositionGetDouble(POSITION_PRICE_OPEN);
     SL   = PositionGetDouble(POSITION_SL);
     T_P  = PositionGetDouble(POSITION_TP);
     Bid  = SymbolInfoDouble(_Symbol,SYMBOL_BID);
     Ask  = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
     L_S  = SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
     buy_trail = NormalizeDouble(Bid - Open,Digits());
     sel_trail = NormalizeDouble(Open - Ask,Digits()); 
    
    if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
    {
    if(!PositionGetDouble(POSITION_SL))
      {
      PositionModify(_Symbol,NormalizeDouble((Open-STR-TR),Digits()),NormalizeDouble((Open+TP),Digits()));
      }
 
Lester:

With varying success I got the gist of the Schablon file, adjusted it a bit to my conditions and Hooray - stops and profits are set. However there is a significant deadlock for me - they are set on the next candle, not on a tick. Here is a part of the code.

input double TP            = 0.003;
input double STR           = 0.0012;
input double TR            = 0.0002;
//=============================================== 
//Един вид извикване на модификация на отворената позиция
  double buy_trail = 0;
  double sel_trail = 0;
  double SL,T_P,Open;
  ulong L_S;
Ну ладно-обяснения:

  if(PositionSelect(_Symbol)){//Ест ли позиция по символа
     Open = PositionGetDouble(POSITION_PRICE_OPEN);//цена опен для поза
     SL   = PositionGetDouble(POSITION_SL);//цена стоп для поза
     T_P  = PositionGetDouble(POSITION_TP);//цена тейк для поза
     Bid  = SymbolInfoDouble(_Symbol,SYMBOL_BID);//цена бид
     Ask  = SymbolInfoDouble(_Symbol,SYMBOL_ASK);//цена аск
     L_S  = SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);//стоп ниво,если ест такое-оно в пункты
     buy_trail = NormalizeDouble(Bid - Open,Digits());//вычисляем разстояние от цена бид и цена опен позиции-ето для бай
     sel_trail = NormalizeDouble(Open - Ask,Digits());//вычисляем разстояние от цена опен позиции и цена аск-ето для сел
    if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)//если ест бай поза
      {
      if(buy_trail > STR)//если разстояние болше указаное
       {
        if(NormalizeDouble((Bid - STR),Digits()) >= Open && Open > SL)
//если цена бид минус указаное разстояние болше щем цена опен и цена опен болше цена стоп-вызиваем модификация
//сама модификация-для стоп будет цена опен,цена тейк не меняем.
          {
           ModifyPosition(_Symbol,Open,T_P);
          }
          if(NormalizeDouble((Bid - TR),Digits()) > SL && Open <= SL)
//если цена бид минус указаное разстояние TR = 0.0002 болше уже от новый стоп(который поменяли уже) и цена опен менше новый стоп 
//вызиваем модификация
//сама модификация - для стоп будет прошлый стоп минус стоп ниво* _Point(что б стали пипси) плюс указаное TR,цена тейк не меняем.
//Т.е. будем двигат стоп через каждые 2 пипса  
           {
            ModifyPosition(_Symbol,NormalizeDouble(((SL - L_S * _Point) + TR),Digits()),T_P);
           }
        }
      }
    if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
      {
      if(sel_trail > STR)
       { 
        if(NormalizeDouble((Ask + STR),Digits()) <= Open && Open < SL)
          {
           ModifyPosition(_Symbol,Open,T_P);
          }
          if(NormalizeDouble((Ask + TR),Digits()) < SL && Open >= SL)
           {
            ModifyPosition(_Symbol,NormalizeDouble(((SL +L_S * _Point)- TR),Digits()),T_P);
           }
        }
      }
     } 
//===============================================

The code should always contain conditions for some actions, but everything should be checked and have some logic.

If you want to help, print(" ", ); ) and see the result.

 
mario065:

The descriptions are all clear and they work. But this is a modification to "breakeven" and "trailing". I should write a modification to set StopLimit and TakeProfit after order opening, i.e.

1. order opening

--------

2. Modification on Stop Limit setting (this is not available yet!)

 if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
    {
    if(!PositionGetDouble(POSITION_SL))
      {
      PositionModify(_Symbol,NormalizeDouble((Open-STR-TR),Digits()),NormalizeDouble((Open+TP),Digits()));
      }

------

3. Modification for Breakeven

4.Modification to trailing stop

5.Close order


You can use point 2 to modify the order, but only at the beginning of the next bar.

 

A function is written to open eats:

Сама функция(символ,обем,проскалзивание,стоп,тейк,магик)
С вызова функции можно все сразу поставит.
bool BuyPositionOpen(const string symbol,double volume,ulong deviation,double StopLoss,double Takeprofit,int Magic)     
    if(Какое то условие)
      {
       BuyPositionOpen(_Symbol,Lot,0,NormalizeDouble(Ask - 0.003,_Digits),NormalizeDouble(Ask + 0.003,_Digits),MagicNumber);
      }
     if(Какое то условие)
      {
       SellPositionOpen(_Symbol,Lot,0,NormalizeDouble(Bid + 0.003,_Digits),NormalizeDouble(Bid - 0.003,_Digits),MagicNumber);
      }
Функция для закрития:
Сама функция(символ,проскалзивание,магик)
bool BuyPositionClose(const string symbol,ulong deviation,int Magic)
// Логика за затваряне на дългите
      if(Какое то условие){
         BuyPositionClose(_Symbol,0,MagicNumber);}                        
// Логика за затваряне на късите
      if(Какое то условие){
         SellPositionClose(_Symbol,0,MagicNumber);} 

Если не хочете сразу ставит стоп и тейк,тогда:
//=============================================== 
//Един вид извикване на модификация на отворената позиция
  double buy_trail = 0;
  double sel_trail = 0;
  double SL,T_P,Open;
  ulong L_S;
  if(PositionSelect(_Symbol)){
     Open = PositionGetDouble(POSITION_PRICE_OPEN);
     SL   = PositionGetDouble(POSITION_SL);
     T_P  = PositionGetDouble(POSITION_TP);
     Bid  = SymbolInfoDouble(_Symbol,SYMBOL_BID);
     Ask  = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
     L_S  = SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
     buy_trail = NormalizeDouble(Bid - Open,Digits());
     sel_trail = NormalizeDouble(Open - Ask,Digits());
    if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)
      {
if(SL = 0 && T_P = 0)//если стоп и тейк равни нулю-вызиваете модофикация и там акуратно ложите нужная вам цена
{
  ModifyPosition(_Symbol,NormalizeDouble((Open - 0.003),Digits()),NormalizeDouble((Open + 0.003),Digits()));
}
//Далше вам понятно:
      if(buy_trail > STR)
       {
        if(NormalizeDouble((Bid - STR),Digits()) >= Open && Open > SL)
          {
           ModifyPosition(_Symbol,Open,T_P);
          }
          if(NormalizeDouble((Bid - TR),Digits()) > SL && Open <= SL)
           {
            ModifyPosition(_Symbol,NormalizeDouble(((SL - L_S * _Point) + TR),Digits()),T_P);
           }
        }
      }
    if(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_SELL)
      {
      if(sel_trail > STR)
       { 
        if(NormalizeDouble((Ask + STR),Digits()) <= Open && Open < SL)
          {
           ModifyPosition(_Symbol,Open,T_P);
          }
          if(NormalizeDouble((Ask + TR),Digits()) < SL && Open >= SL)
           {
            ModifyPosition(_Symbol,NormalizeDouble(((SL +L_S * _Point)- TR),Digits()),T_P);
           }
        }
      }
     } 
//=============================================== 
 
Are there any MQL5 developers in this thread!? Am I asking a question in the wrong branch? Then tell me how to ask a question to the developers? The question above is elementary for an experienced programmer...
Reason: