Calculating Lot Size Based On Risk Percentage

 

Hey,

I'm trying to calculate the lot size of a trade based on the percentage willing to risk for the trade.  Here is my code, but it is not working, please help!

The TRADE_LONG and TRADE_SHORT was obviously defined in the code 

double CalcLot(const string symbol,ENUM_TIMEFRAMES tf,int TradeDirection,double RiskPercentage,double SL)
{

   double lot_size;
   double ActBal;
   double PipVal;
   double pips;
   
   MqlTick latest_price;
   SymbolInfoTick(_Symbol,latest_price);

   ActBal = AccountInfoDouble(ACCOUNT_BALANCE);
   PipVal = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);

   if (TradeDirection == TRADE_LONG)
   {
   
      pips = (latest_price.bid - SL)/_Point;
      lot_size = (ActBal*(RiskPercentage/100)) / (pips*PipVal);    
      return(lot_size);
      
   
   }
   
   if (TradeDirection == TRADE_SHORT)
   {
   
      pips = (SL - latest_price.ask)/_Point;
      lot_size = (ActBal*(RiskPercentage/100)) / (pips*PipVal);
      
      return(lot_size);
     
   
   }
   
   
   
   
   
   return(0);
}
 

I know this thread is super old but in case anyone needs it, this would be my approach (kind of derived from yours):

double Calculate_Single_Risk(double Entry,double SL,double Percent) {
   double AccountBalance = AccountInfoDouble(ACCOUNT_BALANCE);
   double AmountToRisk = AccountBalance*Percent/100;
  
   double ValuePp = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
  
   double Difference = (Entry-SL)/_Point;
   if (Difference < 0) Difference *= -1;
   Difference = Difference*ValuePp;
  
   return (AmountToRisk/Difference);
  
}

This is not tested btw!

 

Nice function! But why not use MathAbs() instead of this?

if (Difference < 0) Difference *= -1;
Documentation on MQL5: Math Functions / MathAbs
  • www.mql5.com
Math Functions / MathAbs - Documentation on MQL5
 
if (TradeDirection == TRADE_LONG)
   {
   
      pips = (latest_price.bid - SL)/_Point;
if (TradeDirection == TRADE_LONG)
   {
   
      pips = (latest_price.ask - SL)/_Point;
if buy, use ask , is it?