How to start with MQL5 - page 16

 
mmee55 :
So once bar size is reached, how can we get it to call on buy or sell?

For example like this:

//+------------------------------------------------------------------+
//|                                  Example Current candle size.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.002"
//---
#include <Trade\Trade.mqh>
//---
CTrade         m_trade;                      // object of CTrade class
//+------------------------------------------------------------------+
//| Enum Pips Or Points                                              |
//+------------------------------------------------------------------+
enum ENUM_PIPS_OR_POINTS
  {
   pips=0,     // Pips (1.00045-1.00055=1 pips)
   points=1,   // Points (1.00045-1.00055=10 points)
  };
//--- input parameters
input group             "Trading settings"
input ENUM_PIPS_OR_POINTS  InpPipsOrPoints   = pips;           // Pips Or Points:
input uint                 InpCandleSize     = 80;             // Candle: Size
input group             "Additional features"
input ulong    InpDeviation         = 10;          // Deviation
input ulong    InpMagic             = 200;         // Magic number
//---
double   m_candle_size           = 0.0;      // Candle: Size               -> double
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
   m_trade.SetDeviationInPoints(InpDeviation);
//--- tuning for 3 or 5 digits
   int digits_adjust=1;
   if(Digits()==3 || Digits()==5)
      digits_adjust=10;
   double m_adjusted_point=Point()*digits_adjust;
   if(InpPipsOrPoints==pips) // Pips (1.00045-1.00055=1 pips)
     {
      m_candle_size              = InpCandleSize               * m_adjusted_point;
     }
   else // Points (1.00045-1.00055=10 points)
     {
      m_candle_size              = InpCandleSize               * Point();
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| 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;
//--- signal search
   if(MathAbs(rates[0].open-rates[0].close)>=m_candle_size)
     {
      if(PositionsTotal()==0)
         m_trade.Buy(0.01);
      int d=0;
     }
  }
//+------------------------------------------------------------------+
 

What about if you already have the buy and sell function set.. I just need the code to call to it.. and be greater than the starting point. 

if(MathAbs(rates[0].open-rates[0].close)>=m_candle_size > start =buy)

Bad example, but could it work somehow similar to that? I need the end result.. 80points above start equals to buy or below equals sell

 
mmee55 :

What about if you already have the buy and sell function set.. I just need the code to call to it.. and be greater than the starting point. 

Bad example, but could it work somehow similar to that? I need the end result.. 80points above start equals to buy or below equals sell

I gave you a sample. Then everything depends on your imagination. Analyze ' rates ' and write any conditions. By analyzing the ' rates ' you can determine: the type of candlestick (bearish or bullish), the size of the candlestick.

 
mmee55:

What about if you already have the buy and sell function set.. I just need the code to call to it.. and be greater than the starting point. 

Bad example, but could it work somehow similar to that? I need the end result.. 80points above start equals to buy or below equals sell

Version 1.003:

//+------------------------------------------------------------------+
//| 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;
   if(PositionsTotal()>0)
      return;
   if(MathAbs(rates[0].open-rates[0].close)<m_candle_size)
      return;
//--- signal search
   if(rates[0].open<rates[0].close) // bearish
     {
      m_trade.Buy(0.01);
      int d=0;
     }
   else
      if(rates[0].open>rates[0].close) // bullish
        {
         m_trade.Sell(0.01);
         int d=0;
        }
  }
 

An example of using the Trend.mqh library is the CiSAR class

Code: CiSAR.mq5

//+------------------------------------------------------------------+
//|                                                        CiSAR.mq5 |
//|                         Copyright © 2017-2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2017-2021, Vladimir Karputov"
#property version   "1.001"
#property description "An example of using the Trend.mqh library is the CiSAR class"
#include <Arrays\ArrayObj.mqh>
#include <Indicators\Trend.mqh>
CArrayObj      m_array;                      // CArrayObj object
//--- input parameters
string SymbTrade[]=
  {
   "EURUSD","GBPUSD","USDJPY","USDCHF","NZDUSD","AUDUSD","EURJPY","USDCAD","EURCHF"/*,
   "EURGBP","GBPCHF","GBPJPY","EURAUD","AUDCAD","AUDCHF","AUDJPY","CADCHF","CADJPY",
   "CHFJPY","NZDCAD","NZDCHF","NZDJPY","GBPCAD","GBPAUD","GBPNZD","EURCAD","EURNZD",
   "AUDNZD"*/
  };
//---
string m_timeframe="";
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   m_timeframe=StringSubstr(EnumToString(Period()),7,-1);
//---
   CiSAR    *isar;
   for(int i=0; i<ArraySize(SymbTrade); i++)
     {
      isar=new CiSAR;
      if(isar==NULL)
        {
         delete isar;
         Print("Object create error");
         return(INIT_FAILED);
        }
      if(isar.Create(SymbTrade[i],Period(),0.02,0.2))
         m_array.Add(isar);
      else
        {
         delete isar;
         Print("SAR ",SymbTrade[i]," create error");
         return(INIT_FAILED);
        }
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   string text="";
   for(int i=0; i<m_array.Total(); i++)
     {
      CiSAR    *isar=m_array.At(i);
      isar.Refresh();
      text+=SymbTrade[i]+","+m_timeframe+" #0 : "+DoubleToString(isar.Main(0),Digits())+"\n";
     }
   Comment(text);
  }
//+------------------------------------------------------------------+


Result:

CiSAR

Files:
CiSAR.mq5  6 kb
 
Thank you
 

Example: how to get the value and color of the 'iAO' indicator in an advisor

Code: iAO Get Value and Color.mq5

When working in MQL5, remember the main rule: the indicator handle (in this example, it is the 'handle_iAO' variable) must be created ONLY ONCE and IT IS NECESSARY TO DO IN OnInit ()

The code below shows an example of how to get the indicator handle in the EA and how to access the indicator data in the EA. For example, I additionally placed an indicator on the chart so that you can visually compare the indicator readings and the data obtained in the EA.

Code:

//+------------------------------------------------------------------+
//|                                      iAO Get Value and Color.mq5 |
//|                              Copyright © 2021, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2021, Vladimir Karputov"
#property version   "1.001"
#property description "Example: how to get the value and color of the 'iAO' indicator in an advisor"
//--- input parameters
input group                "AO"
input ENUM_TIMEFRAMES      Inp_AO_period        = PERIOD_CURRENT;    // AO: timeframe
input group                "Additional features"
input bool                 InpPrintLog          = false;             // Print log
//---
int      handle_iAO;                            // variable for storing the handle of the iAO indicator
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//--- create handle of the indicator iAO
   handle_iAO=iAO(Symbol(),Inp_AO_period);
//--- if the handle is not created
   if(handle_iAO==INVALID_HANDLE)
     {
      //--- tell about the failure and output the error code
      PrintFormat("Failed to create handle of the iAO indicator for the symbol %s/%s, error code %d",
                  Symbol(),
                  EnumToString(Inp_AO_period),
                  GetLastError());
      //--- the indicator is stopped early
      return(INIT_FAILED);
     }
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   if(handle_iAO!=INVALID_HANDLE)
      IndicatorRelease(handle_iAO);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
//---
   double ao_buffer[],color_buffer[];
   ArraySetAsSeries(ao_buffer,true);
   ArraySetAsSeries(color_buffer,true);
   int start_pos=0,count=2;
   if(!iGetArray(handle_iAO,0,start_pos,count,ao_buffer) || !iGetArray(handle_iAO,1,start_pos,count,color_buffer))
      return;
//---
   string text="";
   int limit=(count>2)?2:count;
   for(int i=0; i<limit; i++)
     {
      text=text+
           " bar #"+IntegerToString(i)+": "+
           " AO "+DoubleToString(ao_buffer[i],Digits()+1)+
           " COLOR "+DoubleToString(color_buffer[i],0)+
           "\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:

iAO Get Value and Color

Pic. 1. iAO Get Value and Color

As you can see, we cannot get the indicator color in the form "clrRed or clrGreen". We can only access the color buffer and get the color index (in the picture above it is '1' and '0').

 
I've been trying to place market orders using the code from the book  Expert Advisor Programming for MetaTrader 5 by Andrew R Young and it gives me an error of unsupported filling type, please help
if(( strategy logic &&
            (SellPlaced == false && positionType != POSITION_TYPE_SELL))
           {
            request.action = TRADE_ACTION_DEAL;
            request.type = ORDER_TYPE_SELL;
            request.symbol = sym;
            request.volume = LotSize() + currentVolume;
            request.type_filling = ORDER_FILLING_FOK;
            request.price = SymbolInfoDouble(sym,SYMBOL_BID);
            request.sl = 0;
            request.tp = 0;
            request.deviation = 50;
            OrderSend(request,result);
            // Modify SL/TP
            if((result.retcode == TRADE_RETCODE_PLACED || result.retcode == TRADE_RETCODE_DONE)
               && (StopLoss > 0 || TakeProfit > 0))
              {
               request.action = TRADE_ACTION_SLTP;
               do
                  Sleep(100);
               while(PositionSelect(sym) == false);
               double positionOpenPrice = PositionGetDouble(POSITION_PRICE_OPEN);
               if(StopLoss > 0)
                  request.sl = positionOpenPrice + (StopLoss * _Point);
               if(TakeProfit > 0)
                  request.tp = positionOpenPrice - (TakeProfit * _Point);
               if(request.sl > 0 && request.tp > 0)
                  OrderSend(request,result);
               BuyPlaced = false;
               SellPlaced = true;
              }
           }

 
Ahmad861 :
I've been trying to place market orders using the code from the book   Expert Advisor Programming for MetaTrader 5 by Andrew R Young a nd it gives me an error of unsupported filling type, please help

Here's the simplest code:

//+------------------------------------------------------------------+
//|                                                    Open Sell.mq5 |
//|                              Copyright © 2018, Vladimir Karputov |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2018, Vladimir Karputov"
#property version   "1.000"
#property script_show_inputs
//---
#include <Trade\Trade.mqh>
CTrade         m_trade;                      // trading object
//--- input parameters
input ulong    InpMagic             = 200;         // Magic number
//+------------------------------------------------------------------+
//| Script program start function                                    |
//+------------------------------------------------------------------+
void OnStart()
  {
//---
   m_trade.SetExpertMagicNumber(InpMagic);
   m_trade.SetMarginMode();
   m_trade.SetTypeFillingBySymbol(Symbol());
   m_trade.Sell(1.0); // open Sell position, volume 1.0 lot
  }
//+------------------------------------------------------------------+
Files:
Open_Sell.mq5  2 kb
 
Vladimir Karputov:

Here's the simplest code:

The code you provided does not check if an order is already open or set stoploss and takeprofit