此頁面尚未翻譯為繁體中文,因此以英文顯示。
Scripts
@tradecanvas/script writes an indicator the way a trader reads a chart: one bar at a time.
A script keeps values from bar to bar, reads its past values back, runs ta sums that take one
bar at a time, and runs the live bar again on each tick. It becomes an ordinary indicator, so it draws,
scales, saves and alerts like the built-in ones.
Install it beside the chart: npm install @tradecanvas/script @tradecanvas/chart. Before 1.0, its API
can still change between minor versions. For an indicator computed over the whole series at once, write a plugin.
A first script
import { defineScript, scriptIndicator, ta } from '@tradecanvas/script'
const emaCross = defineScript({
id: 'emaCross',
name: 'EMA Cross',
overlay: true,
inputs: {
fast: { default: 9, kind: 'int', min: 1 },
slow: { default: 21, kind: 'int', min: 1 },
},
setup({ inputs, plot, shape }) {
const fast = ta.ema(inputs.fast)
const slow = ta.ema(inputs.slow)
const up = ta.crossover()
const fastLine = plot('Fast', { color: '#f5c542' })
const slowLine = plot('Slow', { color: '#3b82f6' })
const mark = shape('Cross up', { shape: 'triangleUp', position: 'belowBar', color: '#22c55e' })
return (bar) => {
const f = fastLine.set(fast(bar.close))
const s = slowLine.set(slow(bar.close))
mark.set(up(f, s))
}
},
})
chart.registerIndicator(scriptIndicator(emaCross))
chart.addIndicator('emaCross', { fast: 12 }) The inputs are the indicator's settings: the widget's settings dialog shows them, and addIndicator takes them by name.
How a script runs
setupruns once. It declares the plots, marks, fills and levels, makes thetasums and the kept state, and returns the function each bar runs.- Each
tasum keeps its own state: two calls ofta.ema(9)are two averages. Make them insetup, never on a bar, and feed each one on every bar: a sum fed on some bars only averages those bars. Their values are the chart's built-in indicators' values. - The closed bars run once; the last bar stays live. A tick runs it again from the state the bar before left, so a tick costs one bar, not the whole series. When a new bar comes, the live one runs once more as a closed bar, so a feed ends where loading its bars does.
- Keep values in
state. What a script keeps throughstate.var,state.arrayandstate.series, and thetasums, is put back before a bar runs again. A plainletinsetupis not, so a bar run again would count twice into it. - A bar that throws stops the script there. The output's
meta.errorssays which bar and why. A tick on the live bar runs it again; once that bar closes, the script stays stopped until the bars are loaded again.
setup({ plot, state, prices }) {
const highest = state.var(Number.NaN) // kept from bar to bar, put back before a tick
const line = plot('Highest close')
return (bar) => {
highest.value = Number.isNaN(highest.value) ? bar.close : Math.max(highest.value, bar.close)
line.set(highest.value)
const before = prices.close.at(1) // the close one bar back
}
} The ta sums
Each is made in setup with its settings, then given a value each bar.
- Averages:
sma,ema,rma,wma,vwma(value, volume),hma,alma(period, offset, sigma),swma(four values, weighted 1, 2, 2, 1),linreg(period, offset). - Over a window:
sum,stdev,variance,dev(mean distance from the mean),median,percentileNearestRank(period, percentage),percentileLinearInterpolation(period, percentage),percentrank(the share of the bars before at or under this one),correlation(two values),highest,lowest,highestbarsandlowestbars(how many bars back the extreme is, 0 or less). - Running:
cum(the total so far),change,mom,roc,barssince,valuewhen. - Oscillators:
rsi,macd,bb,stoch(value, high, low: the raw %K),mfi(value, volume). - Of the bars:
tr,atr,supertrend,sar(start, increment, max),obv(close, volume). - Events:
crossover,crossunder,cross,rising(period)andfalling(period)(over, or under, every one of the bars before),pivothigh,pivotlow.
ALMA, linreg, the stochastic, MFI, OBV and sar give the values of the built-in indicators
(ALMA, LSMA, Stochastic, MFI, OBV, Parabolic SAR); sar starts on the second bar, its first trend read
from the first two closes. A window with a missing value in it gives none; cum passes over one. bar.live is true on the live bar, the last one, which a tick runs again, and false once it closes.
chart.timeZone in setup is the exchange's zone ('UTC' when the chart names none) and chart.interval its interval ('5m', null when not known). A script that reads the interval in setup is run again when it changes. chart.symbol is what is known of the symbol, null when
nothing is (its symbol, minTick, currency, exchange…), read the same
way, and chart.dayStart the minute of the day the trading day starts at (0 for midnight). bar.lastIndex is the place of the last bar there is: of the bars loaded, the last of them; of one that
came after, its own. What is drawn by it is drawn otherwise once the bars are loaded again.
Running a script without a chart
ScriptRun runs a script on bars of your own, in a test, a worker or a server. Its output holds a
typed array per plot.
import { ScriptRun } from '@tradecanvas/script'
const run = new ScriptRun(emaCross, { fast: 12 })
run.load(bars) // every closed bar
run.tick(liveBar) // the live bar again, as a tick changes it
run.next(newBar) // the live bar closed, a new one opened
run.output.plots[0].values Colours, fills and backgrounds
line.set(value, color)gives a bar its own colour; the line's stretch to that bar takes it.fill(plotA, plotB, { color })shades between two plots;.set(color)colours one bar's stretch.bgcolor()shades the pane behind a bar, behind the candles and the levels.plot(title, { kind: 'area' })shades the space down to zero under the line.plot(title, { offset: 26 })draws a plot 26 bars on of the bars it is set on, past the last bar too (-26: back; at most 500 either way). Its value at a bar is then the one drawn there.last: 20draws only what the last 20 bars set.shapeandbgcolortake both.shape(title, { text: 'Buy' })writes words by each mark;shape: 'labelUp'and'labelDown'are bubbles that hold them..set(true, color)gives a bar's mark its own colour.barcolor()paints a bar's candle, in a script drawn over the prices, on a chart of candles or OHLC bars.hline(70, { color: '#ef4444', lineStyle: 'solid' })draws a level in a colour and dash of its own; without them it is faint and dashed.
setup({ plot, fill, bgcolor, hline }) {
const rsi = ta.rsi(14)
const line = plot('RSI', { color: '#a78bfa' })
const zone = bgcolor()
hline(70, { color: '#ef4444', title: 'Overbought' })
hline(30, { color: '#22c55e', title: 'Oversold' })
return (bar) => {
const value = line.set(rsi(bar.close))
zone.set(value > 70 ? '#ef444422' : value < 30 ? '#22c55e22' : undefined)
}
} Labels, lines, boxes and tables
drawings() in setup gives a list to draw on. On a bar, label, line and box each return a handle to set() or remove() later.
A point is { bar, value }, bar being a bar's index. Past a kind's limit (50 unless
set, 500 at most) the oldest goes. Keep a handle across bars in state.var, so a tick puts it back.
polyline({ points, curved, closed, fill }) is a line through many points (10,000 at most; maxPolylines, 100 at most), and fill(a, b, { color }) fills the space between two lines, following them. table({ position: 'top-right', columns: 2, rows: 3 }) is a table in a place of the pane: cell(column, row, { text, color, textColor, size, align, columnSpan }) sets a cell (set again, it
keeps what is not said) and clear() empties them. A table keeps clear of the legend, and so does a label
on the price pane: it goes to the other side of its point, or beside it, or under the legend.
setup({ drawings }) {
const draw = drawings({ maxLabels: 20 })
return (bar) => {
if (bar.close > bar.open * 1.02) {
draw.label({ at: { bar: bar.index, value: bar.high }, text: '+2%' })
}
}
} Alerts
alertCondition(title, { message }) in setup names a moment, and .set(true) marks the bars it holds. The widget's alert form lists it as name: title, and an alert set on it fires as it turns true.
setup({ alertCondition }) {
const cross = ta.crossover()
const fast = ta.ema(9)
const slow = ta.ema(21)
const crossed = alertCondition('Fast crosses up', { message: 'EMA 9 crossed above EMA 21' })
return (bar) => { crossed.set(cross(fast(bar.close), slow(bar.close))) }
} Higher intervals
request.security(interval, setup) reads a higher interval of the same symbol, made of the
chart's own bars, with days cut on the exchange's clock. Each bar reads the value of the last bar of the
higher interval that closed before its own, which never changes afterwards; with { atClose: true } the chart's bar that closes it reads it too, once that bar has closed. With { live: true } it reads the forming bar's value as it was at that bar, which repaints.
Neither reads a bar after the chart's own. The value may be a number, or a tuple or an object; it is NaN before the first.
setup({ plot, request }) {
const hourly = request.security('1h', () => {
const avg = ta.sma(20)
return (bar) => avg(bar.close)
})
const line = plot('SMA 20, 1h')
return (bar) => { line.set(hourly(bar)) }
} An interval is a count and a unit: '15m', '1h', '4h', '1d', '1w', '1M'. It must be higher than the chart's bars. Other symbols are not read yet.
Limits
A run stops a script at the bar that goes past one of its limits, and its error says which
(limit: 'loop', 'array' or 'time').
- Loop steps.
loop(), called once each time round a loop, counts a bar's steps; past a million (loopSteps) the bar stops, so a loop that never ends does not hang the chart. - Lists. A
state.arrayholds at most 100,000 numbers (arraySize). A list that takes a number every bar and is never cut needs a largerarraySizeon a longer chart, or ashift()to keep it short. - Time. With
runMsset, aload,tickornextpast that many ms after a bar stops there.
setup({ plot, prices, loop }) {
const line = plot('Bars since a higher close')
return () => {
let n = 0
while (n < 500 && prices.close.at(n + 1) <= prices.close.at(0)) {
loop()
n++
}
line.set(n)
}
}
chart.registerIndicator(scriptIndicator(script, { limits: { loopSteps: 10_000, runMs: 200 } })) A higher interval's run keeps to the same loop steps and list sizes; its time counts in the script's. A script
that catches the error and goes on is stopped all the same. A bar that never returns (a loop with no loop() in it) cannot be stopped on the page's own thread: that takes a worker.
In a worker
A script can run in a worker, so a bar that never returns cannot hang the page. The worker's module serves the
scripts, and the page registers each through scriptWorkerIndicator:
// scripts.worker.ts
import { serveScripts } from '@tradecanvas/script'
import { emaCross } from './emaCross'
serveScripts([emaCross])
// the page
chart.registerIndicator(scriptWorkerIndicator(emaCross, {
spawn: () => new Worker(new URL('./scripts.worker.ts', import.meta.url), { type: 'module' }),
timeoutMs: 5000,
})) The page sends the bars once, then one bar a tick, and draws the points the worker sends back; until the first
answer the indicator draws nothing. A worker that does not answer one request within timeoutMs (5 seconds
unless set, the first load of the bars included) is stopped: the script it hung on says so (limit: 'time')
and loads again only for other inputs or other bars; the others load again in a new worker. A removed indicator's
run goes with it, and the worker once it runs nothing. The setup also runs once on the page, to know what the script draws.
Scripts made of a source
For an editor, or a language of your own: the page sends only the source, and the worker makes the script of it
with the resolve you give. The setup runs there too, so nothing of the script runs on the page,
whose Content Security Policy need not allow eval.
// scripts.worker.ts
import { errorAtLine, serveScripts } from '@tradecanvas/script'
serveScripts([], { resolve: (source, id) => compile(source, id) }) // a defineScript of yours; throws errorAtLine(error, 12)
// the page
const spawn = () => new Worker(new URL('./scripts.worker.ts', import.meta.url), { type: 'module' })
try {
chart.replaceIndicator(await scriptFromWorker({ id: 'mine', source, spawn }))
} catch (error) {
if (error instanceof ScriptSourceError) show(error.message, error.line)
} scriptFromWorkerasks the worker what the script draws, and rejects with aScriptSourceError: itsline, andlimit: 'time'when the worker did not answer withintimeoutMs.chart.replaceIndicatorputs it in the place of the version drawn before (Plugins), which is drawn till the new one's values are in.scriptFromWorkerNow({ id, source, descriptor, spawn })is there at once, with thedescriptorkept from before (plugin.descriptor, plain data): register saved scripts with it before a layout that draws them is restored. A descriptor that is not a script's throws aTypeError: askscriptFromWorkeragain then, and when the compiler is a newer one.errorAtLine(error, line)says which line of the source an error stopped on, inresolveor on a bar;errorstells it asline.- A worker runs code made of text if your
resolvedoes: serve the worker's file with a policy of its own (default-src 'none'; script-src 'self' 'unsafe-eval'), which also keeps the script off the network.
What is not there yet
- Other symbols in
request.security. - Pine Script source: a compiler to these scripts is planned.