User guide
Strategy scripts
Write your own strategy for the Candle Player’s Backtest panel: a first script step by step, every line, value and function the language has, complete examples to start from, and what to do when a script does not run. In the app, open the Candle Player, press Backtest, and choose Custom script in the Strategy list.
Your first script
A strategy script tells the Backtest panel when a strategy would buy, sell short or close. It runs on the candles of the chart, candle by candle, and the panel shows each of those trades on the chart. The trades are a test on past candles only: CandleDraw places no order and connects to no broker.
- Open the Candle Player from the profile menu.
- Press Backtest on the transport bar. The Backtest panel opens in the middle of the canvas; drag it by its title to move it aside.
- In the Strategy list, choose Custom script. The editor shows a working example.
- Change a number on an input line, for example input fast = 10 to input fast = 5. The results and the trades on the chart change at once.
- Or choose a script from Start from an example under the editor, and change it to your idea. Its Built-in strategies group holds the script of every strategy in the Strategy list.
- Press Play on the transport bar to watch the trades appear candle by candle.
The example the editor starts with, line by line:
// Moving average crossover
strategy "My crossover"
input fast = 10, 2..200
input slow = 30, 3..400
fast_ma = sma(close, fast)
slow_ma = sma(close, slow)
if crossover(fast_ma, slow_ma)
long
if crossunder(fast_ma, slow_ma)
exit| Line | What it does |
|---|---|
| // Moving average crossover | A note. The script ignores it. |
| strategy "My crossover" | The name of the script. |
| input fast = 10, 2..200 | A setting called fast: 10 to start, any whole number from 2 to 200. It shows as a field under the editor. |
| fast_ma = sma(close, fast) | The average of the last fast closes, worked out on every candle and kept as fast_ma. |
| if crossover(fast_ma, slow_ma) | True on the candle where the fast average goes above the slow one. |
| long | Indented under the if, so it runs only then: buy. |
| exit | Close the trade when the fast average goes back below. |
How a script runs
Knowing these rules makes a script do what you mean.
- The script runs once for every candle, from the first candle of the layer to the last, and each time from its top line to its bottom line.
- On each candle it sees that candle and the ones before it, never a later one. A result that looks too good cannot come from reading ahead.
- A trading action on a candle is filled at the open of the next candle, as a real order placed at the close would be.
- There is one trade at a time. long while short turns the trade around in one step.
- Every line runs on every candle, also the lines under an if that is not true: a function there still counts every candle. Only the names set and the trading actions under it wait for the if.
- A name keeps its value from candle to candle until a line sets it again. Before the first time it is set, it is na.
- The stop loss, take profit, fees, slippage and Allow short trades in the panel apply to the script as to any strategy. With Allow short trades off, short closes a long and opens nothing.
- On a layer without prices, such as a generated chart, each trade is one unit and the results are in points.
Lines and blocks
One statement per line. These are all the kinds of line a script can have.
| Line | What it does |
|---|---|
| strategy "Name" | Names the script. Optional, once, at the top level; without it the name is Custom script. |
| input name = 10, 2..200 | A setting with its default and range. It becomes a field under the editor. See Inputs. |
| name = expression | Works out a value on every candle and keeps it under that name. |
| if condition | Runs the lines indented under it when the condition is true. |
| else if condition | Placed under an if, at its indent: tried when the if above was not true. |
| else | Runs its indented lines when no if above it in the chain was true. |
| long | Buys. See Trading actions. |
| short | Sells short. See Trading actions. |
| exit | Closes the trade you hold. |
| // comment | Everything after // on a line is a note for you; the script ignores it. |
Indentation shows what belongs to an if. The lines under an if that start further to the right are its block; the block ends at the first line that starts no further right than the if. Use the same number of spaces for every line of a block (two is usual). A tab counts as four spaces. An else goes at the same indent as its if.
if close > open
ups = nz(ups[1]) + 1
else if close < open
ups = 0
else
ups = nz(ups[1])
if ups >= 3
longInputs
An input is a setting you can change without editing the script. Each one becomes a field under the editor, with its own name as the label, and the backtest runs again when you change it.
| Line | What you get |
|---|---|
| input length = 14 | A whole number, 14 to start, with no range. |
| input length = 14, 2..100 | A whole number from 2 to 100. |
| input level = 30.5, 5..50 step 0.5 | A number with decimals: the field moves in steps of 0.5. |
| input offset = -2, -10..10 | Negative values are allowed. |
Inputs go at the top level, not under an if. An input is whole numbers only when its default, its range and its step are all whole numbers. Use an input wherever a length or a history count is asked for: sma(close, length), close[lag].
Values, history and na
Every name in a script has one value per candle: a number, true or false, or na (no value yet).
| Value | Meaning |
|---|---|
| open | The candle’s open. |
| high | The candle’s high. |
| low | The candle’s low. |
| close | The candle’s close. |
| volume | The candle’s volume (0 where the layer has none). |
| bar_index | The candle number, from 0 for the first candle of the layer. |
| position | The trade you hold now: 1 long, -1 short, 0 none. |
Add [n] to any value to read it n candles ago: close[1] is the previous close, sma(close, 10)[1] the previous average. Before the first candle there is nothing to read, so the result is na.
na means there is no value yet: an average of 20 candles is na on the first 19. Arithmetic and comparisons with na give na, and an if with na does not run its block, so a script waits by itself until its values exist. nz(x) reads na as 0, nz(x, 1) as 1. Dividing by 0 also gives na.
true and false are written as true and false. Comparisons give them; and, or and not combine them.
Operators
From the first worked out to the last; use parentheses to change the order: (high + low) / 2.
| Operator | Meaning |
|---|---|
| x[n] | The value n candles ago: close[1] is the candle before. n is a whole number or an input. |
| -x | The negative of x. |
| * / % | Multiply, divide, remainder. |
| + - | Add, subtract. |
| < <= > >= == != | Compare two numbers: less, at most, more, at least, equal, not equal. Gives true or false. |
| not | True when its condition is false. |
| and | True when both conditions are true. |
| or | True when either condition is true. |
Comparisons do not chain: write low < close and close < high, not low < close < high.
Functions
source is any number: close, a name you set, or a calculation such as (high + low) / 2. length is a whole number or an input.
| Function | What it gives |
|---|---|
| sma(source, length) | Simple moving average of source over the last length candles. |
| ema(source, length) | Exponential moving average, started from the simple average of the first length values. |
| rma(source, length) | Wilder’s moving average (each candle counts 1/length), started like ema. |
| rsi(source, length) | Wilder’s relative strength index, from 0 to 100. |
| stdev(source, length) | Standard deviation of source over the last length candles. |
| highest(source, length) | Highest value of source over the last length candles, this one included. |
| lowest(source, length) | Lowest value of source over the last length candles, this one included. |
| atr(length) | Average true range: Wilder’s average of the true range over length candles. |
| crossover(a, b) | True on the candle where a goes from at or below b to above it. |
| crossunder(a, b) | True on the candle where a goes from at or above b to below it. |
| change(source, length = 1) | source minus its value length candles ago. |
| nz(source, replacement = 0) | source, or the replacement where source is na. |
| sum(source, length) | Sum of source over the last length candles. |
| cum(source) | Running total of source from the first candle; a candle with na adds nothing. |
| median(source, length) | Middle value of source over the last length candles. |
| highest_bars(source, length) | How many candles ago source was highest within the last length candles; 0 is this one, and on a tie the most recent counts. |
| lowest_bars(source, length) | How many candles ago source was lowest within the last length candles; 0 is this one. |
| percentrank(source, length) | Percent of the previous length values of source that are at or below the current one, 0 to 100. |
| correlation(a, b, length) | How closely a and b moved together over the last length candles, from -1 to 1. |
| sqrt(x) | Square root of x; na below 0. |
| log(x) | Natural logarithm of x; na at 0 or below. |
| exp(x) | e to the power x. |
| pow(x, y) | x to the power y; na where there is no real result. |
| round(x) | x rounded to the nearest whole number. |
| floor(x) | x rounded down. |
| ceil(x) | x rounded up. |
| abs(x) | The value of x without its sign. |
| min(x, y) | The smaller of x and y. |
| max(x, y) | The larger of x and y. |
Each place a function is written keeps its own count, so sma(close, 10) written twice is two separate averages with the same result.
Studies
Every study in the Studies dialog can be used in a script, with the same settings as in Properties and the same values the chart draws. A study takes its settings by name, in any order, and each one you leave out keeps the value a new study starts with.
bb = bollinger_bands(period = 20, standard_deviations = 2)
trend = moving_average(method = "ema", period = 50)
r = relative_strength_index(period = 14)
if close > bb.upper and close > trend and r < 70
long
if close < bb.basis
exit- A setting is written name = value. A number setting takes a number or an input; a setting with choices takes the choice in double quotes, such as method = "ema" or source = "hl2".
- A study with one line gives a number: r = relative_strength_index(period = 14), then r > 70.
- A study with several lines gives them by name: keep the study under a name, bb = bollinger_bands(), and read bb.upper, bb.basis or bb.lower. bb.upper[1] is the line one candle before. Or write the line straight after the call: macd().histogram.
- A name that holds a study is set once, straight from the call, and is read only through its lines.
- A value outside a setting’s range, a choice that does not exist or a misspelled setting is a mistake, listed with the settings the study takes.
- A study whose chart drawing uses later candles gives its value on the candle where it is known, so a script never reads ahead. The notes under such a study say how.
- Volume studies read the volume the candles have. On a layer without volume, such as a generated chart, the chart estimates volume, but a script reads 0.
moving_average
Moving Average. Averages the closes. Exponential by default; switch the method in its settings.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 14 when left out. |
| method | Method. One of "sma", "ema", "wma", "smma", "hull", "dema", "tema", "alma", "kama", "lsma", "zlema", "mcginley", "t3", "trima", "vidya", "frama"; "ema" when left out. |
| source | Source. One of "close", "open", "high", "low", "hl2", "hlc3", "ohlc4"; "close" when left out. |
Gives: one number, The study line..
volume_weighted_moving_average
VWMA. Moving average weighted by each candle’s volume.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
| source | Source. One of "close", "open", "high", "low", "hl2", "hlc3", "ohlc4"; "close" when left out. |
Gives: one number, The study line..
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
ichimoku_cloud
Ichimoku Cloud. Five lines and a cloud drawn ahead of price.
| Setting | What it sets |
|---|---|
| conversion | Conversion, from 1 to 500, whole numbers; 9 when left out. |
| base | Base, from 1 to 500, whole numbers; 26 when left out. |
| span_b | Span B, from 1 to 500, whole numbers; 52 when left out. |
| displacement | Displacement, from 0 to 200, whole numbers; 26 when left out. |
Gives: .conversion (The conversion line.), .base (The base line.), .lagging (The lagging line, read on the bar it is known.), .span_a (Span A, shifted forward.), .span_b (Span B, shifted forward.)
The chart draws the lagging line displacement candles back, at a close it has not seen yet; the script reads it on the bar it is known, so lagging equals that bar’s close. The spans read the values shifted onto each bar, as drawn.
higher_timeframe_candles
Higher timeframe candles. A higher timeframe’s candles drawn under the chart they roll up from.
| Setting | What it sets |
|---|---|
| timeframe | Timeframe. One of "M1", "M5", "M15", "M30", "H1", "H4", "D1", "W1"; Left out, the next timeframe above the bars’ own. when left out. |
Gives: .open (The last completed candle open.), .high (Its high.), .low (Its low.), .close (Its close.)
The chart draws the candle still forming from candles after this one; the script reads the last completed higher timeframe candle, from the first bar of the next one. Candles start at UTC boundaries (W1 on Monday); on market data the chart starts H4, D1 and W1 at 17:00 New York, so those can differ. A timeframe at or below the bars’ own gives na.
supertrend
SuperTrend. A trailing stop an ATR from price, flipping when it is crossed.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 10 when left out. |
| atr_multiplier | ATR multiplier, from 0.1 to 10; 3 when left out. |
Gives: .value (The stop line.), .direction (1 while the stop is below price (rising), -1 while above.)
parabolic_sar
Parabolic SAR. Dots that close in on price until the trend turns.
| Setting | What it sets |
|---|---|
| step | Step, from 0.001 to 1; 0.02 when left out. |
| maximum | Maximum, from 0.01 to 1; 0.2 when left out. |
Gives: .value (The stop line.), .direction (1 while the stop is below price (rising), -1 while above.)
chandelier_exit
Chandelier Exit. A trailing stop an ATR multiple from the highest high or lowest low.
| Setting | What it sets |
|---|---|
| atr_period | ATR period, from 2 to 500, whole numbers; 22 when left out. |
| atr_multiplier | ATR multiplier, from 0.1 to 10; 3 when left out. |
Gives: .value (The stop line.), .direction (1 while the stop is below price (rising), -1 while above.)
volatility_stop
Volatility Stop. A trailing stop an ATR multiple from the trend’s most extreme close.
| Setting | What it sets |
|---|---|
| atr_period | ATR period, from 2 to 500, whole numbers; 20 when left out. |
| atr_multiplier | ATR multiplier, from 0.1 to 10; 2 when left out. |
Gives: .value (The stop line.), .direction (1 while the stop is below price (rising), -1 while above.)
chande_kroll_stop
Chande Kroll Stop. Long and short stop lines an ATR multiple in from the period’s extremes.
| Setting | What it sets |
|---|---|
| atr_period | ATR period, from 2 to 500, whole numbers; 10 when left out. |
| atr_multiplier | ATR multiplier, from 0.1 to 10; 1 when left out. |
| stop_length | Stop length, from 1 to 500, whole numbers; 9 when left out. |
Gives: .long_stop (The stop for a long position.), .short_stop (The stop for a short position.)
aroon
Aroon. How recently the period’s high and low were set, 0–100, or their gap.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 14 when left out. |
Gives: .up (Aroon Up.), .down (Aroon Down.), .oscillator (Up minus Down.)
vortex
Vortex. Upward and downward travel as shares of the true range, as +VI and -VI.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 14 when left out. |
Gives: .plus_vi (The +VI line.), .minus_vi (The -VI line.)
zig_zag
Zig Zag. A line joining the swing highs and lows, ignoring smaller moves.
| Setting | What it sets |
|---|---|
| deviation | Deviation (%), from 0.1 to 100; 5 when left out. |
| depth | Depth, from 1 to 500, whole numbers; 10 when left out. |
| swings_on | Swings on. One of "high_low", "close"; "high_low" when left out. |
Gives: .pivot (The newest confirmed swing.), .extreme (The extreme of the leg in progress; na when none.), .direction (1 while the leg in progress rises, -1 while it falls.)
Read as the chart draws it with the bars so far: a swing is confirmed only once price has turned far enough, and the newest swing and the extreme can still move.
fractals
Fractals. Arrows over swing highs and under swing lows, with a set reach each side.
| Setting | What it sets |
|---|---|
| candles_before | Candles before, from 1 to 20, whole numbers; 2 when left out. |
| candles_after | Candles after, from 1 to 20, whole numbers; 2 when left out. |
Gives: .up (The high of the newest confirmed up fractal.), .down (The low of the newest confirmed down fractal.)
A fractal is known only once its candles after exist: the chart marks candle i, the script reads it from candle i + candles_after on.
directional_movement
ADX / DMI. Trend strength, with the buying and selling pressure behind it.
| Setting | What it sets |
|---|---|
| di_period | DI period, from 2 to 500, whole numbers; 14 when left out. |
| adx_smoothing | ADX smoothing, from 1 to 500, whole numbers; Left out, it follows the DI period. when left out. |
Gives: .adx (The ADX line.), .plus_di (The +DI line.), .minus_di (The -DI line.), .adxr (The ADXR line: the ADX averaged with its value a smoothing length ago.)
choppiness_index
Choppiness Index. Whether price is trending or moving sideways, 0–100.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 14 when left out. |
Gives: one number, The study line..
vertical_horizontal_filter
Vertical Horizontal Filter. The closes’ range against their total travel: trend or range.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 28 when left out. |
Gives: one number, The study line..
alligator
Alligator. Three smoothed averages, each shifted forward.
| Setting | What it sets |
|---|---|
| jaw | Jaw, from 1 to 500, whole numbers; 13 when left out. |
| teeth | Teeth, from 1 to 500, whole numbers; 8 when left out. |
| lips | Lips, from 1 to 500, whole numbers; 5 when left out. |
| jaw_shift | Jaw shift, from 0 to 100, whole numbers; 8 when left out. |
| teeth_shift | Teeth shift, from 0 to 100, whole numbers; 5 when left out. |
| lips_shift | Lips shift, from 0 to 100, whole numbers; 3 when left out. |
Gives: .jaw (The jaw, shifted forward.), .teeth (The teeth, shifted forward.), .lips (The lips, shifted forward.)
gator_oscillator
Gator Oscillator. How far apart the Alligator’s lines are, as two histograms.
| Setting | What it sets |
|---|---|
| jaw | Jaw, from 1 to 500, whole numbers; 13 when left out. |
| teeth | Teeth, from 1 to 500, whole numbers; 8 when left out. |
| lips | Lips, from 1 to 500, whole numbers; 5 when left out. |
| jaw_shift | Jaw shift, from 0 to 100, whole numbers; 8 when left out. |
| teeth_shift | Teeth shift, from 0 to 100, whole numbers; 5 when left out. |
| lips_shift | Lips shift, from 0 to 100, whole numbers; 3 when left out. |
Gives: .upper (Jaw to teeth gap.), .lower (Teeth to lips gap.)
bollinger_bands
Bollinger Bands. A moving average with standard-deviation bands either side.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
| basis_method | Basis method. One of "sma", "ema", "wma", "smma", "hull", "dema", "tema", "alma", "kama", "lsma", "zlema", "mcginley", "t3", "trima", "vidya", "frama"; "sma" when left out. |
| standard_deviations | Standard deviations, from 0.1 to 10; 2 when left out. |
| source | Source. One of "close", "open", "high", "low", "hl2", "hlc3", "ohlc4"; "close" when left out. |
Gives: .basis (The middle line.), .upper (The upper band.), .lower (The lower band.)
bollinger_percent_b
Bollinger %B. Where price sits between the Bollinger bands, in a pane.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
| basis_method | Basis method. One of "sma", "ema", "wma", "smma", "hull", "dema", "tema", "alma", "kama", "lsma", "zlema", "mcginley", "t3", "trima", "vidya", "frama"; "sma" when left out. |
| standard_deviations | Standard deviations, from 0.1 to 10; 2 when left out. |
| source | Source. One of "close", "open", "high", "low", "hl2", "hlc3", "ohlc4"; "close" when left out. |
Gives: one number, The study line..
keltner_channels
Keltner Channels. A moving average with bands an ATR wide either side.
| Setting | What it sets |
|---|---|
| basis_period | Basis period, from 2 to 500, whole numbers; 20 when left out. |
| atr_period | ATR period, from 1 to 500, whole numbers; Left out, it follows the basis period. when left out. |
| atr_multiplier | ATR multiplier, from 0.1 to 10; 2 when left out. |
Gives: .basis (The middle line.), .upper (The upper band.), .lower (The lower band.)
donchian_channels
Donchian Channels. The highest high and lowest low over a period.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: .basis (The middle line.), .upper (The upper band.), .lower (The lower band.)
envelopes
Envelopes. A moving average with bands a set percentage either side.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 14 when left out. |
| basis_method | Basis method. One of "sma", "ema", "wma", "smma", "hull", "dema", "tema", "alma", "kama", "lsma", "zlema", "mcginley", "t3", "trima", "vidya", "frama"; "sma" when left out. |
| deviation | Deviation (%), from 0.01 to 25; 0.1 when left out. |
| source | Source. One of "close", "open", "high", "low", "hl2", "hlc3", "ohlc4"; "close" when left out. |
Gives: .basis (The middle line.), .upper (The upper band.), .lower (The lower band.)
linear_regression_channel
Linear Regression Channel. A rolling regression line with deviation bands either side.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 100 when left out. |
| standard_deviations | Standard deviations, from 0.1 to 10; 2 when left out. |
| source | Source. One of "close", "open", "high", "low", "hl2", "hlc3", "ohlc4"; "close" when left out. |
Gives: .basis (The regression line.), .upper (The upper band.), .lower (The lower band.)
acceleration_bands
Acceleration Bands. Averages of the highs and lows, pushed out by each candle’s range.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
| width_factor | Width factor, from 0.1 to 20; 4 when left out. |
Gives: .basis (The middle line.), .upper (The upper band.), .lower (The lower band.)
relative_vigor_index
Relative Vigor Index. Where each candle closed within its range, against a signal line.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 10 when left out. |
Gives: .rvi (The RVI line.), .signal (The signal line.)
relative_strength_index
RSI. Momentum on a 0–100 scale, in a pane below the chart.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 14 when left out. |
| source | Source. One of "close", "open", "high", "low", "hl2", "hlc3", "ohlc4"; "close" when left out. |
Gives: one number, The study line..
stochastic
Stochastic. Where the close sits in its recent range, 0–100.
| Setting | What it sets |
|---|---|
| k_length | %K length, from 1 to 500, whole numbers; 14 when left out. |
| smoothing | Smoothing, from 1 to 100, whole numbers; 3 when left out. |
| d_length | %D length, from 1 to 100, whole numbers; 3 when left out. |
Gives: .k (The %K line.), .d (The %D line.)
stochastic_rsi
Stochastic RSI. The stochastic asked of the RSI line instead of price.
| Setting | What it sets |
|---|---|
| rsi_length | RSI length, from 2 to 500, whole numbers; 14 when left out. |
| k_length | %K length, from 1 to 500, whole numbers; 14 when left out. |
| smoothing | Smoothing, from 1 to 100, whole numbers; 3 when left out. |
| d_length | %D length, from 1 to 100, whole numbers; 3 when left out. |
Gives: .k (The %K line.), .d (The %D line.)
commodity_channel_index
CCI. How far price has strayed from its own average.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
williams_percent_r
Williams %R. The stochastic upside down, on a 0 to −100 scale.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
rate_of_change
Rate of Change. How far price has moved, as a percentage, over a period.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
momentum
Momentum. How far price has traveled over the window, in price units.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
trix
TRIX. Slope of a triple-smoothed average, so short cycles drop out.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
demarker
DeMarker. How much of the recent movement extended up rather than down.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
bulls_power
Bulls Power. How far each high reached past the average.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
bears_power
Bears Power. How far each low reached past the average.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
accelerator_oscillator
Accelerator Oscillator. Whether the Awesome Oscillator’s momentum is still gaining.
No settings.
Gives: one number, The study line..
force_index
Force Index. The size of each move times the volume behind it, smoothed.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
chaikin_oscillator
Chaikin Oscillator. Momentum of the accumulation line rather than its level.
No settings.
Gives: one number, The study line..
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
volume_price_trend
Volume Price Trend. Volume times each close’s percentage change, as a running total.
No settings.
Gives: one number, The study line..
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
ease_of_movement
Ease of Movement. How far the midpoint moves for the volume it takes, averaged.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 14 when left out. |
Gives: one number, The study line..
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
klinger_oscillator
Klinger Oscillator. Two averages of volume force, with a signal line.
No settings.
Gives: .value (The Klinger line.), .signal (The signal line.)
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
percentage_volume_oscillator
Percentage Volume Oscillator. Two averages of volume, their gap as a percentage, with a signal line.
No settings.
Gives: .value (The PVO line.), .signal (The signal line.)
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
awesome_oscillator
Awesome Oscillator. The gap between a fast and a slow average of the bar midpoint.
No settings.
Gives: one number, The study line..
macd
MACD. Two moving averages’ difference, with a signal line.
| Setting | What it sets |
|---|---|
| fast | Fast, from 1 to 500, whole numbers; 12 when left out. |
| slow | Slow, from 1 to 500, whole numbers; 26 when left out. |
| signal | Signal, from 1 to 500, whole numbers; 9 when left out. |
| source | Source. One of "close", "open", "high", "low", "hl2", "hlc3", "ohlc4"; "close" when left out. |
Gives: .macd (The MACD line.), .signal (The signal line.), .histogram (MACD minus signal.)
percentage_price_oscillator
Percentage Price Oscillator. MACD as a percentage of the slow average, with a signal and histogram.
| Setting | What it sets |
|---|---|
| fast | Fast, from 1 to 500, whole numbers; 12 when left out. |
| slow | Slow, from 1 to 500, whole numbers; 26 when left out. |
| signal | Signal, from 1 to 500, whole numbers; 9 when left out. |
| source | Source. One of "close", "open", "high", "low", "hl2", "hlc3", "ohlc4"; "close" when left out. |
Gives: .ppo (The PPO line.), .signal (The signal line.), .histogram (PPO minus signal.)
true_strength_index
True Strength Index. The price change smoothed twice, against its size, with a signal line.
| Setting | What it sets |
|---|---|
| long | Long, from 1 to 500, whole numbers; 25 when left out. |
| short | Short, from 1 to 500, whole numbers; 13 when left out. |
| signal | Signal, from 1 to 500, whole numbers; 13 when left out. |
Gives: .tsi (The TSI line.), .signal (The signal line.)
stochastic_momentum_index
Stochastic Momentum Index. The close against the middle of its recent range, smoothed, with a signal line.
| Setting | What it sets |
|---|---|
| length | Length, from 2 to 500, whole numbers; 10 when left out. |
| smoothing | Smoothing, from 1 to 100, whole numbers; 3 when left out. |
| signal | Signal, from 1 to 100, whole numbers; 3 when left out. |
Gives: .smi (The SMI line.), .signal (The signal line.)
fisher_transform
Fisher Transform. The midpoint’s place in its range, stretched so turns stand out, with a trigger.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 9 when left out. |
Gives: .fisher (The Fisher line.), .trigger (The trigger line: the Fisher line one bar earlier.)
know_sure_thing
Know Sure Thing. Four smoothed rates of change, weighted and added, with a signal line.
| Setting | What it sets |
|---|---|
| signal | Signal, from 1 to 500, whole numbers; 9 when left out. |
Gives: .kst (The KST line.), .signal (The signal line.)
ultimate_oscillator
Ultimate Oscillator. Pressure over range on three windows, weighted into one 0–100 line.
No settings.
Gives: one number, The study line..
chande_momentum_oscillator
Chande Momentum Oscillator. Gains less losses over their sum, from −100 to 100.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 9 when left out. |
Gives: one number, The study line..
schaff_trend_cycle
Schaff Trend Cycle. MACD put through a smoothed stochastic twice, 0–100.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 10 when left out. |
Gives: one number, The study line..
connors_rsi
Connors RSI. A short RSI, a streak RSI and the change’s percent rank, averaged.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 100 when left out. |
Gives: one number, The study line..
detrended_price_oscillator
Detrended Price Oscillator. An earlier close less the average, so the trend drops out and cycles remain.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
coppock_curve
Coppock Curve. A weighted average of two rates of change added together.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 10 when left out. |
Gives: one number, The study line..
balance_of_power
Balance of Power. The close less the open over the candle’s range, averaged, −1 to 1.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 14 when left out. |
Gives: one number, The study line..
average_true_range
ATR. How far price travels in a candle, smoothed.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 14 when left out. |
Gives: one number, The study line..
standard_deviation
Standard Deviation. How spread out the closes are, on its own axis.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
bollinger_bandwidth
Bollinger Bandwidth. How far apart the Bollinger bands are — the squeeze.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
| basis_method | Basis method. One of "sma", "ema", "wma", "smma", "hull", "dema", "tema", "alma", "kama", "lsma", "zlema", "mcginley", "t3", "trima", "vidya", "frama"; "sma" when left out. |
| standard_deviations | Standard deviations, from 0.1 to 10; 2 when left out. |
| source | Source. One of "close", "open", "high", "low", "hl2", "hlc3", "ohlc4"; "close" when left out. |
Gives: one number, The study line..
squeeze_momentum
Squeeze Momentum. A momentum histogram, with dots that mark a volatility squeeze.
| Setting | What it sets |
|---|---|
| bollinger_length | Bollinger length, from 2 to 500, whole numbers; 20 when left out. |
| bollinger_deviations | Bollinger deviations, from 0.1 to 10; 2 when left out. |
| keltner_length | Keltner length, from 2 to 500, whole numbers; 20 when left out. |
| keltner_atr_multiplier | Keltner ATR multiplier, from 0.1 to 10; 1.5 when left out. |
Gives: .momentum (The momentum histogram.), .squeeze_on (True while the bands are inside the channels., true or false)
normalized_atr
Normalized ATR. The average true range as a percentage of the close.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 14 when left out. |
Gives: one number, The study line..
mass_index
Mass Index. Widening and narrowing of the candle range, summed: the reversal “bulge”.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 25 when left out. |
Gives: one number, The study line..
chaikin_volatility
Chaikin Volatility. How fast the average candle range is growing or shrinking, in percent.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 10 when left out. |
Gives: one number, The study line..
relative_volatility_index
Relative Volatility Index. The RSI’s arithmetic over the standard deviation of the closes, 0–100.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 10 when left out. |
Gives: one number, The study line..
volume_bars
Volume. Volume per candle, in a pane below the chart.
No settings.
Gives: one number, The study line..
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
on_balance_volume
On Balance Volume. Volume added on up closes and taken away on down closes.
No settings.
Gives: one number, The study line..
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
accumulation_distribution
Accumulation / Distribution. Volume weighted by where each candle closed in its range.
No settings.
Gives: one number, The study line..
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
money_flow_index
Money Flow Index. Momentum over price and volume together, 0–100.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
chaikin_money_flow
Chaikin Money Flow. Where volume gathered in each candle, summed over a period.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
Gives: one number, The study line..
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
rolling_vwap
Rolling VWAP. Volume-weighted average price over a window, with bands.
| Setting | What it sets |
|---|---|
| period | Period, from 2 to 500, whole numbers; 20 when left out. |
| band_deviations | Band deviations, from 0.1 to 10; 2 when left out. |
Gives: .basis (The VWAP line.), .upper (The upper band.), .lower (The lower band.)
Reads the bars’ own volume. On a layer without imported volume that is 0, while the chart estimates volume from candle shape.
pivot_points
Pivot Points. Support and resistance from the previous session’s range.
| Setting | What it sets |
|---|---|
| formula | Formula. One of "classic", "fibonacci", "camarilla"; "classic" when left out. |
| session_length | Session length (candles), from 1 to 1000, whole numbers; 24 when left out. |
Gives: .pivot (The pivot (P).), .r1 (The R1 level.), .r2 (The R2 level.), .r3 (The R3 level.), .s1 (The S1 level.), .s2 (The S2 level.), .s3 (The S3 level.)
The chart draws the levels of the last completed session across every candle; the script reads, on each bar, the levels of the last session completed by that bar.
Trading actions
What long, short and exit do depends on the trade you hold when they run.
| Action | What happens |
|---|---|
| long | No trade: opens a long. Short: closes the short and opens a long. Long: nothing. |
| short | No trade: opens a short. Long: closes the long and opens a short. Short: nothing. |
| exit | Long or short: closes the trade. No trade: nothing. |
When several actions run on one candle, the last one counts. position tells the script what it holds, so if position == 0 and ... opens a trade only when none is open.
Examples
Complete scripts to start from. In the editor, choose one from Start from an example; it replaces the script in the editor.
Moving average crossover
Buys when the fast average crosses above the slow one and closes when it crosses back below. The editor starts with this one.
// Moving average crossover
strategy "My crossover"
input fast = 10, 2..200
input slow = 30, 3..400
fast_ma = sma(close, fast)
slow_ma = sma(close, slow)
if crossover(fast_ma, slow_ma)
long
if crossunder(fast_ma, slow_ma)
exitBuy the RSI dip
Buys when RSI comes back up through the oversold level and sells when it reaches the overbought level. Shows inputs with decimals.
// Buy when RSI turns up from oversold, sell when it is overbought
strategy "RSI dip"
input length = 14, 2..100
input oversold = 30, 5..50 step 0.5
input overbought = 70, 50..95 step 0.5
r = rsi(close, length)
if crossover(r, oversold)
long
if r > overbought
exitChannel breakout
Buys a close above the highest high of the candles before it and closes on a close below the lowest low. Shows history with [1].
// Breakout of the last N candles; [1] leaves the current candle out
strategy "Channel breakout"
input entry = 20, 2..200
input exit_after = 10, 2..200
top = highest(high, entry)[1]
bottom = lowest(low, exit_after)[1]
if close > top
long
if close < bottom
exitCrossover with a trend filter
Takes the fast crossover only while the price is above a long average, and closes below it. Shows and, else and nested ifs.
// Trade the crossover only with the trend
strategy "Filtered crossover"
input fast = 9, 2..100
input slow = 21, 3..200
input trend = 100, 20..400
uptrend = close > sma(close, trend)
if uptrend
if crossover(ema(close, fast), ema(close, slow))
long
else
exitBollinger breakout with a trend study
Buys a close above the upper Bollinger Band while the price is above a 50-candle EMA, and closes below the band basis. Shows studies with settings and lines read by name.
// Studies from the Studies dialog, with their settings by name
strategy "Bollinger trend"
input length = 20, 5..100
bb = bollinger_bands(period = length, standard_deviations = 2)
trend = moving_average(method = "ema", period = 50)
if close > bb.upper and close > trend
long
if close < bb.basis
exitMACD with an RSI filter
Buys when the MACD histogram turns positive while RSI is below 70, and closes when the histogram turns negative. Shows a study line read straight after the call.
// MACD histogram turns, filtered by RSI
strategy "MACD and RSI"
hist = macd(fast = 12, slow = 26, signal = 9).histogram
r = relative_strength_index(period = 14)
if crossover(hist, 0) and r < 70
long
if crossunder(hist, 0)
exitLong and short
Always in the market: long above the average, short below it. Shows that long and short turn an open trade around.
// Long while above the average, short while below it
strategy "Always in"
input length = 50, 5..400
ma = sma(close, length)
if crossover(close, ma)
long
if crossunder(close, ma)
shortVolatility breakout with a time exit
Buys when the close rises more than a share of the average true range, and closes after a set number of candles. Shows a counter kept from candle to candle.
// Buy a strong rise, close it after a number of candles
strategy "Volatility breakout"
input length = 14, 2..100
input mult = 0.5, 0.1..5 step 0.1
input hold = 5, 1..50
if position == 0
held = 0
else
held = nz(held[1]) + 1
if position == 0 and change(close) > atr(length) * mult
long
if held >= hold
exitBuilt-in strategy templates
Every strategy in the Strategy list is written in this language, and its script is here to read, copy and change. It gives exactly the same trades as the built-in. In the Backtest panel, Edit as script opens the chosen strategy in the editor with its settings kept; Start from an example lists them all under Built-in strategies.
Moving average crossover
Long when the fast SMA crosses above the slow SMA.
// Long when the fast SMA crosses above the slow SMA.
// Short, or flat, when it crosses back below.
// Template: copy it, change it, and run it as your own.
strategy "Moving average crossover"
input fast = 10, 2..200 step 1
input slow = 30, 3..400 step 1
fast_ma = sma(close, fast)
slow_ma = sma(close, slow)
if crossover(fast_ma, slow_ma)
long
else if crossunder(fast_ma, slow_ma)
// With shorting off, the engine turns this into an exit.
shortEMA crossover
Long when the fast EMA crosses above the slow EMA.
// Long when the fast EMA crosses above the slow EMA.
// Short, or flat, when it crosses back below.
// Template: copy it, change it, and run it as your own.
strategy "EMA crossover"
input fast = 9, 2..200 step 1
input slow = 21, 3..400 step 1
fast_ma = ema(close, fast)
slow_ma = ema(close, slow)
if crossover(fast_ma, slow_ma)
long
else if crossunder(fast_ma, slow_ma)
// With shorting off, the engine turns this into an exit.
shortRSI mean reversion
Long when RSI crosses up through the lower level.
// Long when RSI crosses up through the lower level.
// Exit when RSI crosses above the upper level.
// Template: copy it, change it, and run it as your own.
strategy "RSI mean reversion"
input period = 14, 2..100 step 1
input lower = 30, 1..50 step 1
input upper = 70, 50..99 step 1
r = rsi(close, period)
// position is 0 while flat, 1 while long.
if position == 0
// A level is a plain number, so crossover compares the line with it.
if crossover(r, lower)
long
else if crossover(r, upper)
exitBollinger breakout
Long when a candle closes above the upper Bollinger Band.
// Long when a candle closes above the upper Bollinger Band.
// Exit when one closes below the basis.
// Template: copy it, change it, and run it as your own.
strategy "Bollinger breakout"
input period = 20, 2..200 step 1
input mult = 2, 0.5..5 step 0.1
basis = sma(close, period)
// The population standard deviation of the same closes.
deviation = stdev(close, period)
upper = basis + mult * deviation
if position == 0
if close > upper
long
else if close < basis
exitDonchian breakout
Long on a close above the highest high of the entry channel,
// Long on a close above the highest high of the entry channel,
// short on a close below its lowest low.
// Exit on a break of the shorter exit channel.
// Template: copy it, change it, and run it as your own.
strategy "Donchian breakout"
input entry = 20, 2..200 step 1
input exit_channel = 10, 2..200 step 1
entry_high = highest(high, entry)
entry_low = lowest(low, entry)
exit_high = highest(high, exit_channel)
exit_low = lowest(low, exit_channel)
// [1] reads the channel of the bars before this one:
// a close cannot break a high that includes its own bar.
if position == 0
if close > entry_high[1]
long
else if close < entry_low[1]
short
else if position == 1
// Long: a break of the entry low turns the trade around.
if close < entry_low[1]
short
else if close < exit_low[1]
exit
else
// Short: the mirror image.
if close > entry_high[1]
long
else if close > exit_high[1]
exitMACD signal cross
Long when the MACD line crosses above its signal line.
// Long when the MACD line crosses above its signal line.
// Short, or flat, when it crosses back below.
// Template: copy it, change it, and run it as your own.
strategy "MACD signal cross"
input fast = 12, 2..100 step 1
input slow = 26, 3..200 step 1
input signal = 9, 2..100 step 1
macd_line = ema(close, fast) - ema(close, slow)
// An EMA of the MACD line, which starts once that line has values.
signal_line = ema(macd_line, signal)
if crossover(macd_line, signal_line)
long
else if crossunder(macd_line, signal_line)
shortStochastic cross
Long when %K crosses above %D from below the oversold level.
// Long when %K crosses above %D from below the oversold level.
// Short, or flat, when it crosses below %D from above the overbought level.
// Template: copy it, change it, and run it as your own.
strategy "Stochastic cross"
input k = 14, 2..100 step 1
input d = 3, 1..50 step 1
input oversold = 20, 1..50 step 1
input overbought = 80, 50..99 step 1
highest_high = highest(high, k)
lowest_low = lowest(low, k)
// Where the close sits in the range, 0 to 100; 50 when the range is flat.
if highest_high == lowest_low
percent_k = 50
else
percent_k = 100 * (close - lowest_low) / (highest_high - lowest_low)
percent_d = sma(percent_k, d)
// percent_k[1] is %K on the bar before the cross.
if percent_k[1] < oversold and crossover(percent_k, percent_d)
long
else if percent_k[1] > overbought and crossunder(percent_k, percent_d)
shortSupertrend
Long when the Supertrend flips up.
// Long when the Supertrend flips up.
// Short, or flat, when it flips down.
// Template: copy it, change it, and run it as your own.
strategy "Supertrend"
input period = 10, 1..100 step 1
input mult = 3, 0.5..10 step 0.1
atr_value = atr(period)
mid = (high + low) / 2
basic_upper = mid + mult * atr_value
basic_lower = mid - mult * atr_value
// trend is 1 up, -1 down, na until the ATR has warmed up.
// A variable keeps its value from bar to bar until a line assigns it,
// so upper, lower and trend carry over and [1] reads the bar before.
if atr_value >= 0
if nz(trend[1]) == 0
// The first bar with an ATR: start from where the close sits.
upper = basic_upper
lower = basic_lower
if close >= mid
trend = 1
else
trend = -1
else
// A band only tightens, unless the close before broke through it.
if basic_upper < upper[1] or close[1] > upper[1]
upper = basic_upper
if basic_lower > lower[1] or close[1] < lower[1]
lower = basic_lower
if trend[1] == 1
if close < lower
trend = -1
else
if close > upper
trend = 1
if trend[1] == -1 and trend == 1
long
else if trend[1] == 1 and trend == -1
shortKeltner breakout
Long when a candle closes above the upper Keltner Channel.
// Long when a candle closes above the upper Keltner Channel.
// Exit when one closes below the basis.
// Template: copy it, change it, and run it as your own.
strategy "Keltner breakout"
input period = 20, 2..200 step 1
input atr_length = 10, 1..100 step 1
input mult = 2, 0.5..5 step 0.1
basis = ema(close, period)
// atr is Wilder's average of the true range.
upper = basis + mult * atr(atr_length)
if position == 0
if close > upper
long
else if close < basis
exitMomentum
Long when the close is more than the threshold percent above the close
// Long when the close is more than the threshold percent above the close
// a set number of bars ago. Exit when it falls below that earlier close.
// Template: copy it, change it, and run it as your own.
strategy "Momentum"
input lookback = 20, 1..400 step 1
input threshold = 2, 0..50 step 0.5
// close[lookback] is the close that many bars ago.
change_pct = na
if close[lookback] > 0
change_pct = 100 * (close / close[lookback] - 1)
if position == 0
if change_pct > threshold
long
else if change_pct < 0
exitZ-score mean reversion
Long when the close falls more than the entry z-score below its SMA.
// Long when the close falls more than the entry z-score below its SMA.
// Exit when the z-score rises above the exit level.
// Template: copy it, change it, and run it as your own.
strategy "Z-score mean reversion"
input period = 20, 2..400 step 1
input entry = 2, 0.5..5 step 0.1
input exit_level = 0, -3..3 step 0.1
average = sma(close, period)
deviation = stdev(close, period)
// How many deviations the close is from its average; na on a flat window.
z = na
if deviation > 0
z = (close - average) / deviation
if position == 0
if z < -entry
long
else if z > exit_level
exitWhen a script does not run
A script with a mistake does not run: the panel lists each mistake with its line number in place of the results, and the chart shows no trades. These are the usual ones.
| The message has | What to do |
|---|---|
| Unknown name | A word the script does not know: check the spelling, or set the name with name = ... first. Names are case sensitive: Close is not close. |
| Unknown function | A function the language does not have. The Functions table lists every one. |
| is used before it is assigned | The line reads a name that is set only further down. Move the line that sets it above, or read its earlier value with name[1]. |
| takes | A function was given too many or too few values, for example sma(close) in place of sma(close, 20). |
| must be true or false, not a number | An if needs a comparison or a true or false value: if close > open, not if close. |
| does not match the lines above it | The lines of one block must start at the same column. Indent each line under an if by the same number of spaces. |
| Expected an indented line under | An if or else needs at least one line indented under it. |
| has no long, short or exit line, so it never trades | Add at least one trading action. |
| is a built-in name and cannot be an input | An input cannot be called close, high or another built-in name. Choose another name. |
| Cannot assign to the input | An input keeps the value set in its field for the whole run. Store the result under a new name. |
| is outside its range | The default of an input must lie inside its range. |
Testing a strategy
A backtest shows how an idea behaved on these candles, not how it will behave next.
- Try the script on several layers: market data from different periods, an imported CSV and generated charts.
- Set fees and slippage in the panel; a strategy that trades often can lose its result to costs.
- Compare with Buy and hold in the results.
- Set a start point on the chart and press Play to see each trade where it happened, with its stop and target.
- Change one input at a time. A result that holds only for one exact value is likely luck.