6.14

🧩 Your own indicators (sTraderZ Script)

Write your own chart indicators with sTraderZ Script: first indicator in five minutes, function reference, inputs, saving, limits and notes.

1. 🧩 What is sTraderZ Script?

The built-in chart indicators (moving averages, RSI, MACD and so on) cover many cases. Sometimes you want something of your own: a band made of an average and its volatility, an RSI with coloured zones, or a marker where two lines cross. For that there is sTraderZ Script, a small scripting language that lets you write your own indicators right in the chart.

A script is a short text with calculation rules. sTraderZ.com reads it, runs it candle by candle from the oldest to the newest, and draws the result on the chart: lines, filled areas, markers, background and candle colours.

Who can use it? The script editor is part of the Premium plan (also included in Pro and admin access). You can save up to 50 scripts of your own. Without Premium the "My indicators" panel shows a note instead.

You do not need to be a programmer. The bundled templates (section 2) run right away and you can change them bit by bit. One thing up front: an indicator shows you calculations based on past prices. It does not predict the future and is not investment advice.

2. ⏱️ Your first indicator in five minutes

We will build an EMA band: a centre line (exponential moving average) with a band above and below it whose width follows the current volatility (ATR). It is one of the examples the editor ships with.

  1. Open the chart of a market and choose Script editor in the indicators menu.
  2. In the editor click Templates and pick EMA band. The source code appears in the editor.
  3. Click Apply. After a moment the band lies on the price chart. It is not saved yet.
  4. Change a number, for example 20 in input.int(20, …) to 50, and apply again. The centre line becomes slower.
  5. Give the indicator a name at the top and click Save. You will find it under My indicators.

This is the source code of the example:

//@version=5 indicator("EMA band", overlay=true) len = input.int(20, "Length", minval=1) mult = input.float(1.5, "ATR factor", minval=0.1, step=0.1) src = input.source(close, "Source") basis = ta.ema(src, len) band = ta.atr(len) * mult upper = basis + band lower = basis - band pu = plot(upper, "Upper", color=color.new(color.blue, 40)) pl = plot(lower, "Lower", color=color.new(color.blue, 40)) plot(basis, "Middle", color=color.blue, linewidth=2) fill(pu, pl, color=color.new(color.blue, 90))

Line by line:

  • //@version=5 states which rules the script is written for (more in section 9).
  • indicator(…) gives the indicator a title. overlay=true puts it on top of the price chart; without it the indicator goes into its own pane below.
  • The three input… lines define settings you can change later in a dialog without touching the source code.
  • ta.ema and ta.atr are ready-made calculation functions. The results are kept in variables (basis, band, …).
  • plot draws a line, fill colours the area between two of them. color.new(color.blue, 40) is blue at 40 % transparency.

Two more templates are available: RSI with zones (separate pane, coloured overbought and oversold zones) and SMA cross with candle colour (two averages, candles coloured by their position, triangles mark the crossings).

3. 🏗️ How a script is structured

A script consists of statements that run once per candle, from top to bottom. The main building blocks:

Building blockExampleMeaning
Comment// noteText up to the end of the line, ignored.
Version line//@version=5Controls compatibility with older scripts (section 9). If missing, version 4 applies.
Headerindicator("Name", overlay=true)Title and placement: overlay=true on the price, otherwise in a pane.
Inputlen = input.int(14, "Length")A setting with a default value, changeable later in the dialog.
Create variablemid = (high + low) / 2Recalculated on every candle.
Change variablex := x + 1:= changes an existing variable, = creates it.
Memory variablevar total = 0.0Set only once and keeps its value from candle to candle.
Look backclose[1]Value from one candle ago. Before the first candle the value is na (no value).
Conditionv = close > open ? 1 : 0Short form of "if … then … else …".
if blockif close > open
    x := 1
Indented lines (4 spaces) belong to the block. else if and else work too.
Own functionspan(a, b) => a - bA small reusable formula (see the note below).
Several results[m, s, h] = ta.macd(close, 12, 26, 9)Some functions return several values at once.

Two terms worth knowing:

  • na means "no value". It appears, for example, at the start when an average does not yet have enough candles. Calculating with na gives na. nz(x) replaces na with 0, na(x) tests for it.
  • Operators: + - * / %, comparisons == != < <= > >=, logic and or not.
