To fix "divide by zero" you should analyse your code and look at every expression where a division occurs and think about whether the divisor will ever be zero or not.
So ask yourself, will "loss_for_lot_size_this_trade" ever be equal to 0?
Given that "loss_for_lot_size_this_trade = loss_for_1_lot * ordersize", then when either "loss_for_1_lot" or "ordersize" is zero it will fail.
So ask yourself, ...
- ... will "loss_for_1_lot" ever be equal to 0?
- ... will "ordersize" ever be equal to 0?
For "loss_for_1_lot", it will be when "SymbolInfoDouble(Symbol(),SYMBOL_TRADE_TICK_VALUE)" fails to obtain the data, for example when the symbol data has not yet been downloaded or a connection to the server is down.
For "ordersize" , it is unknown because the variable does not appear in your sample code, so it is probably a global variable which you will have to analyse.
So, how to your prevent this?
By detecting when these values are zero and stop calculating the rest, and take action to report to the log or do some kind of recovery.
By detecting when these values are zero and stop calculating the rest, and take action to report to the log or do some kind of recovery.
Yes exactly - I find using a ternary expression whenever there is a possible divide by 0 risk is a a convenient way to address this.
Example:
double SL_ticks = (loss_for_lot_size_this_trade != 0)? SL_in_Currency / loss_for_lot_size_this_trade : 0; if (SL_ticks == 0) //handle as needed
// Set minLot: double LotSize= ; // Your lot size. double minLot=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN); if(LotSize<minLot){LotSize=minLot); // Ensure your lot size isn't below the minLot.
Hope this helps.
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
This isn't really my function. I copied it from somewhere (possibly this forum) quite some time ago, and now I am struggling to understand how to fix it.
What it does:
I determine an amount in currency and I choose between StopLoss or TakeProfit. The function is supposed to return the exact price at which the order will gain or lose the specified amount in currency.
The problem is in this line which divides by zero:
double SL_ticks = SL_in_Currency / loss_for_lot_size_this_trade;
I am not sure how to fix it. Can someone please advise.