calculating volume based on risk amount for gold

 

i use this code for calculating volume based on riskAmount and stop loss distance. this code works fine with forex trading but with gold it is not working properly. 

with gold the volume is always wrong it always give me 10 times the actual volume i need.

double calculateVolumne (double riskMoney, double stopLossDistance){
       double ticksize = SymbolInfoDouble (_Symbol, SYMBOL_TRADE_TICK_SIZE); 
       double tickvalue = SymbolInfoDouble (_Symbol, SYMBOL_TRADE_TICK_VALUE); 

       double moneyStep = (stopLossDistance / ticksize) * tickvalue;
       if (moneyStep == 0) return 0; 
       double lots = MathFloor(riskMoney/moneyStep);

      return lots;
}
 
In MQL5, you can just use the function OrderCalcProfit instead.
Documentation on MQL5: Trade Functions / OrderCalcProfit
Documentation on MQL5: Trade Functions / OrderCalcProfit
  • www.mql5.com
OrderCalcProfit - Trade Functions - MQL5 Reference - Reference on algorithmic/automated trading language for MetaTrader 5
 

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 ...
};
 
cool thx i will try that