How to start with MQL5 - page 39

Kutluhan Yesilkaya
690
Vladimir Karputov #:

An example of get values from the iStochastic indicator

Code: iStochastic get value.mq5

Do not forget the rules: create the indicator handle ONCE in OnInit, use CopyBuffer to get the data.


Result:


Do these codes close the stochastik indicator when the difference between the 2 lines is too large?

Vladimir Karputov
Moderator
306178
Kutluhan Yesilkaya # :

Do these codes close the stochastik indicator when the difference between the 2 lines is too large?

The code provided is an example code on how to properly create an indicator and how to get the indicator's value. That is, this is a training code for an Expert Advisor that does ONLY two things: it shows how to create an indicator correctly and how to get the indicator value.

Vladimir Karputov
Moderator
306178

Very Simple Intersection iMA Open Position

(code 'Very Simple Intersection iMA Open Position.mq5')

The example shows how:

  • create iMA indicator handle
  • get indicator values
  • close and open positions when crossing two iMAs ('Fast' and 'Slow)

//+------------------------------------------------------------------+
//|                   Very Simple Intersection iMA Open Position.mq5 |
//|                              Copyright © 2022, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2022, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
//--- input parameters
input group             "Position size management (lot calculation)"
input double               InpLots                    = 0.01;           // Lots
input group             "MA Fast"
input int                  Inp_MA_Fast_ma_period      = 5;              // MA Fast: averaging period
input int                  Inp_MA_Fast_ma_shift       = 0;              // MA Fast: horizontal shift
input ENUM_MA_METHOD       Inp_MA_Fast_ma_method      = MODE_SMA;       // MA Fast: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_Fast_applied_price  = PRICE_CLOSE;    // MA Fast: type of price
input group             "MA Slow"
input int                  Inp_MA_Slow_ma_period      = 15;             // MA Slow: averaging period
input int                  Inp_MA_Slow_ma_shift       = 0;              // MA Slow: horizontal shift
input ENUM_MA_METHOD       Inp_MA_Slow_ma_method      = MODE_SMA;       // MA Slow: smoothing type
input ENUM_APPLIED_PRICE   Inp_MA_Slow_applied_price  = PRICE_CLOSE;    // MA Slow: type of price
input group             "Additional features"
input ulong                InpMagic                   = 200;            // Magic number
//---
int      handle_iMA_Fast;  // variable for storing the handle of the iMA indicator
int      handle_iMA_Slow;  // variable for storing the handle of the iMA indicator

datetime m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
bool     m_init_error               = false;    // error on InInit
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- forced initialization of variables
   m_prev_bars                = 0;        // "0" -> D'1970.01.01 00:00';
   m_init_error               = false;    // error on InInit
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
   m_trade.SetDeviationInPoints(10);
//---
//--- create handle of the indicator iMA
   handle_iMA_Fast=iMA(Symbol(),Period(),Inp_MA_Fast_ma_period,Inp_MA_Fast_ma_shift,
                       Inp_MA_Fast_ma_method,Inp_MA_Fast_applied_price);
//--- if the handle is not created
   if(handle_iMA_Fast==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator ('Fast') for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      m_init_error=true;
      return(INIT_SUCCEEDED);
     }
//--- create handle of the indicator iMA
   handle_iMA_Slow=iMA(Symbol(),Period(),Inp_MA_Slow_ma_period,Inp_MA_Slow_ma_shift,
                       Inp_MA_Slow_ma_method,Inp_MA_Slow_applied_price);
//--- if the handle is not created
   if(handle_iMA_Slow==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iMA indicator ('Slow') for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Period()),
                  GetLastError());
      //--- the indicator is stopped early
      m_init_error=true;
      return(INIT_SUCCEEDED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//--- we work only at the time of the birth of new bar
   datetime time_0=iTime(Symbol(),Period(),0);
   if(time_0==m_prev_bars)
      return;
   m_prev_bars=time_0;
//---
   double ma_fast[],ma_slow[];
   ArraySetAsSeries(ma_fast,true);
   ArraySetAsSeries(ma_slow,true);
   int start_pos=0,count=6;
   if(!iGetArray(handle_iMA_Fast,0,start_pos,count,ma_fast) || !iGetArray(handle_iMA_Slow,0,start_pos,count,ma_slow))
     {
      m_prev_bars=0;
      return;
     }
//---
   if(ma_fast[2]<ma_slow[2] && ma_fast[1]>ma_slow[1])
     {
      //--- Close all 'SELL' ...
      for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
         if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
            if(m_position.Symbol()==Symbol() && m_position.Magic()==InpMagic)
               if(m_position.PositionType()==POSITION_TYPE_SELL)
                  if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                     Print(__FILE__," ",__FUNCTION__,", ERROR: ","SELL PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
      //--- ... and open one 'BUY'
      m_trade.Buy(InpLots);
      //---
      return;
     }
   if(ma_fast[2]>ma_slow[2] && ma_fast[1]<ma_slow[1])
     {
      //--- Close all 'BUY' ...
      for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of current positions
         if(m_position.SelectByIndex(i)) // selects the position by index for further access to its properties
            if(m_position.Symbol()==Symbol() && m_position.Magic()==InpMagic)
               if(m_position.PositionType()==POSITION_TYPE_BUY)
                  if(!m_trade.PositionClose(m_position.Ticket())) // close a position by the specified m_symbol
                     Print(__FILE__," ",__FUNCTION__,", ERROR: ","BUY PositionClose ",m_position.Ticket(),", ",m_trade.ResultRetcodeDescription());
      //--- ...and open one 'SELL'
      m_trade.Sell(InpLots);
      //---
      return;
     }
  }
//+------------------------------------------------------------------+
//| 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))
     {
      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
      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);
  }
//+------------------------------------------------------------------+
Vladimir Karputov
Moderator
306178

Updated script - printout 'ENUM_TIMEFRAMES'

Timeframe in MT5 is a bit field. Printing out 'HEX' values gives an idea of how timeframes are encoded (See timeframe coding from H1 and higher).


Result:

  0: "PERIOD_CURRENT", int:     0, HEX:    0, "Current timeframe"
  1: "     PERIOD_M1", int:     1, HEX:    1, "1 minute"
  2: "     PERIOD_M2", int:     2, HEX:    2, "2 minutes"
  3: "     PERIOD_M3", int:     3, HEX:    3, "3 minutes"
  4: "     PERIOD_M4", int:     4, HEX:    4, "4 minutes"
  5: "     PERIOD_M5", int:     5, HEX:    5, "5 minutes"
  6: "     PERIOD_M6", int:     6, HEX:    6, "6 minutes"
  7: "    PERIOD_M10", int:    10, HEX:    A, "10 minutes"
  8: "    PERIOD_M12", int:    12, HEX:    C, "12 minutes"
  9: "    PERIOD_M15", int:    15, HEX:    F, "15 minutes"
 10: "    PERIOD_M20", int:    20, HEX:   14, "20 minutes"
 11: "    PERIOD_M30", int:    30, HEX:   1E, "30 minutes"
 12: "     PERIOD_H1", int: 16385, HEX: 4001, "1 hour"
 13: "     PERIOD_H2", int: 16386, HEX: 4002, "2 hours"
 14: "     PERIOD_H3", int: 16387, HEX: 4003, "3 hours"
 15: "     PERIOD_H4", int: 16388, HEX: 4004, "4 hours"
 16: "     PERIOD_H6", int: 16390, HEX: 4006, "6 hours"
 17: "     PERIOD_H8", int: 16392, HEX: 4008, "8 hours"
 18: "    PERIOD_H12", int: 16396, HEX: 400C, "12 hours"
 19: "     PERIOD_D1", int: 16408, HEX: 4018, "1 day"
 20: "     PERIOD_W1", int: 32769, HEX: 8001, "1 week"
 21: "    PERIOD_MN1", int: 49153, HEX: C001, "1 month"


24 -> HEX -> '18'

Files:
Vladimir Karputov
Moderator
306178

Simple Trailing

Code: 'Simple Trailing.mq5'

Simple trailing - works on every tick, works both for a losing position and for a profitable position. Works with the current character and only for positions with 'Magic number'

//+------------------------------------------------------------------+
//|                                              Simple Trailing.mq5 |
//|                                  Copyright 2022, MetaQuotes Ltd. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2022, MetaQuotes Ltd."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property description "'Trailing' - in Points (1.00055-1.00045=10 points)"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
//--- input parameters
input group             "Trailing"
input uint                 InpTrailingStop      = 250;         // Trailing Stop, min distance from price to SL
input uint                 InpTrailingStep      = 50;          // Trailing Step
input group             "Additional features"
input bool                 InpPrintLog          = true;        // Print log
input ulong                InpDeviation         = 10;          // Deviation
input ulong                InpMagic             = 75941265;    // Magic number
//---
double   m_trailing_stop            = 0.0;      // Trailing Stop              -> double
double   m_trailing_step            = 0.0;      // Trailing Step              -> double
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
//RefreshRates();
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   m_trailing_stop            = InpTrailingStop             * m_symbol.Point();
   m_trailing_step            = InpTrailingStep             * m_symbol.Point();
