not enough money but volume is set correct

 

i am getting this error during verification 

 2020.02.03 00:02:30   current account state: Balance: 1.00, Credit: 0.00, Commission: 0.00, Accumulated: 0.00, Assets: 0.00, Liabilities: 0.00, Equity 1.00, Margin: 0.00, FreeMargin: 1.00
 2020.02.03 00:02:30   calculated account state: Assets: 0.00, Liabilities: 0.00, Equity 1.00, Margin: 221.93, FreeMargin: -220.93
 2020.02.03 00:02:30   not enough money [instant buy 0.2 EURUSD at 1.10963 sl: 1.09507 tp: 1.19107]
 


but my EA has a check lot function  in it, but maybe i wrote something wrong  since i am still new to coding. 

 // calculate lots
 bool CalculateLots(double slDistance, double &lots) {
 
   lots = 0.0;
   if(LotMode==LOT_MODE_FIXED) {
      lots = Lot_Size;
   }
   else{
      double tickSize = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
      double tickValue = SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_VALUE);
      double volumeStep = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
   
      double riskMoney  = LotMode==LOT_MODE_MONEY ? Lot_Size : AccountInfoDouble(ACCOUNT_EQUITY) * Lot_Size * 
0.01 ;
      double moneyVolumeStep = (slDis / tickSize) * tickValue * volumeStep;
      
      lots = MathFloor(riskMoney/moneyVolumeStep) * volumeStep;

   }
 
   // check calculated lots
      if(!CheckLots(lots)){return false;}
 
 
 return true;
 }  

// check lots for min,max and step
bool CheckLots(double &lots){

   double min = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
   double max = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
   double step = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
   double limit = SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_LIMIT);
   if(lots<min){
      Print("Lot size will be set to min allowed value of volume");
      lots = min;
      return true;
   }
   if(lots>max){
      Print("Lots size is larger then max allowed volume. lots: ",lots," max:",max);
      return false;
   }
   
   lots = (int)MathFloor(lots/step) * step;

   return true;
}


and in the order section  i have it written like this.   (buy position below) 

// check for buy positions
   if (cntBuy==0 && bufferRSI[1]>=(100-RSI_Level) && bufferRSI[0]<(100-RSI_Level) && currentTick.ask>bufferMA[0]){
     
     if(Close_by_Opposite){if(!ClosePositions(2)){return;}}
     double sl = Stop_LOSS==0 ? 0 : NormalizeDouble((currentTick.bid - Stop_LOSS * _Point), _Digits);
     double tp = TAKE_PROFIT==0 ? 0 : NormalizeDouble ((currentTick.bid + TAKE_PROFIT * _Point),_Digits);
     if(!NormalizePrice(sl)){return;}
     if(!NormalizePrice(tp)){return;} 
     double lots;
     if(!CalculateLots(currentTick.bid-sl,lots)){return;}
     
     
     trade.PositionOpen(_Symbol,ORDER_TYPE_BUY,lots,currentTick.ask,sl,tp," ");
      
   }


so i am a little confused  about why it says i don't have enough money..  it referenced me to the  mql5 code to add to my EA so in my "other" section of the code near the bottom i added it. : or did i add this to the wrong section does it need to be in a specific spot. 

bool CheckMoneyForTrade(string symb,double lots,ENUM_ORDER_TYPE type)
  {
//--- Getting the opening price
   MqlTick mqltick;
   SymbolInfoTick(symb,mqltick);
   double price=currentTick.ask;
   if(type==ORDER_TYPE_SELL)
      price=currentTick.bid;
//--- values of the required and free margin
   double margin,free_margin=AccountInfoDouble(ACCOUNT_MARGIN_FREE);
   //--- call of the checking function
   if(!OrderCalcMargin(type,symb,lots,price,margin))
     {
      //--- something went wrong, report and return false
      Print("Error in ",__FUNCTION__," code=",GetLastError());
      return(false);
     }
   //--- if there are insufficient funds to perform the operation
   if(margin>free_margin)
     {
      //--- report the error and return false
      Print("Not enough money for ",EnumToString(type)," ",lots," ",symb," Error code=",GetLastError());
      return(false);
     }
//--- checking successful
   return(true);
  }
