Developer APITutorials

Developer tutorials

Build a moving-average crossover in Candle Script

Create, plot, and backtest a two-average crossover with Candle Script's clean-room syntax and bar-by-bar runtime.

Published 2026-08-18; reviewed 2026-08-18.

  1. 1. Define the averages

    Read the close series and calculate fast and slow simple moving averages. Candle Script history is evaluated bar by bar, so each result is aligned to the current candle.

    javascript
    const fastLength = input.int("Fast length", 10, 2, 100);
    const slowLength = input.int("Slow length", 30, 3, 300);
    
    const fast = avg.simple(close, fastLength);
    const slow = avg.simple(close, slowLength);
  2. 2. Paint both series

    Give each calculated series a stable title so it can be styled and inspected on the chart.

    javascript
    paint("Fast average", fast);
    paint("Slow average", slow);
    paint.style("Fast average", "line", "#2563eb", 2);
    paint.style("Slow average", "line", "#f59e0b", 2);
  3. 3. Create crossover conditions

    Use the signal namespace for one-bar crossover events. The conditions become true only when the ordering changes.

    javascript
    const longSignal = signal.crossOver(fast, slow);
    const exitSignal = signal.crossUnder(fast, slow);
    
    paint.marker("Long signal", longSignal, "buy");
    paint.marker("Exit signal", exitSignal, "sell");
  4. 4. Add simulated trade intents

    Send the conditions to the strategy runtime, then run the script through Script Lab's backtest controls. Results are simulations, not investment recommendations.

    javascript
    trade.enter("crossover-long", longSignal);
    trade.exit("crossover-long", exitSignal);

Backtest output is simulated and educational. It is not investment advice or a promise of future performance.

Build a moving-average crossover in Candle Script