Volatility Index Strategy
The Volatility Index strategy is based on the Volatility Index 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 Volatility Index Strategy
Examine the details of the Volatility Index 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 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
endMethod
Last updated