Important about loops and functions: Loops (for, while) and switch are read but not executed. The script keeps running, you get a note, and values that only arise there stay na. Solve such tasks with the ready-made ta.* functions or with var variables. Your own functions run as long as they calculate without memory, meaning no ta.*, no var and no look-back on their own variables. A function with memory is skipped (result na, with a note).

Rule of thumb for execution: Only what feeds into an output (plot, fill and so on) is calculated. Auxiliary code that is never shown costs no computing time. Outputs may only appear at the top level, not inside if or functions.

4. 🎨 Outputs: what you can put on the chart

OutputWhat it shows
plot(value, "Title", color=…, linewidth=…, style=…)A line, optionally as histogram, columns, area, dots or step line. The colour may change from candle to candle. If the series has no value (na), a gap appears or is bridged, depending on the style.
hline(price, "Title", color=…, linestyle=…)A fixed horizontal line, for example at 70 and 30 for the RSI. Solid, dashed or dotted.
fill(plotA, plotB, color=…)Colours the area between two lines (plot results) or two hlines. For this, keep the result of plot in a variable, like pu and pl in the example.
plotshape(condition, "Title", style=…, location=…, color=…, text=…)A marker (triangle, arrow, circle, cross, diamond, square, flag, label) on every candle where the condition is true. Position: above or below the candle, top, bottom or on the price.
plotchar(condition, "Title", char="x", …)Like plotshape, but with a single character instead of a shape.
bgcolor(colour)Tints the background of a candle, for example for "RSI overbought". na means no tint.
barcolor(colour)Recolours the candles themselves. Works for indicators with overlay=true.
alertcondition(condition, "Title", "Message")Is evaluated and offers an alert in the chart: show the indicator and choose the bell in its legend. The alert keeps the current version of the script with its inputs, checks closed candles only (the running candle never fires) and notifies you by bell, push, email or Telegram. You manage the alerts in the "My indicators" panel. Premium only; up to 20 script alerts.

Colours: color.red, color.green, color.blue, color.orange, color.purple and other basic colours, or a hex value like #2962FF. With color.new(colour, transparency) you make a colour more see-through (0 = fully opaque, 100 = invisible), with color.rgb(r, g, b) you mix your own.

Amounts: A script may have up to 64 outputs, and one plotshape up to 500 markers.

5. 📚 Function reference

This overview lists the functions sTraderZ Script actually runs. Terms in the signatures describe the order of arguments; source is a price series such as close, length is a number of candles.

Price data and chart information

NameMeaning
open, high, low, close, volumeOpen, high, low, close and volume of the current candle.
hl2, hlc3, ohlc4, hlcc4Averages of high/low, high/low/close, all four prices, or with a double-weighted close.
bar_index, last_bar_indexNumber of the current and of the last candle (counts from 0).
time, timenowTimestamp of the candle or the current moment.
syminfo.ticker, syminfo.currency, syminfo.type, syminfo.mintick, syminfo.timezoneSymbol, currency, instrument type, smallest price step and time zone of the market.
timeframe.period, timeframe.multiplier, timeframe.isintraday, timeframe.isdaily …Which timeframe the chart currently shows.
barstate.isfirst, barstate.islast, barstate.ishistory …Where in the history you currently are (first candle, last candle, …).

Moving averages and smoothing

FunctionWhat it calculates
ta.sma(source, length)Simple average of the last candles.
ta.ema(source, length)Exponential average, recent candles count more.
ta.wma(source, length)Linearly weighted average.
ta.rma(source, length)Moving average with slow smoothing (basis of RSI and ATR).
ta.vwma(source, length)Volume-weighted average.
ta.hma(source, length)Hull average, reacts fast with little lag.
ta.swma(source)Fixed average over four candles with weights in the middle.

Volatility, bands and trend

FunctionWhat it calculates
ta.tr, ta.atr(length)True range of a candle and its average (ATR), a measure of volatility.
ta.stdev(source, length), ta.variance(source, length)Standard deviation and variance.
[middle, upper, lower] = ta.bb(source, length, factor)Bollinger Bands.
[middle, upper, lower] = ta.kc(source, length, factor)Keltner Channel.
[line, direction] = ta.supertrend(factor, atr_length)ATR-based trend line; direction is −1 (up) or 1 (down).
ta.sar(start, step, max)Parabolic SAR.
[plusDI, minusDI, adx] = ta.dmi(di_length, adx_smoothing)Directional indicators and ADX (trend strength).

