Documentation

5. Writing Strategies

Created
Jun 5, 2026
Updated
Jun 5, 2026

A strategy is authored code that places trades during a backtest. You write it in the Strategy Tester's Compose tab, using the same engine and language as custom indicators.

The strategy shape

A strategy export defaults an object implementing the Strategy interface — a name, an optional init, and a next that runs once per bar:

export default {
  name: "SMA Cross",
  init(ctx) {
    // Declare indicators/patterns ONCE here. Store handles on `this`.
    this.fast = ctx.useIndicator("sma", { length: 10 });
    this.slow = ctx.useIndicator("sma", { length: 30 });
  },
  next(ctx) {
    const f = this.fast.at(0), s = this.slow.at(0);     // current values
    const fp = this.fast.at(1), sp = this.slow.at(1);   // one bar back
    if (f == null || s == null || fp == null || sp == null) return; // warmup
    if (fp <= sp && f > s) ctx.entry("long", { side: "long" });     // golden cross
    else if (fp >= sp && f < s) ctx.close("death cross");           // exit
  }
};

Event-driven, no lookahead

The engine walks bars oldest → newest. Orders you submit in next() on bar i are filled by the broker on bar i+1 (market orders at the next open). Indicator and bar accessors can only read the current bar or earlier — there is no way to peek at the future.

Placing trades

Inside next(ctx) you act on the account:

  • ctx.entry(id, { side, ... }) — submit an entry (capped by the pyramiding setting; an opposite entry reverses).
  • ctx.order(id, { side, ... }) — a lower-level buy/sell that nets against an opposite position.
  • ctx.exit(id, { ... }) — a named Pine-like exit supporting stop/limit brackets, trailing stops, partial exits, and entry-ID targeting.
  • ctx.close(...) / ctx.closeAll(...) — flatten the position or everything.
  • ctx.cancel(id?) / ctx.cancelAll() — cancel pending orders.

Read account state with ctx.position ({ size, side, avgPrice, openPnl }), ctx.equity, and ctx.cash, and read recent bars with ctx.bars(n).

The complete surface — order types, sizing precedence, OCA/OCO groups, and trailing exits — is in the Strategy API Reference.

Using indicators and patterns

Declare indicator and pattern handles in init and read them in next. This is covered in Composing Indicators & Patterns.

Running and saving

Run the strategy with the Run button and read the output as described in Reading Backtest Results. Save versions as drafts — see Saving & Managing Drafts. The Compose tab also ships templates (SMA cross, RSI mean reversion, bull-flag breakout, pyramiding pullback) to start from.

Next steps

See the complete strategy API.

Next: Strategy API Reference