Class-form indicators

Class-form indicators

On this page

CodeLab is ChartLabs’ in-browser editor for indicators and strategies. Every script uses @chartlabs/script-sdk in one of two forms: the terse indicator() form, or a class that extends Lab. A script that places orders with strategy.* is a strategy you can backtest.

A class-form indicator

The same kind of indicator written as a class: it plots RSI and marks every cross of the 50 midline. Paste it into a blank file and hit Run.

rsi-tracker.ts
// A class-form indicator: paste it into a new CodeLab script and hit Run.
// It plots a 14-period RSI and marks every cross of the 50 midline.
import { Lab, bars, compute, draw, config } from '@chartlabs/script-sdk';

export default class RsiTracker extends Lab {
  static readonly meta = {
    name: 'RSI tracker',
    slug: 'rsi-tracker',
    version: '1.0.0',
    placement: 'subpane' as const,
  };

  private period = config.number('RSI Period', 14, { min: 2, max: 100 });
  private rsiLine = draw.line({ name: 'RSI', color: '#7e57c2', width: 2 });
  private upMark = draw.marker({ name: 'Cross up', shape: 'triangleup', color: '#089981', location: 'below' });
  private downMark = draw.marker({ name: 'Cross down', shape: 'triangledown', color: '#f23645', location: 'above' });
  private prev: number | null = null;

  onBar() {
    // bars.close is current-first: bars.close[0] is this bar, [1] the one before.
    const rsi = compute.rsi(bars.close, { period: this.period.value });
    if (!Number.isFinite(rsi)) return;   // still warming up
    this.rsiLine.push(rsi);

    if (this.prev !== null) {
      if (this.prev < 50 && rsi >= 50) this.upMark.at('current');
      if (this.prev > 50 && rsi <= 50) this.downMark.at('current');
    }
    this.prev = rsi;
  }
}

Mental model

Everything else in CodeLab is easier if you hold these four ideas in your head:

  • Your script is a pure function over bars. It sees the chart’s bars and nothing else. No network, no DOM.
  • History is indexed current-first. close[0] and bars.close[0] are the newest bar, [1] the bar before.
  • Orders are intents, not executions. strategy.entry() queues an order; the backtester fills it at the next bar’s open.
  • The same file can draw and trade. Plot and mark things like any indicator, and call strategy.* to make it a strategy.

bars.* (class form)

In the class form, bars holds the bars loaded so far as plain arrays, current-first: open, high, low, close, volume and timestamps.

TypeScript
if (bars.length < 6) return;   // not enough history yet
bars.close[0];       // this bar's close
bars.close[1];       // previous bar's close
bars.close[5];       // close 5 bars ago
bars.length;         // how many bars are loaded so far
bars.at(0).high;     // careful: at(i) counts from the OLDEST bar (0 = oldest)

Pass these arrays straight to compute.*, for example compute.ema(bars.close, { period: 20 }). See compute.*.