Oscillators and momentum

FunctionWhat it calculates
ta.rsi(source, length)Relative Strength Index from 0 to 100.
[macd, signal, hist] = ta.macd(source, fast, slow, signal)MACD line, signal line and histogram.
ta.stoch(source, high, low, length)Stochastic value from 0 to 100.
ta.cci(source, length)Commodity Channel Index.
ta.mfi(source, length)Money Flow Index (RSI that includes volume).
ta.wpr(length)Williams %R.
ta.mom(source, length), ta.roc(source, length)Price change over n candles, absolute or in percent.
ta.obv, ta.pvt, ta.vwapOn-balance volume, price-volume trend and volume-weighted daily average (calendar day in UTC).

Highs/lows, crossings and patterns

FunctionWhat it calculates
ta.highest(source, length), ta.lowest(source, length)Highest or lowest value of the last candles. With only the length as argument, high or low is used.
ta.highestbars(source, length), ta.lowestbars(source, length)How many candles back the highest or lowest value lies.
ta.change(source, length)Difference from the value n candles ago.
ta.crossover(a, b), ta.crossunder(a, b), ta.cross(a, b)True when a crosses b from below, from above, or in either direction.
ta.rising(source, length), ta.falling(source, length)True when the series has risen or fallen for n candles in a row.
ta.barssince(condition)Candles since the condition was last true.
ta.valuewhen(condition, source, n)Value of the source when the condition was true for the n-th most recent time.
ta.pivothigh(source, left, right), ta.pivotlow(source, left, right)Local high or low, confirmed by the given number of candles to the left and right (so it appears with a corresponding delay).
ta.cum(source), math.sum(source, length)Running total, or sum of the last n candles.

Maths, helpers and text

FunctionWhat it calculates
math.abs, math.signAbsolute value and sign.
math.max(…), math.min(…), math.avg(…)Largest, smallest value or mean of any number of values.
math.round(x, digits), math.floor, math.ceilRound, round down, round up.
math.sqrt, math.pow(base, exponent), math.exp, math.log, math.log10Square root, power, exponential and logarithms.
nz(x, replacement), na(x), fixnan(x)Replace na, test for na, or hold the last valid value.
iff(condition, then, else)Selection like the short form ?:, but evaluates both sides.
int(x), float(x), bool(x)Convert type (int cuts off the decimals).
str.tostring(x), str.length(text)Convert a number to text, text length.
color.new, color.rgbMake colours transparent or mix them.
time(timeframe, session)Session filter: returns a value only inside the given time window. The chart's timeframe applies.

Inputs

FunctionShown in the dialog as
input.int(…), input.float(…)Number field, with minval, maxval and step as limits.
input.bool(…)On/off switch.
input.string(…, options=[…])Text field or selection list.
input.source(close)Choice of the price series (close, open, high, …).
input.color(…)Colour picker.
input.timeframe(…), input.session(…)Timeframe or trading session.
Note on VWAP: ta.vwap restarts on every calendar day (UTC). Settings such as a different anchor or bands are accepted but not evaluated; you will see a note.

6. 💾 Inputs, saving and My indicators

Input dialog

Every input… line in your script becomes a field in the Inputs dialog. You open it in the My indicators panel at the respective script. There you change, for example, the length of an average without touching the source code. A value outside the allowed limits (minval, maxval)? You then get a message for that field. Default resets everything. If a script has no inputs, the dialog says so.

Apply and save

  • Apply runs the script on the chart right away without saving anything. Good for trying things out.
  • Save creates a new version of the script ("Saved, version 3"). Earlier versions are kept.
  • Save as … creates a copy under a new name, for instance to try out a variant.
  • The editor reminds you of unsaved changes ("Applied. Not saved yet.").

My indicators

In the chart's indicators menu you open the My indicators panel. It lists all your scripts, each labelled Price (on the price chart) or Pane. There you can show and hide scripts, change their inputs, edit or delete them. At the top you see how many of your 50 slots are used.

In the chart itself, the legend offers Recalculate, Show notes and Hide for each script.

Bundled templates

In the editor you find the Templates button with three ready-made examples: EMA band, RSI with zones and SMA cross with candle colour. They are original work by sTraderZ.com and free to use. Load one, change it and save it under your own name.

