JForex Example: Automatic position sizing
Proper position sizing is an integral part of risk management. It can be one of the easiest thing to do too. For example, I typically size my trading position based on the following factors:
- Amount of capital willing to put at risk.
- Stop price level.
- Volatility of the instrument.
The following JForex code calculates a lot size based on these three factors. It is part of my Dukascopy JForex July strategy (complete source code to the strategy is available via that link).
private double getLot(Instrument instrument) throws JFException
{
double riskAmt;
double lotSize = 0;
riskAmt = this.acctEquity * (this.riskPct / 100d); // CCYUSD only
lotSize = riskAmt / (this.atr[instrument.ordinal()] * this.atrFactor);
lotSize /= 1000000d; // in millions
return roundLot(lotSize);
}
Referring to line 237, riskAmt is the amount of capital to put at risk for a trade (#1). Line 238 calculates lotSize, which is the position size that we want. The denominator in that division is the distance of the stop in pips. The strategy uses a multiple of ATR to set the stop loss. Nothing fancy here.
Lines 240–241 are to set the lotSize value according to the JForex API specification. In which the lot amount is in millions and in steps of a thousand units, or 0.001 step size.
As I’ve noted in the code, the caveat to this implementation is that the secondary currency of the instrument and your account currency needs to be in U.S. dollar. However, it’s just a matter of conversion to extend this method for other currencies.
Update: I expanded on this functionality in the JFUtil open source project.
Related posts:

Hi, Paul. I don’t understand this code. Is ‘price’ the stop price? It does not seem to be used. Why would the calculation of ‘riskAmt’ require US dollars?
Brian, you’re right, “price” parameter is useless. I have removed it in the published code. This method only works for USD as secondary in a USD account because otherwise you’d have to convert the value to the corresponding currency. For example, if the instrument is GBP/JPY. Then riskAmt would be in Yen. Then you’ll need to convert that to USD by dividing the value with a USD/JPY exchange rate.
I have since updated my code to be more robust. Perhaps I’ll release them when I have time.