Maximum number of lots that can be opened MQL5.

 

Does anyone know how I can know how many lots I can open for example in a buy knowing the available capital?

double max_lots() {
   double lots = MathMin((AccountInfoDouble(ACCOUNT_BALANCE)*AccountInfoInteger(ACCOUNT_LEVERAGE)/ SymbolInfoDouble(Symbol(),SYMBOL_TRADE_CONTRACT_SIZE)),
   SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX));

        return lots;
}
 
emei:

Does anyone know how I can know how many lots I can open for example in a buy knowing the available capital?


You need to know the margin requirement for your symbol, best is to know the margin for 1.0 lots. Then you need to know your stop loss on your position and how much that will cost you on your account.


 Now you need to know the stop out level of your account in account currency.

Subtract both values from that stop out level, and stay above zero. That is the maximum lot size you can open without exceeding your accounts capabilities.


Edit:

Example: 1.0 lots on EURUSD has 1000$ margin required.

Your balance is at 10k$
Your stop out is at 7k$

You have a stop loss of 10$ per lot.

Now you can calculate your max supported lot size.
 

Didn't test or compile this:

double maxLots(const string        symbol,                 // symbol
               ENUM_ORDER_TYPE     trade_operation,     // operation
               double              price                // price
              )
  {
   double vol_step=SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
   double lots=SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
   while(FreeMarginCheck(symbol, trade_operation, lots, price)==true)
      lots+=vol_step;
   return lots-vol_step;
  }

double  FreeMarginCheck(
   const string        symbol,              // symbol
   ENUM_ORDER_TYPE     trade_operation,     // operation
   double              volume,              // volume
   double              price                // price
)
  {

   double freeMargin = AccountInfoDouble(ACCOUNT_MARGIN_FREE);
   double margin = 0.0;

   bool ret = OrderCalcMargin(trade_operation, symbol, volume, price, margin);


   if(freeMargin - margin <= 0.0 || ret != true)
      return (false);
   return true;
  }
 
Yashar Seyyedin #:

Didn't test or compile this:


This code is missing the stop loss. You just maximize by margin, but then you have no room for your position to move..
 
Dominik Egert #:
This code is missing the stop loss. You just maximize by margin, but then you have no room for your position to move..

I believe that is what @emei is asking. Anyway I agree with you that his question is missing SL.

 
Thank you very much!