Download MetaTrader 5

Calculating Lot Size Based On Risk Percentage

To add comments, please log in or register
Franco
374
Franco  

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);
}
Operator_Jon
3
Operator_Jon  

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!

Andriy Moraru
1260
Andriy Moraru  

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
HongDi s& t development co.,ltd.
1604
hongbin fei  
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?
To add comments, please log in or register