Let us walk through a complete example — an EMA crossover strategy that goes from plain-language idea to runnable code. The thesis is simple: when short-term momentum turns bullish (fast EMA crosses above slow EMA), go long. When it turns bearish, close the position.
First, the define() function declares the parameters — the knobs you can tune later during optimisation:
function define(ctx) {
ctx.param('fastLength', {
type: 'int', label: 'Fast EMA', default: 9,
min: 5, max: 50, optimize: true, group: 'Trend'
});
ctx.param('slowLength', {
type: 'int', label: 'Slow EMA', default: 21,
min: 10, max: 200, optimize: true, group: 'Trend'
});
}
These parameters have default values that work out of the box, but because optimize: true is set, the platform can automatically search for better values during Walk-Forward Analysis. The min/max bounds prevent the optimiser from exploring absurd values.
Next, init() declares the indicators — telling the engine what to calculate before the bar-by-bar simulation begins:
function init(ctx) {
ctx.indicator('fastEma', 'EMA', {
period: ctx.p.fastLength, source: 'close'
});
ctx.indicator('slowEma', 'EMA', {
period: ctx.p.slowLength, source: 'close'
});
}
Notice ctx.p.fastLength — the indicator period references the parameter, so when the optimiser changes the parameter value, the indicator automatically recalculates. This is how parameters and indicators stay connected.
Finally, onBar() contains the actual trading logic — the rules that fire on every candle:
function onBar(ctx, i) {
const fast = ctx.ind.fastEma;
const slow = ctx.ind.slowEma;
if (q.isNaN(fast[i]) || q.isNaN(slow[i])) return;
if (q.crossOver(fast, slow, i) && !ctx.state.inPosition) {
ctx.order.market('ASSET', 1, { signal: 'buy' });
ctx.state.inPosition = true;
}
if (q.crossUnder(fast, slow, i) && ctx.state.inPosition) {
ctx.order.close('ASSET', { signal: 'sell' });
ctx.state.inPosition = false;
}
}
The q.isNaN() check skips bars where the indicators have not had enough data to compute — the warm-up period. After that, the logic maps directly to the plain-language rules: if the fast EMA crosses above the slow and we have no position, buy. If it crosses below and we are long, close. Every line has a clear purpose, and the entire strategy fits in under 30 lines of code.
Note: ctx.pos('ASSET') exists but does not track real position state during a backtest - it always reports flat. Track "am I in a position" yourself with a ctx.state flag, as above.