Code of iSAR

 

Hello all,

i want to optimize the indicator iSAR.  Is it possible to change it. Where can I find the code of this indicator?

 

BR, mtsTrader 

 
mtsTrader:

Hello all,

i want to optimize the indicator iSAR.  Is it possible to change it. Where can I find the code of this indicator?

 

BR, mtsTrader 

Parabolic SAR
 
Thank you! I tried to change something in parabolicsar.mq5 but it has no effect on my trailing stop. Concretly I am unsing the parabolic SAR of this article:  https://www.mql5.com/en/articles/134 Now I want to optimize the calculation of the SAR. Is there an other function that I have change?
How to Create Your Own Trailing Stop
How to Create Your Own Trailing Stop
  • 2010.08.12
  • Dmitry Fedoseev
  • www.mql5.com
The basic rule of trader - let profit to grow, cut off losses! This article considers one of the basic techniques, allowing to follow this rule - moving the protective stop level (Stop loss level) after increasing position profit, i.e. - Trailing Stop level. You'll find the step by step procedure to create a class for trailing stop on SAR and NRTR indicators. Everyone will be able to insert this trailing stop into their experts or use it independently to control positions in their accounts.
 
mtsTrader:
Thank you! I tried to change something in parabolicsar.mq5 but it has no effect on my trailing stop. Concretly I am unsing the parabolic SAR of this article:  https://www.mql5.com/en/articles/134 Now I want to optimize the calculation of the SAR. Is there an other function that I have change?
You have to show the relevant code for such help.
 

ok, i will tray:

This is the main program:

//+------------------------------------------------------------------+
//|                                                  My_First_EA.mq5 |
//|                        Copyright 2010, MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2010, MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"

#include <Sample_TrailingStop.mqh> // include Trailing Stop class

//--- input parameters
input int      StopLoss=30;      // Stop Loss
input int      TakeProfit=100;   // Take Profit
input int      ADX_Period=8;     // ADX Period
input int      MA_Period=8;      // Moving Average Period
input int      EA_Magic=12345;   // EA Magic Number
input double   Adx_Min=22.0;     // Minimum ADX Value
input double   Lot=0.1;          // Lots to Trade
input double   TrailingSARStep    =  0.02; // Step of Parabolic
input double   TrailingSARMaximum =   0.2; // Maximum of Parabolic

//--- Other parameters
int adxHandle; // handle for our ADX indicator
int maHandle;  // handle for our Moving Average indicator
double plsDI[],minDI[],adxVal[]; // Dynamic arrays to hold the values of +DI, -DI and ADX values for each bars
double maVal[]; // Dynamic array to hold the values of Moving Average for each bars
double p_close; // Variable to store the close value of a bar
int STP, TKP;   // To be used for Stop Loss & Take Profit values

CParabolicStop Trailing; // create class instance

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
  
  //--- Initialize (set basic parameters)
   Trailing.Init(_Symbol,PERIOD_CURRENT,true,true,false); 
   //--- Set parameters of used trailing stop type
   if(!Trailing.SetParameters(TrailingSARStep,TrailingSARMaximum))
     { 
      Alert("trailing error");
      return(-1);
     }
   Trailing.StartTimer(); // Start timer
   Trailing.On();         // Turn On
   
//--- Get handle for ADX indicator
   adxHandle=iADX(NULL,0,ADX_Period);
//--- Get the handle for Moving Average indicator
   maHandle=iMA(_Symbol,_Period,MA_Period,0,MODE_EMA,PRICE_CLOSE);
//--- What if handle returns Invalid Handle
   if(adxHandle<0 || maHandle<0)
     {
      Alert("Error Creating Handles for indicators - error: ",GetLastError(),"!!");
      return(-1);
     }

//--- Let us handle currency pairs with 5 or 3 digit prices instead of 4
   STP = StopLoss;
   TKP = TakeProfit;
   if(_Digits==5 || _Digits==3)
     {
      STP = STP*10;
      TKP = TKP*10;
     }
   return(0);
  }
  
...

in the upper part the class Sample_TrailingStop.mqh is included:




//+------------------------------------------------------------------+
//|                                          Sample_TrailingStop.mqh |
//|                                        MetaQuotes Software Corp. |
//|                                              http://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "MetaQuotes Software Corp."
#property link      "http://www.mql5.com"
#property version   "1.00"


class CTrailingStop{
   protected:
      string m_symbol;              // ñèìâîë
      ENUM_TIMEFRAMES m_timeframe;  // òàéìôðåéì
      bool m_eachtick;              // ðàáîòàòü íà êàæäîì òèêå
      bool m_indicator;             // ïîêàçûâàòü èíäèêàòîð íà ãðàôèêå
      bool m_button;                // ïîêàçûâàòü êíîïêó âêëþ÷åíèÿ/âûêëþ÷åíèÿ
      int m_button_x;               // êîîðäèíàòà õ êíîïêè
      int m_button_y;               // êîîðäèíàòà ó êíîïêè
      color m_bgcolor;              // öâåò êíîïêè
      color m_txtcolor;             // öâåò íàäïèñè êíîïêè
      int m_shift;                  // ñìåùåíèå áàðà
      bool m_onoff;                 // âêëþ÷åíî/âûêëþ÷åíî
      int m_handle;                 // õýíäë èíäèêàòîðà

...

...

 class CParabolicStop: public CTrailingStop {
   protected:
      double pricebuf[1]; // çíà÷åíèå öåíû
      double indbuf[1];   // çíà÷åíèå èíäèêàòîðà
   public:  
      void  CParabolicStop(){
         m_typename="SAR"; // óñòàíîâêà èìåíè òèïà òðåéëèíã ñòîïà
      };
      //--- Ìåòîä óñòàíîâêè ïàðàìåòðîâ è çàãðóçêè èíäèêàòîðà
      bool SetParameters(double sarstep=0.02,double sarmaximum=0.2){
         //--- çàãðóçêà èíäèêàòîðà
         m_handle=iSAR(m_symbol,m_timeframe,sarstep,sarmaximum); 
            //--- åñëè íå óäàëîñü çàãðóçèòü èíäèêàòîð, ìåòîä âîçâðàùàåò false
            if(m_handle==-1){
               return(false); 
            }
            if(m_indicator){
               //--- ïðèñîåäèíåíèå èíäèêàòîðà ê ãðàôèêó
               ChartIndicatorAdd(0,0,m_handle); 
            }         
         return(true);
      }
      //--- Ìåòîä ïîëó÷åíèÿ çíà÷åíèé èíäèêàòîðà
      bool Refresh(){
            //--- åñëè íå óäàëîñü ñêîïèðîâàòü çíà÷åíèå â ìàññèâ, âîçâðàùàåòñÿ false
            if(CopyBuffer(m_handle,0,m_shift,1,indbuf)==-1){
               return(false); 
            } 
            //--- åñëè íå óäàëîñü ñêîïèðîâàòü çíà÷åíèå â ìàññèâ, âîçâðàùàåòñÿ false
            if(CopyClose(m_symbol,m_timeframe,m_shift,1,pricebuf)==-1){
               return(false); 
            }  
         return(true);                   
      }
      //--- Ìåòîä îïðåäåëåíèÿ òðåíäà
      int Trend()
     {
            //--- öåíà âûøå ëèíèè èíäèêàòîðà, òðåíä ââåðõ
            if(pricebuf[0]>indbuf[0]){ 
               return(1);
            }
            //--- öåíà íèæå ëèíèè èíäèêàòîðà, òðåíä âíèç
            if(pricebuf[0]<indbuf[0]){ 
               return(-1);
            }            
         return(0);
      } 
   
      //--- Ìåòîä îïðåäåëåíèÿ óðîâíÿ ñòîïëîññ äëÿ buy
      virtual double BuyStoploss(){
         return(indbuf[0]);
      };   
      //--- Ìåòîä îïðåäåëåíèÿ óðîâíÿ ñòîïëîññ äëÿ sell
      virtual double SellStoploss(){
         return(indbuf[0]);
      };            
};  
      


...
  

in the end you can find the function iSAR. In the file ParabolicSAR is in the end the calculation of the SAR ('//--- calculate SAR for tomorrow').



...
          //--- calculate SAR for tomorrow
         ExtSARBuffer[i+1]=ExtSARBuffer[i]+ExtAFBuffer[i]*(ExtEPBuffer[i]-ExtSARBuffer[i]);
         //--- check for SAR
         if(ExtSARBuffer[i+1]>low[i] || ExtSARBuffer[i+1]>low[i-1])
            ExtSARBuffer[i+1]=MathMin(low[i],low[i-1]);
        }
      else
        {
         //--- check for new Low
         if(low[i]<ExtEPBuffer[i-1] && i!=ExtLastRevPos)
           {
            ExtEPBuffer[i]=low[i];
            ExtAFBuffer[i]=ExtAFBuffer[i-1]+ExtSarStep;
            if(ExtAFBuffer[i]>ExtSarMaximum)
               ExtAFBuffer[i]=ExtSarMaximum;
           }
         else
           {
            //--- when we haven't reversed
            if(i!=ExtLastRevPos)
              {
               ExtAFBuffer[i]=ExtAFBuffer[i-1];
               ExtEPBuffer[i]=ExtEPBuffer[i-1];
              }
           }
         //--- calculate SAR for tomorrow
         ExtSARBuffer[i+1]=ExtSARBuffer[i]+ExtAFBuffer[i]*(ExtEPBuffer[i]-ExtSARBuffer[i]);
         //--- check for SAR
         if(ExtSARBuffer[i+1]<high[i] || ExtSARBuffer[i+1]<high[i-1])
            ExtSARBuffer[i+1]=MathMax(high[i],high[i-1]);
        }
     }
//---- OnCalculate done. Return new prev_calculated.
   return(rates_total);
  }
//+------------------------------------------------------------------+
//| Find highest price from start to current position                |
//+------------------------------------------------------------------+
double GetHigh(int nPosition,int nStartPeriod,const double &HiData[])
  {
//--- calculate
   double result=HiData[nStartPeriod];
   for(int i=nStartPeriod;i<=nPosition;i++) if(result<HiData[i]) result=HiData[i];
   return(result);
  }
//+------------------------------------------------------------------+
//| Find lowest price from start to current position                 |
//+------------------------------------------------------------------+
double GetLow(int nPosition,int nStartPeriod,const double &LoData[])
  {
//--- calculate
   double result=LoData[nStartPeriod];
   for(int i=nStartPeriod;i<=nPosition;i++) if(result>LoData[i]) result=LoData[i];
   return(result);
  }
//+------------------------------------------------------------------+


My question is how can I manipulate the calculation of the next SAR value? I tried to change something in this formula but it has no effect on the SAR shown in the diagram.Is it possible that the SAR is calculated at another place?

 
mtsTrader:

ok, i will tray:

This is the main program:

in the upper part the class Sample_TrailingStop.mqh is included:




in the end you can find the function iSAR. In the file ParabolicSAR is in the end the calculation of the SAR ('//--- calculate SAR for tomorrow').




My question is how can I manipulate the calculation of the next SAR value? I tried to change something in this formula but it has no effect on the SAR shown in the diagram.Is it possible that the SAR is calculated at another place?

Calculate SAR for tomorrow ? You can't calculate value for future.

How is indexed your ExtSARBuffer ? As a series or not ?

         //--- calculate SAR for tomorrow
         ExtSARBuffer[i+1]=ExtSARBuffer[i]+ExtAFBuffer[i]*(ExtEPBuffer[i]-ExtSARBuffer[i]);
         //--- check for SAR
         if(ExtSARBuffer[i+1]<high[i] || ExtSARBuffer[i+1]<high[i-1])
            ExtSARBuffer[i+1]=MathMax(high[i],high[i-1]);

Suppose it's indexed as a series, then i+1 is 1 candle in the past of i candle, and i-1 is in the future of candle i. That will never permit you to trade effectively. That can work on historical data, but not in actual trading.

 
angevoyageur:

Calculate SAR for tomorrow ? You can't calculate value for future.

How is indexed your ExtSARBuffer ? As a series or not ?

Suppose it's indexed as a series, then i+1 is 1 candle in the past of i candle, and i-1 is in the future of candle i. That will never permit you to trade effectively. That can work on historical data, but not in actual trading.

This is the Code of the ParabolicSAR. I have not changed anything. The question is where the Indicator iSAR in Sample_TrailingStop.mqh is calculated? Is it in ParabolicSAR or could it be that the indicator is calculated somewhere else?
 
mtsTrader:
This is the Code of the ParabolicSAR. I have not changed anything. The question is where the Indicator iSAR in Sample_TrailingStop.mqh is calculated? Is it in ParabolicSAR or could it be that the indicator is calculated somewhere else?

Thank you for porting to my attention this behaviour of Parabolic Sar.

Sample_TrailingStop.mqh use iSAR() function, which use the standard built-in Parabolic Sar of MT5, you can't change it.

If you want to customize the module, you need to use iCustom() with ParabolicSAR.mq5 custom indicator. Then you can customize it this last file where is calculated the parabolic sar.

 

Thank you! Now it's clear why it has no effect if I change something in ParabolicSAR. 

Now i will read the article of the custom indicator. Is it possible to copy and paste the ParabolicSAR or is not quite as simple? 

 
mtsTrader:

Thank you! Now it's clear why it has no effect if I change something in ParabolicSAR. 

Now i will read the article of the custom indicator. Is it possible to copy and paste the ParabolicSAR or is not quite as simple? 

Sorry but I don't understand your question, copy and paste where ?
Reason: