PSAR Strategy
How To Trade using the automatic PSAR 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
endMathodLast updated