How to start with MQL5 - page 10

 
Vladimir Karputov:

Algorithm: issue the 'ChartOpen' command -> check the value, if the value is greater than '0' -> try the template using the 'ChartApplyTemplate' command.

Code: ChartOpen ChartApplyTemplate.mq5

Thanks for helping me, it works fine. But sometimes the strategy of my logic is executed after another 3 candles or so and the ChartOpen ChartApplyTemplete is executed again and the same chart is opened again, how can i code it so that if chart already is open dont open again, Thank you
 
GeorgeReji :
Expert Advisor

Code: Example Bullish Bearish.mq5

To get OHLC from the advisor, it is optimal to request CopyRates to the array of the MqlRates structure. Apply to the array

- now in the 'rates' array element [0] corresponds to the rightmost bar on the chart.

//+------------------------------------------------------------------+
//|                                      Example Bullish Bearish.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
//--- input parameters
input int      Input1=9;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   Comment("");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   MqlRates rates[];
   ArraySetAsSeries(rates,true);
   int start_pos=0,count=3;
   if(CopyRates(Symbol(),Period(),start_pos,count,rates)!=count)
      return;
//---
   string text=(rates[0].open<rates[0].close)?"Bullish":"Bearish";
   Comment(text);
  }
//+------------------------------------------------------------------+


Result:

Example Bullish Bearish

Documentation on MQL5: Timeseries and Indicators Access / CopyRates
Documentation on MQL5: Timeseries and Indicators Access / CopyRates
  • www.mql5.com
Gets history data of MqlRates structure of a specified symbol-period in specified quantity into the rates_array array. The elements ordering of the copied data is from present to the past, i.e., starting position of 0 means the current bar. If you know the amount of data you need to copy, it should better be done to a statically allocated...
 
Ahmad861 :
Thanks for helping me, it works fine. But sometimes the strategy of my logic is executed after another 3 candles or so and the ChartOpen ChartApplyTemplete is executed again and the same chart is opened again, how can i code it so that if chart already is open dont open again, Thank you

