AlphaScript The AlphaScript language
The AlphaScript language
AlphaScript is small on purpose: a few kinds of value, a few statements, and a library made for charts. If you have written any code before, you can read it already.
Statements and comments
One statement per line (or several, separated by ;). Blocks are in braces. // starts a comment to the end of the line, /* … */ a comment of any length.
// a comment
let fast = ta.ema(close, 12) // one statement per line
let slow = ta.ema(close, 26); let gap = fast - slow
/* a longer comment,
over several lines */A line that ends with an operator, a comma or an open bracket carries on to the next one.
Values
| Kind | Written as | Notes |
|---|---|---|
| number | 14 2.5 1_000_000 1e-4 | Whole and decimal numbers are the same kind. |
| bool | true false | Comparisons give bools. |
| text | "Close {close}" 'plain' | In double quotes, {expr} puts a value in the text. Single quotes keep it as it is. |
| colour | #2962ff #2962ff80 color.red | #rrggbb, or #rrggbbaa with opacity. See colours. |
| na | na | Missing. Arithmetic with na gives na, and comparing na with anything is false; x == na asks whether x is missing. |
| list | [1, 2, 3] | See lists. |
Variables: let, state, const
let declares a value worked out on every bar. state declares one kept from bar to bar: its starting value is set on the first bar, and from then on it holds whatever the script puts in it. const is a value that never changes.
let range = high - low // a new value on every bar
state upBars = 0 // kept: counts across the whole chart
const LOOKBACK = 20 // never changes
if close > open {
upBars += 1
}A name declared inside a block (between { }) is known only inside that block.
History: x[n]
x[n] is the value x had n bars ago. It works for the data (close[1]), for any variable, and for any value (ta.sma(close, 20)[1]). Looking back past the first bar gives na; looking forward is not possible.
let change = close - close[1]
let rising = change > 0 and change[1] > 0 and change[2] > 0
let avgBefore = ta.sma(close, 20)[5]Operators
| Arithmetic | + - * / %, ** (power). + joins texts. |
| Comparison | == != < <= > >=. x == na asks whether x is na. |
| Logic | and or not (also && || !) |
| na | a ?? b: a, or b when a is na. |
| Choice | cond ? a : b |
| Assignment | = += -= *= /= %= |
Conditions and loops
if close > open {
bgcolor(color.alpha(color.green, 0.1))
} else if close < open {
bgcolor(color.alpha(color.red, 0.1))
} else {
mark("=", position: "above")
}
let sum = 0
for i in 0..10 { // 0 to 9
sum += close[i]
}
for i in 0..=10 step 2 { // 0, 2, … 10
}
for i in 10..0 { // counts down: 10 to 1
}
for x in [1, 2, 3] {
}
while sum > 100 {
sum /= 2
}break leaves a loop, continue goes to its next round.
Functions
Functions are defined at the top level with fn. Parameters may have defaults; arguments may be given by name. A one-line function can be written with =>.
fn percentChange(a, b) => (a - b) / b * 100
fn band(src, length = 20, width = 2) {
let mid = ta.sma(src, length)
let dev = ta.stdev(src, length)
return [mid + width * dev, mid - width * dev]
}
let [upper, lower] = band(close, width: 2.5)
plot(percentChange(close, close[1]), "Change %")Each call of a function has its own memory for the ta.* calls inside it, so band(close) and band(hl2) keep separate averages. A state inside a function is shared by all its calls.
Named arguments
Library functions take their arguments in order, or by name with name: value, which reads better for options:
plot(ta.ema(close, 21), "EMA", color: #ff9800, width: 2, style: "line")
mark("Buy", position: "below", shape: "triangleUp", color: color.green)Lists
state closes = array.new() // an empty list, kept
closes.push(close)
if closes.size() > 50 {
closes.shift() // drop the oldest
}
let mean = closes.avg()
let first = closes[0]
let last = closes.last()Lists have methods for adding, removing, sorting and summing. An index outside the list stops the script with the line and the bar where it happened.
The script’s settings: indicator()
indicator("Trend strength", overlay: false, precision: 2, short: "TS")overlay: true draws on the price chart; otherwise the script gets a pane of its own. precision is the number of decimals in the legend. Without indicator(), the script goes by the name you gave it in the editor and gets its own pane.
Inputs
Inputs become fields in the indicator’s settings. Their titles and defaults are written out, so the settings exist before the script runs.
let length = input.int("Length", 14, min: 1, max: 500)
let mult = input.float("Multiplier", 2.0, step: 0.1)
let showBands = input.bool("Show bands", true)
let kind = input.string("Average", "EMA", options: ["SMA", "EMA", "WMA"])
let src = input.source("Source", close)
let lineColor = input.color("Line", #2962ff)Drawing
plot() draws a value on every bar; its colour may change from bar to bar. hline() draws a level across the pane, fill() colours between two plots or two levels, bgcolor() colours the bar’s background.
let r = ta.rsi(close, 14)
plot(r, "RSI", color: r > 70 ? color.red : r < 30 ? color.green : #7e57c2, width: 2)
let top = hline(70, "Overbought")
let bottom = hline(30, "Oversold")
fill(top, bottom, color: color.alpha(#7e57c2, 0.08))
bgcolor(r > 70 ? color.alpha(color.red, 0.08) : na)Plot styles: line, step, histogram, columns, circles, cross, area.
mark() puts a glyph on a bar. label(), line() and box() give back a handle you can keep in a state variable and change later: the chart shows them where the script left them.
state last = na
if ta.crossover(close, ta.sma(close, 50)) {
mark("Up", position: "below", shape: "arrowUp", color: color.green)
}
if isLastBar {
last = label("Now " + str(close, 2), close, color: color.blue)
line(barIndex - 30, low[30], barIndex, low, color: color.teal, extend: "right")
}Alerts
alert(message, when: condition) raises an alert on the newest bar: a notice in the app (with a sound when sounds are on) and, if you allowed notifications, a system notification while the tab is in the background. Each call raises it once per bar, while the script is on a chart that is open.
let r = ta.rsi(close, 14)
alert("RSI crossed above 70 on {symbol.name}", when: ta.crossover(r, 70))Printing to the console
print() writes to the editor’s console with the bar it ran on; the last 500 lines are kept. Print on the last bar to see where a script ended up:
if isLastBar {
print("bars:", barCount, "last close:", close)
}Mistakes
The editor checks the script as you type. A mistake (an unknown name, a missing bracket, a wrong argument) is underlined in red with its line and column and, where it can, a suggestion: ta.smaa is not in the library. Did you mean ta.sma? A script with mistakes is saved but not put on the chart. A warning (yellow) does not stop it: for example a ta.* call inside an if, which only remembers the bars where the condition held. A mistake found while running (an index outside a list, a loop that never ends) stops the script; the console shows the line and the bar.