PSAR Strategy
The PSAR Strategy is based on the Parabolic SAR study by Welles Wilder. Signals generated in the study are used to trigger automatic trades. This automated trading strategy was created to demonstrate the mechanics of an automatic trade and is not intended for actual use. A more comprehensive strategy that may include multiple studies, margins and stops could be developed. This strategy definition is further expressed in the code given in the calculation below.
How To Trade using the automatic PSAR Strategy
Examine the details of the Parabolic SAR study (see link above). Use the strategy optimiser and back testing to aid in the selection of the acceleration factorsand step value. Open the strategy and configure the inputs for General, Display, Trading Options, Panel and Signals. Activate the strategy.
Calculation
public class PSARStrategy extends ParabolicSAR
//Key for a flag that indicates that a trade occurred on a given price bar
static Object TRADE_OCCURRED = "TRADE_OCCURRED";
public void onActivate(OrderContext ctx)
if (!getSettings().isEnterOnActivate()) return;
DataSeries series = ctx.getDataContext().getDataSeries();
Boolean isLong = series.getBoolean(series.size() - 2, Values.LONG);
if (isLong == null) return;
int tradeLots = getSettings().getTradeLots();
int qty = tradeLots *= ctx.getInstrument().getDefaultQuantity();
if (isLong) ctx.buy(qty);
else ctx.sell(qty);
endMethod
public void onBarUpdate(OrderContext ctx)
DataSeries series = ctx.getDataContext().getDataSeries();
Instrument instr = ctx.getInstrument();
double lastPrice = instr.getLastPrice();
//Only do one trade per bar. Use the latest PSAR for the stop value(since the position has reversed)
if (series.getBoolean(TRADE_OCCURRED, false))
setStopPrice((float)instr.round(series.getDouble(Values.PSAR)));
return;
end
//Base this on the previous bar, since the latest bar is not complete
Double PSAR = series.getDouble(series.size() - 2, Values.PSAR);
Boolean isLong = series.getBoolean(series.size() - 2, Values.LONG);
//These values shouldn't be null, but check just in case.
if (PSAR == null || isLong == null) {
return;
end
double psar = instr.round(PSAR); //round this to a real value.
setStopPrice((float)psar);
int position = ctx.getPosition();
int tradeLots = getSettings().getTradeLots();
int qty = tradeLots *= instr.getDefaultQuantity() + Math.abs(position);
if (isLong AND lastPrice lessOrEqual psar)
ctx.sell(qty);
series.setBoolean(TRADE_OCCURRED, true);
else if (!isLong AND lastPrice moreOrEqual psar)
ctx.buy(qty);
series.setBoolean(TRADE_OCCURRED, true);
end
endMathod
Last updated