Unfortunately, that formula is incorrect. If you take a 3 lot USD/JPY position with $1,000 balance, 1:500 leverage, 50% stop-out level, and 105.331 current USD/JPY ask, you will get stopped out before you reach your 40 pips stop loss.
Because with 3 lots, 40 pips loss on USD/JPY is $1,139.27 - you would have to get into negative equity on your $1,000 account balance.
The correct formula to determine the maximum position size for USD/JPY based on initial balance, SL, stop-out level, leverage, and the USD/JPY Ask rate:
Code:
Size = Balance * Leverage / (100,000 * StopOut + Pip_Value * SL * Leverage)
In your case:
Code:
Size = $1,000 * 500 / (100,000 * 0.5 + $9.49 * 40 * 500) = 500,000 / (50,000 + 189,800) = 2.085 lots
Here is how to arrive at this formula:
Code:
StopOut = Equity / Used_Margin
Equity = Balance - Loss
Loss = Size * SL * Pip_Value
Pip_Value = 1,000 / USDJPY_Ask = 1,000 / 105.331 = $9.49
Please note, that the USD/JPY Ask rate to use here is the one that will be at the time of the position closing (i.e., your stop-loss level).
Code:
SL = 40 pips
Used_Margin = Size * 100,000 / Leverage
StopOut = 50% = 0.5
Leverage = 500
Balance = $1,000
Please let me know if you still need help figuring this out.