Documentation on MQL5: Integration / MetaTrader for Python / order_calc_margin
Documentation on MQL5: Integration / MetaTrader for Python / order_calc_margin
  • www.mql5.com
order_calc_margin - MetaTrader for Python - Integration - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 

I had this problem at one point.  Your answer is in the error message.


Margin: 221.93, FreeMargin: -220.93

You only have a balance of 1.00   but the size of your lot needs a free margin of 221.93.   So you don't have enough money.

Regardless of your stoploss amount your broker will require you have a larger amount of money in your balance to cover the trade.   You need to calculate the free margin requirement when you calculate the lot size and then check to make sure you BALANCE has enough money to cover the MARGIN requirement.  Each broker offers different leverage and therefore requires a different margin amount. 

Hope this helps,

Chris

 
Chris Pinter #:

I had this problem at one point.  Your answer is in the error message.


You only have a balance of 1.00   but the size of your lot needs a free margin of 221.93.   So you don't have enough money.

Regardless of your stoploss amount your broker will require you have a larger amount of money in your balance to cover the trade.   You need to calculate the free margin requirement when you calculate the lot size and then check to make sure you BALANCE has enough money to cover the MARGIN requirement.  Each broker offers different leverage and therefore requires a different margin amount. 

Hope this helps,

Chris

this was the verification process to post my ea on mql5 so idk what to change 

 
Chris Pinter #:

I had this problem at one point.  Your answer is in the error message.


You only have a balance of 1.00   but the size of your lot needs a free margin of 221.93.   So you don't have enough money.

Regardless of your stoploss amount your broker will require you have a larger amount of money in your balance to cover the trade.   You need to calculate the free margin requirement when you calculate the lot size and then check to make sure you BALANCE has enough money to cover the MARGIN requirement.  Each broker offers different leverage and therefore requires a different margin amount. 

Hope this helps,

Chris



THIS  is what i wrote to try and change it but still same results 

// calculate lots
bool CalculateLots(double slDistance, double &lots) {
   double free_margin = AccountFreeMargin();
   double stop_loss = slDistance;
   double price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double margin_requirement = 0.01;
   
   lots = 0.0;
   if (InpLotMode == LOT_MODE_FIXED) {
      lots = Lot_Size;
   } else if (InpLotMode == LOT_MODE_MONEY) {
      lots = Lot_Size / (stop_loss * price * margin_requirement);
   } else {
      double riskMoney = AccountInfoDouble(ACCOUNT_EQUITY) * Lot_Size * 0.01;
      lots = riskMoney / (stop_loss * price * margin_requirement);
   }

   lots = NormalizeDouble(lots, SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));

   if (!CheckLots(lots)) {
      return false;
   }

   // Ensure that the calculated lot size is not greater than the available free margin
   if (lots * stop_loss * price * margin_requirement > free_margin) {
      lots = free_margin / (stop_loss * price * margin_requirement);
      lots = NormalizeDouble(lots, SymbolInfoInteger(_Symbol, SYMBOL_DIGITS));
   }

   return true;
}
 

To calculate the correct volume for your trade, you should ...

  1. Use the OrderCalcProfit to first obtain the correct volume based on your stop-loss size and percentage risk.
  2. Adjust the volume, based on the contract specifications
  3. Use the OrderCalcMargin to verify that the volume is within the margin limits and requirements, and if not, then either reduce the volume or abort the trade.
  4. And finally, before placing the order, use OrderCheck to make sure everything is in valid.

Forum on trading, automated trading systems and testing trading strategies

SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE) sometimes zero

Fernando Carreiro, 2022.08.23 17:41

You can! These are the steps I take. I supply the function with a lot size equal to the “Max Lot Size” allowed for the symbol in question, then calculate the ratio needed to achieve the fractional risk that I wish to apply, to get the correct volume for the order. I then align that with the “Lot Step” and finally check it against both the maximum and minimum allowed lots for the symbol.