Chart templates

If you save a chart template (your selection of indicators and settings), it also remembers your own indicators with their inputs. They reappear when you load the template. If a script no longer exists, it is skipped and you see a note.

7. 🚧 Limits and what does not work (yet)

Safety limits

So that a single script cannot slow down the server, fixed limits apply:

LimitValue
Script size64 KB, at most 2,000 lines
Number of candlesthe last 5,000 candles of the selected timeframe
Look-back (close[n])at most 5,000 candles
Run time3 seconds per run, after which the calculation stops with an error message
Outputs per script64 (with up to 500 markers per output)
Textsat most 4,096 characters, longer ones are shortened (with a note)
Saved scripts50 with Premium
Recalculateat most 30 calculations per minute

The result is a look back, not a live ticker

The script runs on the loaded candles when you apply it or have it recalculated. The running, not yet completed candle is not recalculated live with every tick. If you want the latest state, click Recalculate in the legend. Scripts that depend on real-time states (barstate.isrealtime and similar) therefore do not produce live signals.

With the Heikin Ashi candle type the script runs on the Heikin Ashi candles, like the built-in indicators; you get a note about that.

What is not supported

sTraderZ Script understands the basics, not every special function. The following is read but skipped. You get a note with the line each time; the script keeps running:

  • Drawings and tables: label.*, line.*, box.*, table.*, linefill.*, polyline.*
  • Data from other markets or timeframes: request.* (including security)
  • Strategies and backtests: strategy(…) and strategy.*. Of a strategy script only the plots are shown.
  • Loops and branches: for, while, switch
  • Data structures and modules: array.*, matrix.*, map.*, import, export, method, type, enum
  • Further outputs: plotarrow, plotcandle, plotbar, alert()
  • Calendar functions such as year, month, hour, timestamp
  • Individual maths and indicator functions, including trigonometry (math.sin …), ta.linreg, ta.alma, ta.median, ta.percentrank, color.from_gradient

If a skipped element feeds into an output, the affected value is na and the note names the output. A plot that depends only on it stays empty.

8. 🔎 Reading notes and error messages

The editor checks your script when you apply it and shows the result in the Notes area. Every entry names the line and has one of three levels:

LevelMeaningWhat to do
ErrorThe script cannot run: a typo, an unknown name, a wrong number of arguments, a missing character, or a safety limit was exceeded.Check the line and fix it. As long as an error remains, the chart shows nothing.
SkippedAn unsupported element was left out, for example label.new or a for loop.The script runs. Check whether the result still makes sense without that element.
NoteThe script runs, but something is unusual: an old function name, a variable hides another one, a value is ignored.Usually nothing. For "hides the outer variable" you probably meant := instead of =.

Common beginner errors

  • Indentation: After if the lines of the block must be indented (4 spaces or one tab).
  • Changing a value: You change an existing variable with :=. = creates a new one. := on a variable that does not exist yet is an error.
  • Output inside if: plot and the like always sit at the top level. If you want to "draw only sometimes", give the plot a value that is na for "do not draw": plot(condition ? value : na).
  • Too few candles at the start: A 200-period average only has a value from the 200th candle. Before that it is empty, which is normal.
  • Quotes: Texts go in "…" or '…'.

If the 3-second run time is exceeded because the script is very demanding, it usually helps to use shorter lengths, fewer nested functions and fewer outputs.

9. 🧩 Your own indicators in trading rules and backtests

A plot or an alertcondition condition of your script can be the input of a trading rule, for example "buy signal when my indicator reports the condition Buy Signal". The same rule runs in the live evaluation of the strategy and in the backtest and produces the same values in both.

How to create the rule

  1. Open your strategy and choose Rules & signals → Add rule.
  2. Choose the indicator Custom indicator (script).
  3. Choose your script and then the plot or the condition. The list shows the titles from your script.
  4. Set the inputs if needed. An empty field means: the script's default value.
  5. For a plot you choose a comparison and a value (for example "greater than 100" or "crosses above 0"). For a condition the operator is true applies: the rule is met when the condition holds on the current candle.
OutputOperatorThe rule is met when …
Plot<, ≤, =, ≥, >, ≠the plot value of the current candle satisfies the comparison with your value.
Plotcrosses above / belowthe plot crosses your value from below or from above.
Conditionis truethe alertcondition holds on the current candle.

The rule pins one version

When you save, the rule remembers the current version of your script together with its inputs. Later changes to the script do not change this rule, so backtests and signals stay reproducible. If a newer version exists, the rule shows a note. In the Edit rule dialog you can deliberately switch to the new version.

When the script is no longer available

If the script is deleted, locked or you lose access to it, the rule is paused: it is kept, but it gets no more values and counts as not met. There is no error message in the background. The rule row names the reason. If the script is released again, the rule resumes.

Good to know

  • The rule calculates on real candles (not Heikin Ashi) with the available history, at most the latest 5000 candles. This way the backtest gets the same value as live.
  • Script indicators are only calculated for the markets of active strategies. If the calculation takes longer than the time budget per run, the remaining markets follow in the next run.
  • Using a custom indicator in rules belongs to Premium, like the script editor.

10. 📚 The indicator library: share, subscribe, copy

In the indicator library users make their own indicators available to others. You reach it via the entry Indicator library in the Trading System area and in the chart via My indicators → Add from library. The library is visible to logged-in users only. It shows name, description, the author's display name, origin, licence and the complete source code, never an e-mail address.

Subscribe or copy

SubscriptionCopy
Who can do it?All users, including free accountsPremium
VersionAlways follows the author's most recently published version. You never see the author's work in progress.A fixed version that belongs to you. Later changes by the author do not reach the copy.
In "My indicators"Label "Subscription · by …", read-onlyLabel "Copy of …", you can edit it
LimitDoes not count towards your script limitCounts towards your script limit

Subscribed indicators can be shown on the chart, used with your own inputs and saved in chart templates, even without Premium. If the author withdraws an indicator, existing subscriptions keep the last published version.

Publish your own indicator (Premium)

  1. Save your indicator and click Publish in "My indicators".
  2. Enter a description and choose the licence: Own work, MPL 2.0, MIT or Other licence (with free text). For MPL 2.0 and MIT the origin is mandatory, for example "based on … by …".
  3. Confirm: "I am allowed to publish this source code and make it available to other users of sTraderZ.com." Nothing is published without this confirmation. The time and the version of the confirmation text are recorded.

The most recently saved version is published. Clicking Publish again updates all subscriptions. Withdraw removes the indicator from the library. Licence headers in the source code always stay unchanged.

Reporting and locking

On the detail page you can report an indicator that violates the law or the terms of use. If an indicator is locked (by moderation or automatically after several reports), it is locked immediately for everyone, including subscribers. The author still sees it, marked "locked". Copies belong to their owners and stay untouched unless they are reported themselves.

Use is at your own risk. Not investment advice. Read the source code before you trust an indicator. Library indicators come from other users and are not reviewed by sTraderZ.com.

11. 🔁 Bringing over existing scripts

The syntax of sTraderZ Script follows widespread indicator scripting languages. Many scripts you know from books, blogs or forums therefore run with little or no change. Just paste them into the editor and click Apply.

  • Version line: Scripts with //@version=4 (or older, or without any version line) run in legacy mode. Old names such as sma(close, 20), study(…) or crossover(a, b) are mapped automatically to today's spellings (ta.sma, indicator, ta.crossover). With version 5 and 6 you get a note about this.
  • Indicators only: The strategy(…) header is recognised; the plots appear, but there are no orders and no evaluation.
  • Check the result: Small differences from other programs are possible, for example in the handling of the running candle, trading hours or the price data itself. Recalculate important values.
Licence headers stay. Many publicly shared scripts carry a licence notice at the top, for example "This Source Code Form is subject to the terms of the Mozilla Public License 2.0" (MPL) or MIT. This comment block must stay unchanged in the source code. It is not executed, so it does no harm. Also check whether you are allowed to pass the script on or modify it at all. Only use source code you are allowed to use, and respect the author's terms.

12. ⚖️ Liability and no investment advice

Not investment advice: Indicators and scripts are calculation tools based on past prices. They provide no forecast, no trading recommendation and no investment advice. Whether and how you trade is your own decision and at your own risk. Past performance is not a reliable indicator of future results.

Your scripts: The source code you write is yours. Source code, name and settings are stored in your account. Using the script feature requires that you hold the necessary rights to the source code you enter.