//---
   /*bool res=false;
   while(!res)
     {
      res=m_trade.Sell(0.03);
      if(!res)
         Sleep(1000*60*5);
     }*/
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   for(int i=PositionsTotal()-1; i>=0; i--) // returns the number of open positions
      if(m_position.SelectByIndex(i))
         if(m_position.Symbol()==m_symbol.Name() && m_position.Magic()==InpMagic)
           {
            double price_current = m_position.PriceCurrent();
            double price_open    = m_position.PriceOpen();
            double stop_loss     = m_position.StopLoss();
            double take_profit   = m_position.TakeProfit();
            //---
            if(m_position.PositionType()==POSITION_TYPE_BUY)
              {
               if(price_current-stop_loss>=m_trailing_stop+m_trailing_step)
                 {
                  if(!m_trade.PositionModify(m_position.Ticket(),m_symbol.NormalizePrice(price_current-m_trailing_stop),take_profit))
                     if(InpPrintLog)
                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","Modify BUY ",m_position.Ticket(),
                              " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),
                              ", description of result: ",m_trade.ResultRetcodeDescription());
                  continue;
                 }
              }
            else
              {
               if(stop_loss-price_current>=m_trailing_stop+m_trailing_step || stop_loss==0.0)
                 {
                  if(!m_trade.PositionModify(m_position.Ticket(),m_symbol.NormalizePrice(price_current+m_trailing_stop),take_profit))
                     if(InpPrintLog)
                        Print(__FILE__," ",__FUNCTION__,", ERROR: ","Modify SELL ",m_position.Ticket(),
                              " Position -> false. Result Retcode: ",m_trade.ResultRetcode(),
                              ", description of result: ",m_trade.ResultRetcodeDescription());
                 }
              }
           }
//---
   /*if(PositionsTotal()==0)
     {
      bool res=false;
      while(!res)
        {
         res=m_trade.Sell(0.03);
         if(!res)
            Sleep(1000*60*5);
        }
     }*/
  }
//+------------------------------------------------------------------+
Files:
Tobias Johannes Zimmer
1195
This thread deserves way more attention. Thanks for the good work.
Vladimir Karputov
Moderator
306178

Simple advisor. Always one position. The position is opened with Stop Loss and Take Profit. There are no defenses

Code: 'Stop Loss Take Profit EA.mq5'

//+------------------------------------------------------------------+
//|                                     Stop Loss Take Profit EA.mq5 |
//|                              Copyright © 2022, Vladimir Karputov |
//|                      https://www.mql5.com/en/users/barabashkakvn |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2022, Vladimir Karputov"
#property link      "https://www.mql5.com/en/users/barabashkakvn"
#property version   "1.000"
//---
#include <Trade\PositionInfo.mqh>
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
//---
CPositionInfo  m_position;                   // object of CPositionInfo class
CTrade         m_trade;                      // object of CTrade class
CSymbolInfo    m_symbol;                     // object of CSymbolInfo class
//--- input parameters
input group             "Trading settings"
input uint                 InpStopLoss             = 150;            // Stop Loss (SL) ('0' -> OFF)
input uint                 InpTakeProfit           = 460;            // Take Profit (TP) ('0' -> OFF)
input group             "Additional features"
input ulong                InpDeviation            = 10;             // Deviation, in Points (1.00045-1.00055=10 points)
input ulong                InpMagic                = 200;            // Magic number
//---
double   m_stop_loss                = 0.0;      // Stop Loss                  -> double
double   m_take_profit              = 0.0;      // Take Profit                -> double
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- forced initialization of variables
   m_stop_loss                = 0.0;      // Stop Loss                  -> double
   m_take_profit              = 0.0;      // Take Profit                -> double
//---
   ResetLastError();
   if(!m_symbol.Name(Symbol())) // sets symbol name
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: CSymbolInfo.Name");
      return(INIT_FAILED);
     }
   RefreshRates();
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(m_symbol.Name());
   m_trade.SetDeviationInPoints(InpDeviation);
//---
   m_stop_loss                = InpStopLoss                 * m_symbol.Point();
   m_take_profit              = InpTakeProfit               * m_symbol.Point();
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   if(!IsPositionExists())
     {
      if(!RefreshRates())
         return;
      if(MathRand()<32767/2)
        {
         //--- open BUY
         double sl=(m_stop_loss==0.0)?0.0:m_symbol.Ask()-m_stop_loss;
         double tp=(m_take_profit==0.0)?0.0:m_symbol.Ask()+m_take_profit;
         m_trade.Buy(m_symbol.LotsMin(),m_symbol.Name(),m_symbol.Ask(),sl,tp);
         //---
         return;
        }
      else
        {
         //--- open SELL
         double sl=(m_stop_loss==0.0)?0.0:m_symbol.Bid()+m_stop_loss;
         double tp=(m_take_profit==0.0)?0.0:m_symbol.Bid()-m_take_profit;
         m_trade.Sell(m_symbol.LotsMin(),m_symbol.Name(),m_symbol.Bid(),sl,tp);
        }
     }
  }
//+------------------------------------------------------------------+
//| Refreshes the symbol quotes data                                 |
//+------------------------------------------------------------------+
bool RefreshRates()
  {
//--- refresh rates
   if(!m_symbol.RefreshRates())
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","RefreshRates error");
      return(false);
     }
//--- protection against the return value of "zero"
   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)
     {
      Print(__FILE__," ",__FUNCTION__,", ERROR: ","Ask == 0.0 OR Bid == 0.0");
      return(false);
     }
//---
   return(true);
  }
//+------------------------------------------------------------------+
//| Is position exists                                               |
//+------------------------------------------------------------------+
bool IsPositionExists(void)
  {
   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()==m_symbol.Name() && m_position.Magic()==InpMagic)
            return(true);
//---
   return(false);
  }
//+------------------------------------------------------------------+