WiseTrader Toolbox

VariablePeriodRef

Background

AmiBroker's built-in Ref function reads a value from a fixed number of bars away — a negative offset looks back in time, a positive offset looks forward. It is the standard way to compare the current bar with an earlier (or later) one, for example Ref( Close, -1 ) for yesterday's close.

VariablePeriodRef does the same thing but lets the offset change on every bar. The value of the periods array at each bar is used as the shift, so you can reference a different distance back (or forward) depending on cycle length, volatility or any rule you encode. As with Ref, a negative value looks back and a positive value looks forward; bars whose shift would fall outside the available data are left empty.

Included formula

The toolbox ships a ready-made Adaptive Smoothed Momentum indicator built on this function, so you can use it without writing any code. In AmiBroker open the Charts window, expand the WiseTraderToolbox group and drag Adaptive Smoothed Momentum onto a chart.

It plots an adaptive momentum line in its own pane below price, with an optional signal line. Momentum compares price with an earlier bar, and this function is what lets that look-back distance vary: the Adaptor you pick produces the per-bar shift, and an optional Smoother cleans up the input first. The adaptor's bounds, the smoothing and the colours are all set from the indicator's parameters.

The exported function

If you would rather build your own formula, the toolbox exports the calculation as a single AFL function you can call directly — it is the engine inside that indicator.

VariablePeriodRef(Price, Periods)
ParameterDescription
Price The array to read shifted values from.
Periods An array (or value) giving the bar shift to apply at each bar. Negative values look back, positive values look forward.

Usage

// Look back a different number of bars depending on the dominant cycle
periods = -DominantCycle( Close );
priorClose = VariablePeriodRef( Close, periods );
Plot( Close, "Price", colorDefault, styleBar );
Plot( priorClose, "Cycle-ago Close", colorRed );