Thursday, September 10, 2015

How to calculate what lot-size to use in your MT4 EA

Here is a function I've just written and tested, called CalculateLots. What it does is that it takes a risk percentage (i.e. 2%) and the stop-loss distance in pips (i.e. 30 pips) and it gives back what the lotsize shoud be so that when the trades hits its 30 pips stop-loss, it losses exactly 2% of the account balance.
Check it out.


double CalculateLots(double riskPercentage, double stopLoss)
  {

   double pipValue=MarketInfo(Symbol(),MODE_TICKVALUE);
   double point=MarketInfo(Symbol(),MODE_POINT);
   double pip=GetPip(Symbol());

   double StopLoss=TriggerDistance;

   double lots=(AccountBalance())*riskPercentage/100/(stopLoss*(pip/point)*pipValue);

   double lotStep=MarketInfo(Symbol(),MODE_LOTSTEP);
   int digits = 0;
   if(lotStep<= 0.01)
      digits=2;
   else if(lotStep<=0.1)
                    digits=1;
   lots=NormalizeDouble(lots,digits);

   double minLots=MarketInfo(Symbol(),MODE_MINLOT);
   if(lots<minLots)
      lots=minLots;

   double maxLots=MarketInfo(Symbol(),MODE_MAXLOT);
   if(lots>maxLots)
      lots=maxLots;

   return (lots);
  }

Moreover, if you do not give a cr@p about what your balance is and how much you're losing relative to that, but you only want to ensure that the SL does not exceed a certain amount of dollars, let's say $50, all you need to do differently is to replace AccountBalance()*riskPercentage/100 with your variable or constant that stores this USD amount.
Good luck learning Metatrader programming, share your ideas and questions below. Thanks!

No comments:

Post a Comment