Dynamic lot calculation function not working for CFDs

 

I'm successfully calculating lot size given a certain risk and certain stop loss

double getLot(double risk_per_trade_percent, int stopLossTicks)
{
   double actualBalance;
   actualBalance=AccountBalance();
      
   double tickVal=MarketInfo(Symbol(),MODE_TICKVALUE);
  
   double targetTickVal=(actualBalance*risk_per_trade_percent/100)/stopLossTicks;
   //Print("tickval: "+tickVal+" targetTickVal:"+targetTickVal);
   double lotVal=targetTickVal/ tickVal;
  
   lotVal=NormalizeDouble(lotVal,2);
   //Print("targetTickVal="+targetTickVal+" actualBalance="+actualBalance+" risk_per_trade_percent="+risk_per_trade_percent+" stopLossTicks="+stopLossTicks+" tickVal="+tickVal+" lotVal="+lotVal+" tick size: "+MarketInfo(Symbol(),MODE_TICKSIZE)+" lotval: "+lotVal+" MODE_LOTSIZE: "+MarketInfo(Symbol(),MODE_LOTSIZE));
   return lotVal;

}


risk per trade has to be passed like 10 ( 10% ) and stopLossTicks is the number of ticks as an integer value ( for example 100 ticks ).
It seems using this function brings to Error 131 on OrderSend function when trading on CFD ( i.e. DAX ).
I have found that "tickVal" has a bad value on CFDs, and brings to a bad result.
How can it be solved?
thank you
 

 

Hi please see: https://docs.mql4.com/marketinformation/marketinfo

MODE_PROFITCALCMODE

27

Profit calculation mode. 0 - Forex; 1 - CFD; 2 - Futures

MODE_MARGINCALCMODE

28

Margin calculation mode. 0 - Forex; 1 - CFD; 2 - Futures; 3 - CFD for indices

MarketInfo - Market Info - MQL4 Reference
MarketInfo - Market Info - MQL4 Reference
  • docs.mql4.com
MarketInfo - Market Info - MQL4 Reference
 
I haven't checked your code, but there is often a problem with non-forex symbols. Dax for example, TICK_VALUE will often be returned in Euros, not the account currency and this messes up the calculation.