Need help with LotSize calculation (How to make it compatible with index!)

 

Hey, I have been trying to write one function that would calculate LotSize regardless of the instrument, but it seems that despite all my efforts the program seems to throw weird lot sizes anytime I use it for index - ES or NQ. It's working good for forex, gold and crude. I am yet to try it fully on crypto but each have a different contract size so I was thinking it would throw errors, but on BTC, ETH, LTC it seems to be working soundly.

Please, if anyone has the key to this lock, please please help me! Thanks!

NOTE: I have a very basic knowledge about coding and this is not my code and I have found it on a YT tutorial.

   double ReneLotsCalcu(double riskPercent, double entry, double sl){
   double tickSize   = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
   double tickValue  = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
   double lotStep    = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);

   if (tickSize == 0 || tickValue == 0 || lotStep == 0){
      Print(__FUNCTION__, " > ❌ Invalid market params: tickSize / tickValue / lotStep is zero");
      return 0;
   }

   double slDistance = MathAbs(entry - sl); // Handles both Buy & Sell
   if (slDistance <= tickSize){
      Print(__FUNCTION__, " > ❌ SL distance too small: %.5f", slDistance);
      return 0;
   }

   double riskMoney     = AccountInfoDouble(ACCOUNT_BALANCE) * riskPercent / 100.0;
   double moneyPerLot   = (slDistance / tickSize) * tickValue * lotStep;
   if (moneyPerLot == 0){
      Print(__FUNCTION__, " > ❌ MoneyPerLot evaluated to zero");
      return 0;
   }

   double lots = MathFloor(riskMoney / moneyPerLot) * lotStep;
   PrintFormat("Calculated LotSize: %.2f", lots);
   return lots;
}

Improperly formatted code edited by moderator. Please always use the CODE button (Alt-S) when inserting code.

Code button in editor

 
You may find this helpful.
How to calculate % lotSeize on Free Equity
How to calculate % lotSeize on Free Equity
  • 2025.07.08
  • Mattia Trabucchi
  • www.mql5.com
Hi everyone, here posting on a simple apparently stupid topic for the mayority of y'all but still struggling in it...
 
Yashar Seyyedin #:
You may find this helpful.

Thank you very much! After all these attempts, I pretty much believe that yours is the only appropriate solution! But, you think this adds substantial load if and when the account size is high, or it's fine?

 
Finversia J #:

Thank you very much! After all these attempts, I pretty much believe that yours is the only appropriate solution! But, you think this adds substantial load if and when the account size is high, or it's fine?

Good point. Maybe you can adjust starting volume from a larger amount depending on your specific balance.