Write a script that draws a 20-period EMA, shades it by trend, and can alert when the price crosses it. Each step adds one idea.
Open the editor
In the terminal, open the chart’s menu and choose New script, or press / for the Indicators dialog and choose New script. The editor checks the script as you type and lists its problems underneath; Add to chart runs it on the chart, and Save keeps it in this browser under its name.
Name it and read the bars
Every script starts with indicator(name, options). overlay: true draws on the price pane; without it, the script gets a pane of its own below.
bars() with no options is the chart’s own bars. It is a stream: a source of data with a handler that runs on each bar.
Calculate on every bar
Indicators such as ta.ema are created once at the top, then updated in a handler. The handler runs once for every bar of history, and again on every update of the bar still forming.
Update an indicator on every bar, before any early return: it only advances on the bars it is updated on.
Add a setting
input.* declares a setting the chart’s settings panel shows. Changing it runs the script again from the first bar.
Colour by trend
A plot’s set takes an optional colour for that bar. color.up and color.down are the theme’s own, so they follow the reader’s theme.
Alert on a cross
alert(name) declares an alert, which the reader arms on the chart. fire fires it when the condition is true, at most once per bar, and only on live data.
Next step
Learn how a script runs: the rules behind what you just wrote. Last modified on October 16, 2026