Keep records of open charts (more precisely, keep records of not chart numbers, but records of actions: the symbol "such and such", the timeframe "such and such" is already open.

 
Vladimir Karputov:

Code: Example Bullish Bearish.mq5

To get OHLC from the advisor, it is optimal to request CopyRates to the array of the MqlRates structure. Apply to the array

- now in the 'rates' array element [0] corresponds to the rightmost bar on the chart.


Result:


Not regular bullish or bearish candles, small bodied candles with large wicks on both sides
 
Ahmad861 :
Not regular bullish or bearish candles, small bodied candles with large wicks on both sides

You have to take my sample and make changes from it yourself. I can't see your code. I do not see your desire to code.

 
im using bollinger bands and before trading i check if the distance between upper and lower bollinger band is minimum 30 pips

double   BB_pSize = NormalizeDouble((BB_2_Upper[1]-BB_2_Lower[1])/_Point,2);
double   BB_MinSize = 300.00;

    
    
    
if(BB_pSize>=BB_MinSize)Alert("YES");
else Alert("NO");

This works fine when i test on a script and run, but i use it in my logic of my expert advisor and even if the condition is false, the code is executed without any problems

Bollinger Bands ®
Bollinger Bands ®
  • www.mql5.com
Bollinger Bands ® technical indicator (BB) is similar to Envelopes. The only difference is that the bands of Envelopes are plotted a fixed distance (%) away from the moving average, while the Bollinger Bands are plotted a certain number of standard deviations away from it. Standard deviation is a measure of volatility, therefore Bollinger Bands...
 
GeorgeReji :
im using bollinger bands and before trading i check if the distance between upper and lower bollinger band is minimum 30 pips

This works fine when i test on a script and run, but i use it in my logic of my expert advisor and even if the condition is false, the code is executed without any problems

What is your question?

 

Example: how to get the value of the iSAR indicator in an advisor.

Code: iSAR Get Value.mq5

ATTENTION: In OnInit we get the indicator handle (type 'int') - we do it ONCE. Further, we get the indicator values using CopyBuffer .

Advisor code:

//+------------------------------------------------------------------+
//|                                               iSAR Get Value.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
//--- input parameters
input group                "SAR"
input double            Inp_SAR_step          = 0.02;       // SAR: price increment step - acceleration factor
input double            Inp_SAR_maximum       = 0.2;        // SAR: maximum value of step
input group                "Additional features"
input bool              InpPrintLog          = false;       // Print log
//---
int    handle_iSAR;                          // variable for storing the handle of the iSAR indicator
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create handle of the indicator iSAR
   handle_iSAR=iSAR(Symbol(),Period(),Inp_SAR_step,Inp_SAR_maximum);
//--- if the handle is not created
   if(handle_iSAR==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iSAR indicator for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   if(handle_iSAR!=INVALID_HANDLE)
      IndicatorRelease(handle_iSAR);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   double sar[];
   MqlRates rates[];
   ArraySetAsSeries(sar,true);
   ArraySetAsSeries(rates,true);
   int start_pos=0,count=2;
   if(!iGetArray(handle_iSAR,0,start_pos,count,sar) || CopyRates(Symbol(),Period(),start_pos,count,rates)!=count)
      return;
//---
   string text="";
   int limit=(count>2)?2:count;
   for(int i=0; i<limit; i++)
     {
      text=text+
           " bar #"+IntegerToString(i)+": "+
           " sar "+DoubleToString(sar[i],Digits())+((sar[i]>=rates[i].high)?" UP":" DOWN")+
           "\n";
     }
   Comment(text);
  }
//+------------------------------------------------------------------+
//| Get value of buffers                                             |
//+------------------------------------------------------------------+
bool iGetArray(const int handle,const int buffer,const int start_pos,
               const int count,double &arr_buffer[])
  {
   bool result=true;
   if(!ArrayIsDynamic(arr_buffer))
     {
      if(InpPrintLog)
         PrintFormat("ERROR! EA: %s, FUNCTION: %s, this a no dynamic array!",__FILE__,__FUNCTION__);
      return(false);
     }
   ArrayFree(arr_buffer);
//--- reset error code
   ResetLastError();
//--- fill a part of the iBands array with values from the indicator buffer
   int copied=CopyBuffer(handle,buffer,start_pos,count,arr_buffer);
   if(copied!=count)
     {
      //--- if the copying fails, tell the error code
      if(InpPrintLog)
         PrintFormat("ERROR! EA: %s, FUNCTION: %s, amount to copy: %d, copied: %d, error code %d",
                     __FILE__,__FUNCTION__,count,copied,GetLastError());
      //--- quit with zero result - it means that the indicator is considered as not calculated
      return(false);
     }
   return(result);
  }
//+------------------------------------------------------------------+


Result:

iSAR Get Value

Documentation on MQL5: Timeseries and Indicators Access / CopyBuffer
Documentation on MQL5: Timeseries and Indicators Access / CopyBuffer
  • www.mql5.com
Counting of elements of copied data (indicator buffer with the index buffer_num) from the starting position is performed from the present to the past, i.e., starting position of 0 means the current bar (indicator value for the current bar). When copying the yet unknown amount of data, it is recommended to use a dynamic array as a buffer[]...
Files:
 

Problem: there can be only one position at a time. The check is the same for netting and hedge accounts.

We check if there is a position by symbol, while there is no check by Magic number.

Code: IsPositionExists.mq5


//+------------------------------------------------------------------+
//|                                             IsPositionExists.mq5 |
//|                              Copyright © 2020, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2020, Vladimir Karputov"
#property version   "1.000"
#include <Trade\PositionInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
//--- input parameters
input int      Input1=9;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(!IsPositionExists("EURUSD"))
     {
      //--- open positions "EURUSD"
     }
   else
     {
      return;
     }
//---
   if(!IsPositionExists("USDJPY"))
     {
      //--- open positions "USDJPY"
     }
   else
     {
      return;
     }
//---
  }
//+------------------------------------------------------------------+
//| Is position exists                                               |
//+------------------------------------------------------------------+
bool IsPositionExists(const string symbol)
  {
   for(int i=PositionsTotal()-1; i>=0; i--)
      if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
         if(m_position.Symbol()==symbol)
            return(true);
//---
   return(false);
  }
//+------------------------------------------------------------------+
Files:
 
Dear Vladimir, can you help me to make an EA with only fractal indicator signals. and wear SL and TP and trailing. for scalping trading. hopefully it can provide better colors in the mql5 world. You are a very good programmer.

 10:21

 Dear Vladimir, you can help me to make an Expert Advisor based on signals from fractal indicators only. and use SL, TP and trailing. for scalping. Hopefully it will increase the color in the MQL5 world. You are a very good programmer.

 10:22

 hope you can help me just to share. with fractal indicator codebase only for each transaction. if there is a fractal sign will open if not advance. and placing pending orders above the fractal line from the breakout area.

 10:26

 In fact, every time there is a transaction, the fracture will function. For example the fractal above, the trade will sell dan SL and TP.
Документация по MQL5: Константы, перечисления и структуры / Именованные константы / Предопределенные макроподстановки
Документация по MQL5: Константы, перечисления и структуры / Именованные константы / Предопределенные макроподстановки
  • www.mql5.com
//| Expert initialization function                                   | //| Expert deinitialization function                                 | //| Expert tick function                                             | //| test1                                                            |...
Reason: