Trailing stop tutorial using ATR indicator
in

Trailing stop tutorial using ATR indicator

I. Main function

1. Using condition buy or sell base on price action.

2. Auto caculate lot size

3. Auto trailling stop by ATR.

4. Backtest result

Trailing stop tutorial using ATR indicator

Trailing stop tutorial using ATR indicator

II. Main function code

1. Trailling and count position function

//+------------------------------------------------------------------+
//|Count position and Trailling Functiom                              |
//+------------------------------------------------------------------+

void  count_position(int &count_buy, int &count_sell, double &_atr[])

  {
   
   count_buy=0; count_sell=0;
   int total_postion=PositionsTotal();
   double cp=0.0, op=0.0, sl=0.0,tp=0.0; ulong ticket=0.0;
   for ( int i=total_postion-1; i>=0; i--)
     {
     if(m_position.SelectByIndex(i))
      {
      if(m_position.Symbol()==_Symbol && m_position.Magic()== m_magicnumber)
       cp=m_position.PriceCurrent();op=m_position.PriceOpen();sl=m_position.StopLoss();tp=m_position.TakeProfit();ticket=m_position.Ticket();
       {       
       if(m_position.PositionType()== POSITION_TYPE_BUY)
        {
        count_buy++;
        double Traill= cp-Trailling*_atr[1];
        if(cp>sl+Trailling_Step*_atr[1] && Traill>sl)
         {
          trade.PositionModify(ticket,Traill,tp);
         }
        }
      
       if(m_position.PositionType()== POSITION_TYPE_SELL)
        {
         count_sell++;
         double Traill= cp+Trailling*_atr[1];
         if(cp<sl-Trailling_Step*_atr[1] && Traill<sl)
         
         {
          trade.PositionModify(ticket,Traill,tp);
         }
        }
         
       }
      }
     
     }
  }

2. caculate lot size

double calculate_lotsize(double sl, double price)   
 
 {
  double lots=0.,margin ;
  double lotstep= SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
 double ticksize = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
   double tickvalue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
  double balance= AccountInfoDouble(ACCOUNT_BALANCE);
  double point= SymbolInfoDouble(_Symbol,SYMBOL_POINT);
  //double  loss=MathRound((MathAbs(price-sl)/ ticksize) * ticksize );
  double  loss=MathAbs(price-sl)/point;  m_symbol.NormalizePrice(loss);
  double Risk= initial_risk*balance;
  if(loss!=0)
   {
    lots=MathAbs(Risk/loss);
    lots=MathFloor(lots/lotstep)*lotstep;
   }  
   if(OrderCalcMargin(ORDER_TYPE_BUY,_Symbol,lots,price,margin))
       {
         double free_margin=AccountInfoDouble(ACCOUNT_MARGIN_FREE);
         if(free_margin<0)
           {
            lots=0;
           }
         else if(free_margin<margin)
           {
            lots=lots*free_margin/margin;
            lots=MathFloor(lots/lotstep-1)*lotstep;
           }
        }
   lots=MathMax(lots,SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN));
   lots=MathMin(lots,SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX));
   return lots;
 }

3. Main tick function

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
if(OpenBar(Symbol()))
   {
 // Candle declaration
 double High[],Low[],open[],close[];
 ArraySetAsSeries(High,true);ArraySetAsSeries(Low,true);ArraySetAsSeries(close,true);ArraySetAsSeries(open,true);
 CopyHigh(Symbol(),timeframe,0,1000,High);
 CopyLow(Symbol(),timeframe,0,1000,Low);
 CopyOpen(_Symbol,timeframe,0,100,open);
 CopyClose(_Symbol,timeframe,0,100,close);
// Highest high and lowest low declaration
int highest= ArrayMaximum(High,HL_shift,HL_period);
int lowest= ArrayMinimum(Low,HL_shift,HL_period); 

double  HH= High[highest];
//Drawline(" Kháng Cự ", clrRed,HH);
double  LL= Low[lowest];
//Drawline(" hỗ trợ ", clrBlue,LL);

// Moving average declaration
CopyBuffer(Handle_MA,0,0,100,MA_Filter);
ArraySetAsSeries(MA_Filter,true);
 // Atr declaration
 ArraySetAsSeries(atr,true); CopyBuffer(hand_atr,0,0,50,atr);

//   Broker parameter                                               
    
double point = SymbolInfoDouble(_Symbol,SYMBOL_POINT);
double ask= SymbolInfoDouble(_Symbol,SYMBOL_ASK);
double bid= SymbolInfoDouble(_Symbol,SYMBOL_BID);
double spread=ask-bid;
double stoplevel= (int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
int freezerlevel= (int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_FREEZE_LEVEL); 

 
 // Count bjuy and count sell
 int count_buy=0; int count_sell=0;
 count_position(count_buy,count_sell,atr);

 // Main condition for buy and sell
 
    if(count_buy==0)
     {
       if(ask>(HH) && High[highest] > MA_Filter[highest]  )
        {
         double  entryprice= ask;
         double  sl        = LL;
         double  tp        = entryprice   +TP_factor*atr[1];
         double lotsize    = calculate_lotsize(sl,entryprice);
        if(  bid-sl>stoplevel && tp-bid>stoplevel&& CheckVolumeValue(lotsize) )
         {
         trade.Buy(lotsize,_Symbol,entryprice,sl,tp, " Buy Mr Tan ");
        
         }
       }
     }
    if(count_sell==0)
     {
    if(bid<(LL) && Low[lowest] < MA_Filter[lowest])
        {
         double  entryprice= bid;
         double  sl        = HH;
         double  tp        = entryprice   -TP_factor*atr[1];
         double lotsize    = calculate_lotsize(sl,entryprice);
         if(  sl-ask>stoplevel && ask-tp>stoplevel&& CheckVolumeValue(lotsize) )
         {
          trade.Sell(lotsize,_Symbol,entryprice,sl,tp, " Sell Mr Tan ");
         }
        }
     }
   
  }
 
  }

Share Your Valuable Opinions