Voir comment télécharger gratuitement des robots de trading
Retrouvez-nous sur Telegram !
Rejoignez notre page de fans
Un script intéressant ?
Poster un lien vers celui-ci -
laisser les autres l'évaluer
Vous avez aimé le script ? Essayez-le dans le terminal MetaTrader 5
Experts

Trailing stop tutorial using ATR indicator - expert pour MetaTrader 5

Vues:
1455
Note:
(3)
Publié:
2024.05.28 21:02
Besoin d'un robot ou d'un indicateur basé sur ce code ? Commandez-le sur Freelance Aller sur Freelance

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


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 ");
         }
        }
     }
   
  }
 
  }







Calculate Lot Size and Trailling Stop Calculate Lot Size and Trailling Stop

This is a lesson on how to: 1. calculate the lot size in each order corresponding to the percentage of balance loss. 2. Trailling and count position buy and sell. The condition buy or sell base on Price action and moving average filter

Delete all objects on chart (main window and sub window) with drag and drop Delete all objects on chart (main window and sub window) with drag and drop

It will delete all objects on the chart when the compiled executable is dragged onto the chart

Lesson 7 Price action Ket hop Volume VSA Lesson 7 Price action Ket hop Volume VSA

This is a lesson on trading using price action combined with volume.

Lesson 9 Buy sell stop Order Lesson 9 Buy sell stop Order

This is a lesson on buying or selling with pending orders stop