Trend_Catcher

Author: Dmitriy Epshteyn
Price Data Components
Series array that contains close prices for each bar
Indicators Used
Moving average indicatorParabolic Stop and Reverse system
0 Views
0 Downloads
0 Favorites
Trend_Catcher
ÿþ//+------------------------------------------------------------------+

//|                    Trend_Catcher_v2(barabashkakvn's edition).mq5 |

//|                                                 Dmitriy Epshteyn |

//|                                                  setkafx@mail.ru |

//+------------------------------------------------------------------+

#property copyright "Dmitriy Epshteyn"

#property link      "setkafx@mail.ru"

#property version   "1.001"

#include <Trade\PositionInfo.mqh>

#include <Trade\Trade.mqh>

#include <Trade\SymbolInfo.mqh>  

#include <Expert\Money\MoneyFixedRisk.mqh>

CPositionInfo  m_position;                   // trade position object

CTrade         m_trade;                      // trading object

CSymbolInfo    m_symbol;                     // symbol info object

CMoneyFixedRisk m_money;

//--- !25G0, 70 ?5@8>4 :>B>@>9 <>65B 1KBL >B:@KB0 B>;L:> >4=0 ?>78F8O,

//--- 0?@8<5@, 5A;8 2K1@0BL PERIOD_D1 - B> A>25B=8: <>65B >B:@KBL B>;L:> >4=C ?>78F8N =0 B5:CI59 4=52=>9 A25G5 

input ENUM_TIMEFRAMES Candle_TF=PERIOD_CURRENT; // !25G0, 70 ?5@8>4 :>B>@>9 <>65B 1KBL >B:@KB0 B>;L:> >4=0 ?>78F8O

input bool     Close_opposite_signal=true;   // 0:@K20BL ;8 ?>78F8N ?> >1@0B=><C A83=0;C

input bool     Monday            = true;     // ">@3>2K9 45=L >=545;L=8:

input bool     Tuesday           = true;     // ">@3>2K9 45=L B>@=8:

input bool     Wednesday         = true;     // ">@3>2K9 45=L !@540

input bool     Thursday          = true;     // ">@3>2K9 45=L '5B25@3

input bool     Friday            = true;     // ">@3>2K9 45=L OB=8F0

input bool     Reverse_Sig_Open  = false;    // "true" -> A83=0; 1C45B ?5@525@=CB, 2<5AB> 109 >B:@>5BAO A5;;, 2<5AB> A5;; >B:@>5BAO 109  

input int      PeriodMA_slow     = 200;      // 5@8>4 <54;5==>9 MA

input int      PeriodMA_fast     = 50;       // 5@8>4 ?5@2>9 1KAB@>9 MA 

input int      PeriodMA_fast2    = 25;       // 5@8>4 2B>@>9 1KAB@>9 MA

input double   Step_Sar          = 0.004;    // (03 87<5=5=8O F5=K Parabolic SAR

input double   Max_Sar           = 0.2;      // 0:A8<0;L=K9 H03 87<5=5=8O F5=K Parabolic SAR

input bool     Auto_SL           = true;     // :;NG8BL 02B><0B8G5A:89 AB>? ;>AA =0 B>G:5 8=48:0B>@0 Parabolic SAR

input bool     Auto_TP           = true;     // :;NG8BL 02B><0B8G5A:89 B59: ?@>D8B, :>B>@K9 @0AAG8BK205BAO ?> :>MDD8F85=BC

input ushort   minSL             = 10;       // A;8 @0AG5B=K9 AB>? ;>AA <5=LH5 minSL, ?>78F8N =5 >B:@K205<

input ushort   maxSL             = 200;      // A;8 @0AG5B=K9 AB>? ;>AA 1>;LH5 maxSL, ?>78F8N =5 >B:@K205<

input double   SL_koef           = 1;        // >MDD8F85=B =0 :>B>@K9 C<=>605BAO AB>? ;>AA (5A;8 1, B> AB>? ;>AA 1C45B =0 B>G:5 Parabolic SAR)

input double   TP_koef           = 1;        // >MDD8F85=B @0AG5B0 B59: ?@>D8B0 >B AB>? ;>AA0, ?@8<5@: 5A;8 TP_koef=2,B> MB> >7=0G05B, GB> B59: ?@>D8B 2 420 @070 1>;LH5 AB>? ;>AA0

input ushort   SL                = 20;       // !B>? ;>AA 2 ?C=:B0E, ?@8<5=O5BAO, 5A;8 Auto_SL = false

input ushort   TP                = 200;      // "59: ?@>D8B 2 ?C=:B0E, ?@8<5=O5BAO, 5A;8  Auto_TP = false

input double   Risk              = 2;        //  8A:, ?> :>B>@><C @0AAG8BK205BAO ;>B >@45@0, 7028A8B >B AB>? ;>AA0

input bool     Martin            = true;     // A;8 2:;NG5=, B> ?@8<5=O5BAO 0@B8=359;.

input double   Koef              = 2;        // A;8 ?>A;54=OO A45;:0 70:@KB0 A C1KB:><, B> @8A: A;54CNI59 A45;:8 1C45B C<=>65= =0 Koef

input ushort   Profit_Level      = 500;      // A;8 ?>78F8O 2KE>48B 2 ?;NA =0 Profit_Level ?C=:B>2

input ushort   SL_Plus           = 1;        // B> +SL_Plus 2KAB02;O5BAO 157C1KB>:

input ushort   Profit_Level2     = 500;      // A;8 ?>78F8O 2KE>48B 2 ?@>D8B =0 Profit_Level2 ?C=:B>2

input ushort   TrailingStop2     = 10;       // B> =0 @0AAB>O=88 TrailingStop2 ?C=:B>2 AB>? ;>AA 1C45B BO=CBLAO 70 F5=>9

input ulong    m_slippage        = 30;       // @>A:0;L7K20=85

input ulong    m_magic           = 1;        // =48284C0;L=K9 =><5@ 4;O ?>78F89, :>B>@K5 2KAB02;O5B A>25B=8:

//---

double         m_Full_Financial_Result=0;    // >;=K9 D8=0=A>2K9 @57C;LB0B ?>A;54=59 A45;:8

int            handle_iMA_slow;              // variable for storing the handle of the iMA indicator 

int            handle_iMA_fast;              // variable for storing the handle of the iMA indicator 

int            handle_iMA_fast2;             // variable for storing the handle of the iMA indicator 

int            handle_iSAR;                  // variable for storing the handle of the iSAR indicator 

ENUM_ACCOUNT_MARGIN_MODE m_margin_mode;

double         m_adjusted_point;             // point value adjusted for 3 or 5 points

//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

//SetMarginMode();

//if(!IsHedging())

//  {

//   Print("Hedging only!");

//   return(INIT_FAILED);

//  }

//---

   m_symbol.Name(Symbol());                  // sets symbol name

   if(!RefreshRates())

     {

      Print("Error RefreshRates. Bid=",DoubleToString(m_symbol.Bid(),Digits()),

            ", Ask=",DoubleToString(m_symbol.Ask(),Digits()));

      return(INIT_FAILED);

     }

   m_symbol.Refresh();

//---

   m_trade.SetExpertMagicNumber(m_magic);    // sets magic number

   m_trade.SetDeviationInPoints(m_slippage);

//--- tuning for 3 or 5 digits

   int digits_adjust=1;

   if(m_symbol.Digits()==3 || m_symbol.Digits()==5)

      digits_adjust=10;

   m_adjusted_point=m_symbol.Point()*digits_adjust;

//---

   if(!m_money.Init(GetPointer(m_symbol),Period(),m_symbol.Point()*digits_adjust))

      return(INIT_FAILED);

   m_money.Percent(Risk);                    // risk

//--- create handle of the indicator iMA

   handle_iMA_slow=iMA(m_symbol.Name(),Period(),PeriodMA_slow,0,MODE_EMA,PRICE_CLOSE);

//--- 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 for the symbol %s/%s, error code %d",

                  m_symbol.Name(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early 

      return(INIT_FAILED);

     }

//--- create handle of the indicator iMA

   handle_iMA_fast=iMA(m_symbol.Name(),Period(),PeriodMA_fast,0,MODE_EMA,PRICE_CLOSE);

//--- 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 for the symbol %s/%s, error code %d",

                  m_symbol.Name(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early 

      return(INIT_FAILED);

     }

//--- create handle of the indicator iMA

   handle_iMA_fast2=iMA(m_symbol.Name(),Period(),PeriodMA_fast2,0,MODE_EMA,PRICE_CLOSE);

//--- if the handle is not created 

   if(handle_iMA_fast2==INVALID_HANDLE)

     {

      //--- tell about the failure and output the error code 

      PrintFormat("Failed to create handle of the iMA indicator for the symbol %s/%s, error code %d",

                  m_symbol.Name(),

                  EnumToString(Period()),

                  GetLastError());

      //--- the indicator is stopped early 

      return(INIT_FAILED);

     }

//--- create handle of the indicator iSAR

   handle_iSAR=iSAR(Symbol(),Period(),Step_Sar,Max_Sar);

//--- 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)

  {

//---

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

//---

   int b=0,s=0,n=0;

   double bez     = m_symbol.NormalizePrice(Profit_Level*m_adjusted_point);

   double sl_plus = m_symbol.NormalizePrice(SL_Plus*m_adjusted_point);

   double bez2    = m_symbol.NormalizePrice(Profit_Level2*m_adjusted_point);

   double tr      = m_symbol.NormalizePrice(TrailingStop2*m_adjusted_point);



   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() && m_position.Magic()==m_magic)

           {

            if(!RefreshRates())

               continue;

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               b++;n++;

               if(m_symbol.Bid()-m_position.PriceOpen()>bez && 

                  m_position.StopLoss()<m_symbol.NormalizePrice(m_position.PriceOpen()+sl_plus) &&

                  m_position.StopLoss()!=m_symbol.NormalizePrice(m_position.PriceOpen()+sl_plus))

                 {

                  if(m_trade.PositionModify(m_position.Ticket(),

                     m_symbol.NormalizePrice(m_position.PriceOpen()+sl_plus),

                     m_position.TakeProfit()))

                     Print("57C1KB>: Buy",m_symbol.NormalizePrice(m_position.PriceOpen()+sl_plus));

                 }

               if(m_symbol.Bid()-m_position.PriceOpen()>bez2 &&

                  m_symbol.Bid()-m_position.StopLoss()>tr &&

                  m_position.StopLoss()!=m_symbol.NormalizePrice(m_symbol.Bid()-tr))

                 {

                  if(m_trade.PositionModify(m_position.Ticket(),

                     m_symbol.NormalizePrice(m_symbol.Bid()-tr),

                     m_position.TakeProfit()))

                     Print(""@59;8=3 Buy",m_symbol.NormalizePrice(m_symbol.Bid()-tr));

                 }

              }

            if(m_position.PositionType()==POSITION_TYPE_SELL)

              {

               s++;n++;

               if(m_position.PriceOpen()-m_symbol.Ask()>bez &&

                  m_position.StopLoss()>m_symbol.NormalizePrice(m_position.PriceOpen()-sl_plus) &&

                  m_position.StopLoss()!=m_symbol.NormalizePrice(m_position.PriceOpen()-sl_plus))

                 {

                  if(m_trade.PositionModify(m_position.Ticket(),

                     m_symbol.NormalizePrice(m_position.PriceOpen()-sl_plus),

                     m_position.TakeProfit()))

                     Print("57C1KB>: Sell",m_symbol.NormalizePrice(m_position.PriceOpen()-sl_plus));

                 }

               if(m_position.PriceOpen()-m_symbol.Ask()>bez2)

                  if(m_position.StopLoss()-m_symbol.Ask()>tr || m_position.StopLoss()==0)

                     if(m_position.StopLoss()!=m_symbol.NormalizePrice(m_symbol.Ask()+tr))

                       {

                        if(m_trade.PositionModify(m_position.Ticket(),

                           m_symbol.NormalizePrice(m_symbol.Ask()+tr),

                           m_position.TakeProfit()))

                           Print(""@59;8=3 Sell",m_symbol.NormalizePrice(m_symbol.Ask()+tr));

                       }

              }

           }



//--- ?>4AGQB :>;8GAB20 A45;>: 2=CB@8 B5:CI59 A25G8

   int      CountInCandel=0;

   datetime from_date=iTime(0,m_symbol.Name(),Candle_TF);

   datetime to_date=TimeCurrent();

//--- request trade history 

   HistorySelect(from_date-PeriodSeconds(Candle_TF),to_date+PeriodSeconds(Candle_TF));

//---

   uint     total=HistoryDealsTotal();

   ulong    ticket=0;

   string   symbol;

   long     magic;

   long     entry;

   datetime time;

//--- for all deals 

   for(uint i=0;i<total;i++)

     {

      //--- try to get deals ticket 

      if((ticket=HistoryDealGetTicket(i))>0)

        {

         //--- get deals properties 

         symbol=HistoryDealGetString(ticket,DEAL_SYMBOL);

         magic=HistoryDealGetInteger(ticket,DEAL_MAGIC);

         entry =HistoryDealGetInteger(ticket,DEAL_ENTRY);

         time  =(datetime)HistoryDealGetInteger(ticket,DEAL_TIME);

         //--- only for current symbol and magic

         if(symbol==m_symbol.Name() && magic==m_magic)

           {

            if(entry==DEAL_ENTRY_OUT)

              {

               if(time>=from_date)

                  CountInCandel++;

               if(time<from_date)

                  break;

              }

           }

        }



     }

//--- A83=0; 8 8=48:0B>@K

   double SAR0=iSARGet(0); //?> =5<C AB>? ;>AA @0AAG8BK205< // stop loss forward on it 

   double SAR1 = iSARGet(1);

   double SAR2 = iSARGet(2);

   double MA_slow = iMAGet(handle_iMA_slow,0);

   double MA_fast = iMAGet(handle_iMA_fast,0);

   double MA_fast2= iMAGet(handle_iMA_fast2,0);



   if(!RefreshRates())

      return;



   int sig=0;



   if(iClose(0)>SAR0 && iClose(1)<SAR1 && MA_fast>MA_slow && m_symbol.Ask()>MA_fast2)

      sig=1;

   if(iClose(0)<SAR0 && iClose(1)>SAR1 && MA_fast<MA_slow && m_symbol.Bid()<MA_fast2)

      sig=2;

//--- ?@545;5=85 B>@3>2>3> 4=O



   MqlDateTime str1;

   TimeToStruct(TimeCurrent(),str1);



   bool trade_day=false;

   if(str1.day_of_week==1 && Monday==true)

      trade_day=true;

   if(str1.day_of_week==2 && Tuesday==true)

      trade_day=true;

   if(str1.day_of_week==3 && Wednesday==true)

      trade_day=true;

   if(str1.day_of_week==4 && Thursday==true)

      trade_day=true;

   if(str1.day_of_week==5 && Friday==true)

      trade_day=true;

//--- AB>? ;>AA 8 B59: ?@>D8B

   double sl=0;

   double tp=0;

   double min_sl = m_symbol.NormalizePrice(minSL*m_adjusted_point);

   double max_sl = m_symbol.NormalizePrice(maxSL*m_adjusted_point);



   if(!Auto_SL)

      sl=m_symbol.NormalizePrice(SL*m_adjusted_point);

   if(!Auto_TP)

      tp=m_symbol.NormalizePrice(TP*m_adjusted_point);



   if(Auto_SL && m_symbol.Ask()<SAR0)

      sl=m_symbol.NormalizePrice((MathAbs(SAR0-m_symbol.Ask()))*SL_koef);

   if(Auto_SL && m_symbol.Bid()>SAR0)

      sl=m_symbol.NormalizePrice((MathAbs(m_symbol.Bid()-SAR0))*SL_koef);



   if(sl<min_sl)

      sl=min_sl;

   if(sl>max_sl)

      sl=max_sl;



   if(Auto_TP==true)

      tp=m_symbol.NormalizePrice(sl*TP_koef);

//--- ;>B @0AAG8BK205< ?> ?@>F5=BC >B 10;0=A0 AG5B0 8 ?@8<5=O5< <0@B8=359; 2 A>>B25BAB288 A =0AB@>9:0<8

//double Procent=AccountBalance()/100*Risk;

   if(m_Full_Financial_Result<0 && Martin)

      m_money.Percent(Risk*Koef);

   else

      m_money.Percent(Risk);

//Procent=NormalizeDouble(MathAbs(m_Full_Financial_Result)*Koef,Digits);



//--- ?>;CG05< @07<5@ ;>B0 4;O Buy ?@8 C:070==>< @8A:5

   double check_open_long_lot=m_money.CheckOpenLong(m_symbol.Ask(),sl);

   if(check_open_long_lot==0.0)

     {

      Print("CheckOpenLong == 0");

      return;

     }

//--- ?>;CG05< @07<5@ ;>B0 4;O Sell ?@8 C:070==>< @8A:5

   double check_open_short_lot=m_money.CheckOpenShort(m_symbol.Bid(),sl);

   if(check_open_long_lot==0.0)

     {

      Print("CheckOpenShort == 0");

      return;

     }



//--- >B:@K205< ?>78F8N

   if(!Reverse_Sig_Open && trade_day && n==0 && sig==1 && CountInCandel==0 && sl>min_sl)

     {

      //--- check volume before OrderSend to avoid "not enough money" error (CTrade)

      double chek_volume_lot=m_trade.CheckVolume(m_symbol.Name(),check_open_long_lot,m_symbol.Ask(),ORDER_TYPE_BUY);



      if(chek_volume_lot!=0.0)

         if(chek_volume_lot>=check_open_long_lot)

           {

            if(m_trade.Buy(check_open_long_lot,NULL,

               m_symbol.Ask(),

               m_symbol.NormalizePrice(m_symbol.Ask()-sl),

               m_symbol.NormalizePrice(m_symbol.Ask()+tp)))

               Print("&5=0 buy=",m_symbol.Ask(),", !B>? ;>AA=",m_symbol.Ask()-sl,", "59: ?@>D8B=",m_symbol.Ask()+tp);

           }

     }

   if(!Reverse_Sig_Open && trade_day && n==0 && sig==2 && CountInCandel==0 && sl>min_sl)

     {

      //--- check volume before OrderSend to avoid "not enough money" error (CTrade)

      double chek_volume_lot=m_trade.CheckVolume(m_symbol.Name(),check_open_short_lot,m_symbol.Bid(),ORDER_TYPE_SELL);



      if(chek_volume_lot!=0.0)

         if(chek_volume_lot>=check_open_short_lot)

           {

            if(m_trade.Sell(check_open_short_lot,NULL,

               m_symbol.Bid(),

               m_symbol.Bid()+sl,

               m_symbol.Bid()-tp))

               Print("&5=0 sell=",m_symbol.Bid(),", !B>? ;>AA=",m_symbol.Bid()+sl,", "59: ?@>D8B=",m_symbol.Bid()-tp);

           }

     }

   if(Reverse_Sig_Open && trade_day && n==0 && sig==2 && CountInCandel==0 && sl>min_sl)

     {

      //--- check volume before OrderSend to avoid "not enough money" error (CTrade)

      double chek_volume_lot=m_trade.CheckVolume(m_symbol.Name(),check_open_long_lot,m_symbol.Ask(),ORDER_TYPE_BUY);



      if(chek_volume_lot!=0.0)

         if(chek_volume_lot>=check_open_long_lot)

           {

            if(m_trade.Buy(check_open_long_lot,NULL,

               m_symbol.Ask(),

               m_symbol.Ask()-sl,

               m_symbol.Ask()+tp))

               Print("&5=0 buy=",m_symbol.Ask(),", !B>? ;>AA=",m_symbol.Ask()-sl,", "59: ?@>D8B=",m_symbol.Ask()+tp);

           }

     }

   if(Reverse_Sig_Open && trade_day && n==0 && sig==1 && CountInCandel==0 && sl>min_sl)

     {

      //--- check volume before OrderSend to avoid "not enough money" error (CTrade)

      double chek_volume_lot=m_trade.CheckVolume(m_symbol.Name(),check_open_short_lot,m_symbol.Bid(),ORDER_TYPE_SELL);



      if(chek_volume_lot!=0.0)

         if(chek_volume_lot>=check_open_short_lot)

           {

            if(m_trade.Sell(check_open_short_lot,NULL,

               m_symbol.Bid(),

               m_symbol.Bid()+sl,

               m_symbol.Bid()-tp))

               Print("&5=0 sell=",m_symbol.Bid(),", !B>? ;>AA=",m_symbol.Bid()+sl,", "59: ?@>D8B=",m_symbol.Bid()-tp);

           }

     }



//--- 70:@K205< ?>78F8N ?> >1@0B=><C A83=0;C

   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() && m_position.Magic()==m_magic)

           {

            if(m_position.PositionType()==POSITION_TYPE_BUY)

              {

               if(sig==2 && Close_opposite_signal && !Reverse_Sig_Open)

                  m_trade.PositionClose(m_position.Ticket());



               if(sig==1 && Close_opposite_signal && Reverse_Sig_Open)

                  m_trade.PositionClose(m_position.Ticket());

              }

            if(m_position.PositionType()==POSITION_TYPE_SELL)

              {

               if(sig==1 && Close_opposite_signal && !Reverse_Sig_Open)

                  m_trade.PositionClose(m_position.Ticket());



               if(sig==2 && Close_opposite_signal && Reverse_Sig_Open)

                  m_trade.PositionClose(m_position.Ticket());

              }

           }

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

void SetMarginMode(void)

  {

   m_margin_mode=(ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE);

  }

//+------------------------------------------------------------------+

//|                                                                  |

//+------------------------------------------------------------------+

bool IsHedging(void)

  {

   return(m_margin_mode==ACCOUNT_MARGIN_MODE_RETAIL_HEDGING);

  }

//+------------------------------------------------------------------+

//| Refreshes the symbol quotes data                                 |

//+------------------------------------------------------------------+

bool RefreshRates()

  {

//--- refresh rates

   if(!m_symbol.RefreshRates())

      return(false);

//--- protection against the return value of "zero"

   if(m_symbol.Ask()==0 || m_symbol.Bid()==0)

      return(false);

//---

   return(true);

  }

//+------------------------------------------------------------------+

//| Get value of buffers for the iMA                                 |

//+------------------------------------------------------------------+

double iMAGet(int handle_iMA,const int index)

  {

   double MA[1];

//--- reset error code 

   ResetLastError();

//--- fill a part of the iMABuffer array with values from the indicator buffer that has 0 index 

   if(CopyBuffer(handle_iMA,0,index,1,MA)<0)

     {

      //--- if the copying fails, tell the error code 

      PrintFormat("Failed to copy data from the iMA indicator, error code %d",GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated 

      return(0.0);

     }

   return(MA[0]);

  }

//+------------------------------------------------------------------+

//| Get value of buffers for the iSAR                                |

//+------------------------------------------------------------------+

double iSARGet(const int index)

  {

   double SAR[1];

//--- reset error code 

   ResetLastError();

//--- fill a part of the iSARBuffer array with values from the indicator buffer that has 0 index 

   if(CopyBuffer(handle_iSAR,0,index,1,SAR)<0)

     {

      //--- if the copying fails, tell the error code 

      PrintFormat("Failed to copy data from the iSAR indicator, error code %d",GetLastError());

      //--- quit with zero result - it means that the indicator is considered as not calculated 

      return(0.0);

     }

   return(SAR[0]);

  }

//+------------------------------------------------------------------+

//| TradeTransaction function                                        |

//+------------------------------------------------------------------+

void OnTradeTransaction(const MqlTradeTransaction &trans,

                        const MqlTradeRequest &request,

                        const MqlTradeResult &result)

  {

//--- get transaction type as enumeration value 

   ENUM_TRADE_TRANSACTION_TYPE type=trans.type;

//--- if transaction is result of addition of the transaction in history

   if(type==TRADE_TRANSACTION_DEAL_ADD)

     {

      long     deal_entry        =0;

      double   deal_commission   =0.0;

      double   deal_swap         =0.0;

      double   deal_profit       =0.0;

      string   deal_symbol       ="";

      long     deal_magic        =0;

      if(HistoryDealSelect(trans.deal))

        {

         deal_entry=HistoryDealGetInteger(trans.deal,DEAL_ENTRY);

         deal_commission=HistoryDealGetDouble(trans.deal,DEAL_COMMISSION);

         deal_swap=HistoryDealGetDouble(trans.deal,DEAL_SWAP);

         deal_profit=HistoryDealGetDouble(trans.deal,DEAL_PROFIT);

         deal_symbol=HistoryDealGetString(trans.deal,DEAL_SYMBOL);

         deal_magic=HistoryDealGetInteger(trans.deal,DEAL_MAGIC);

        }

      else

         return;

      if(deal_symbol==Symbol() && deal_magic==m_magic)

         if(deal_entry==DEAL_ENTRY_OUT)

           {

            m_Full_Financial_Result=deal_commission+deal_swap+deal_profit;

           }

     }

  }

//+------------------------------------------------------------------+ 

//| Get Time for specified bar index                                 | 

//+------------------------------------------------------------------+ 

datetime iTime(const int index,string symbol=NULL,ENUM_TIMEFRAMES timeframe=PERIOD_CURRENT)

  {

   if(symbol==NULL)

      symbol=Symbol();

   if(timeframe==0)

      timeframe=Period();

   datetime Time[1];

   datetime time=0;

   int copied=CopyTime(symbol,timeframe,index,1,Time);

   if(copied>0) time=Time[0];

   return(time);

  }

//+------------------------------------------------------------------+ 

//| Get Close for specified bar index                                | 

//+------------------------------------------------------------------+ 

double iClose(const int index,string symbol=NULL,ENUM_TIMEFRAMES timeframe=PERIOD_CURRENT)

  {

   if(symbol==NULL)

      symbol=Symbol();

   if(timeframe==0)

      timeframe=Period();

   double Close[1];

   double close=0;

   int copied=CopyClose(symbol,timeframe,index,1,Close);

   if(copied>0) close=Close[0];

   return(close);

  }

//+------------------------------------------------------------------+

Comments

Markdown supported. Formatting help

Markdown Formatting Guide

Element Markdown Syntax
Heading # H1
## H2
### H3
Bold **bold text**
Italic *italicized text*
Link [title](https://www.example.com)
Image ![alt text](image.jpg)
Code `code`
Code Block ```
code block
```
Quote > blockquote
Unordered List - Item 1
- Item 2
Ordered List 1. First item
2. Second item
Horizontal Rule ---