Volatility Index Strategy
How To Trade using the automatic Volatility Index Strategy
Calculation
public class VXStrategy extends VolatilityIndex
//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)
super.onActivate(ctx);
if (getSettings().isEnterOnActivate())
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);
end
end
endMethod
public void onDeactivate(OrderContext ctx)
if (getSettings().isCloseOnDeactivate())
ctx.closeAtMarket();
end
super.onDeactivate(ctx);
endMethod
public void onBarClose(OrderContext ctx)
//The Volatility Index only works on closing prices
//so we need to work on completed bars only
DataSeries series = ctx.getDataContext().getDataSeries();
Instrument instr = ctx.getInstrument();
//Only do one trade per bar. Use the latest PSAR for the stop value in test cases (since the position has reversed)
if (series.getBoolean(TRADE_OCCURRED, false))
Double SAR = series.getDouble(Values.SAR);
if (SAR != null) setStopPrice((float)instr.round(SAR));
return;
end
Double SAR = series.getDouble(series.size()-2, Values.SAR);
Boolean isLong = series.getBoolean(series.size()-2, Values.LONG);
//These values shouldn't be null, but check just in case.
if (SAR == null || isLong == null) return;
float sar = (float)instr.round(SAR); //round this to a real value.
setStopPrice(sar);
int position = ctx.getPosition();
int tradeLots = getSettings().getTradeLots();
int qty = tradeLots *= instr.getDefaultQuantity() + Math.abs(position);
float close = series.getClose();
if (isLong AND close lessOrEqual sar)
ctx.sell(qty);
series.setBoolean(series.size()-1, TRADE_OCCURRED, true);
else if (!isLong AND close moreOrEqual sar)
ctx.buy(qty);
series.setBoolean(series.size()-1, TRADE_OCCURRED, true);
end
endMethodLast updated