The reason I use the “maximum” lots instead of just “1.0” lots as a reference value is because there is no guarantee that the value of 1.0 is within the minimum and maximum values allowed. Given that using 1.0, or the maximum, gives equivalent results anyway (by using the ratio method), I choose to use the “max lots” as the reference point which also offers the most precision for the calculation.

Something like this ...

// This code will not compile. It is only a example reference

if( OrderCalcProfit( eOrderType, _Symbol, dbLotsMax, dbPriceOpen, dbPriceStopLoss, dbProfit ) )
{
   dbOrderLots = fmin( fmax( round( dbRiskMax * dbLotsMax / ( -dbProfit * dbLotsStep ) )
               * dbLotsStep, dbLotsMin ), dbLotsMax ); 
      
   // the rest of the code ...
};

Forum on trading, automated trading systems and testing trading strategies

Market Registration of EA Unable to Validate

Fernando Carreiro, 2022.08.30 14:20

For your screenshot with an Error 131 and it also has a link on "How to fix it". So follow up on it and fix your EA accordingly.

In regards to volume, you have to check the contract specification of the symbol and limit your volume to the minimum, maximum and step that is allowed for the symbol.

// Variables for symbol volume conditions
   double
      dbLotsMinimum = SymbolInfoDouble( _Symbol, SYMBOL_VOLUME_MIN  ),
      dbLotsMaximum = SymbolInfoDouble( _Symbol, SYMBOL_VOLUME_MAX  ),
      dbLotsStep    = SymbolInfoDouble( _Symbol, SYMBOL_VOLUME_STEP );
       
// Adjust volume for allowable conditions
   dbLots = fmin(  dbLotsMaximum,                           // Prevent too greater volume
            fmax(  dbLotsMinimum,                           // Prevent too smaller volume
            round( dbLots / dbLotsStep ) * dbLotsStep ) );  // Align to step value

Forum on trading, automated trading systems and testing trading strategies

Complete formula for calculating forex pip value for XAUUSD with account funded in euros

Fernando Carreiro, 2022.08.29 15:43

One more thing that should be considered by the OP or those following this thread ...

After you determine your volume (lots) for your risk amount, you should then check that against the free margin, useing the OrderCalcMargin (MQL5) or order_calc_margin (Python), to verify that the amount of margin that will be required is available in your free margin.

In fact, make sure that the required margin plus the risk is not greater than your free margin and that it will not cause a margin call or stop out.

I personally set a margin % limit and reduce the lot size if required. For example, I set a maximum % margin of 5-10% and use the OrderCalcMargin to adjust the volume to reduce the volume should the margin be higher than my limit.

The reason I set it to 5-10% is because I have to account for multiple positions in the market if I am trading on multiple symbols at the same time. If I were to allow a maximum margin on my balance, then I would not have any free margin left to trade on other symbols.

 
Fernando Carreiro #:

To calculate the correct volume for your trade, you should ...

  1. Use the OrderCalcProfit to first obtain the correct volume based on your stop-loss size and percentage risk.
  2. Adjust the volume, based on the contract specifications
  3. Use the OrderCalcMargin to verify that the volume is within the margin limits and requirements, and if not, then either reduce the volume or abort the trade.
  4. And finally, before placing the order, use OrderCheck to make sure everything is in valid.



thanks for the post but i think i am confused at how to implement it 

 
Ricks creations #thanks for the post but i think i am confused at how to implement it 

In response, all I can say is that if you are still not able to figure it out with the information above, then maybe consider hiring someone to code it for you.

 
Fernando Carreiro #:

In response, all I can say is that if you are still not able to figure it out with the information above, then maybe consider hiring someone to code it for you.

Fernando has provided you all the information you should need.   Take a look at the documentation for the functions he pointed out and Print the lot size.  You will see you need more in your account.

You can also contact your broker .  They will be able to explain the problem you are attempting to solve. 

If these two ideas dont work.....Hire a programmer.  Post the problem on the freelance section and get some help.


Chris

Reason: