หน้านี้ยังไม่ได้แปลเป็นภาษาไทย จึงแสดงเป็นภาษาอังกฤษ

Indicators

138 built-in indicators. Add one by its id; parameters you leave out take their defaults, and invalid ones fall back to them.

Adding an indicator

const ema = chart.addIndicator('ema', { period: 50 })          // on the price pane
const rsi = chart.addIndicator('rsi', { period: 14 }, 'bottom') // in a pane of its own
chart.updateIndicator(rsi, { period: 21 })
chart.removeIndicator(rsi)

addIndicator returns an instance id: the same indicator can be added several times, each instance with its own inputs, colours and levels.

In TypeScript the built-in ids and their inputs are typed: BuiltInIndicators lists each indicator with its inputs, their defaults, and the keys of its lines, so an editor offers them as you type and a misspelt input fails the type check. An indicator a plugin registers takes any id and inputs.

Sources and indicators on indicators

Indicators marked source below can run on another price than the close (open, high, low, hl2, hlc3, ohlc4, hlcc4) or on another indicator's line. A moving average of RSI is drawn in RSI's pane, on its scale, and goes when RSI does.

import { indicatorSource } from '@tradecanvas/chart'

chart.updateIndicator(ema, { source: 'hlc3' })
const smoothed = chart.addIndicator('sma', { period: 9, source: indicatorSource(rsi, 'value') })

Pane indicators can also share a pane: chart.addIndicator('stochastic', {}, 'bottom', { pane: rsi }).

Levels, colours and values

chart.setIndicatorLevels(rsi, [20, 50, 80])   // null restores 30 / 70
chart.updateIndicatorStyle(rsi, { colors: ['#f2a93b'], lineWidths: [2] })
chart.setIndicatorVisible(rsi, false)

await chart.whenIndicatorsReady()   // at once in 3.x; from 4.0, its code the first time one is added
const series = chart.getIndicatorOutput(rsi)?.series ?? []
const latest = series[series.length - 1]?.value   // keyed by the line keys below

The values are there as an indicator is added. From 4.0 a built-in's code loads the first time one is added, or a layout with one is loaded, so that a page that shows two indicators downloads those two: its output is pending till then. await chart.whenIndicatorsReady() before a read, which resolves at once in 3.x, keeps the read right through 4.0; indicatorUpdate fires as values come.

The legend shows each line's latest value. To tag it on the axis as well, in the line's colour, turn on features.indicatorValueLabels: true or setIndicatorValueLabelsVisible(true) (off by default). A pane's lines, levels, axis and crosshair share one scale.

On some intervals only

An indicator can be kept to some intervals: a 200-day average on the daily chart and up, a fast oscillator on the minute charts only. Each kind of interval (ticks, seconds, minutes, hours, days, weeks, months) is left on, switched off, or given a range of counts; a kind left out shows it on all. The chart reads the rules against the interval of the stream it is connected to, as the interval changes; for bars given with setData, chart.setDataTimeframe('1h') tells it theirs (ChartWidget does this itself); with neither it shows the indicator. The rules are saved with the layout and undone like any other edit.

chart.setIndicatorIntervals(ema, { seconds: false, minutes: false, hours: [1, 4] })
chart.getIndicatorIntervals(ema)    // { seconds: false, minutes: false, hours: [1, 4] }
chart.setIndicatorIntervals(ema, null)  // all of them again

getActiveIndicators() says of each whether it is visible (switched on) and shown (drawn on this interval). In ChartWidget, its legend row greys out while it isn't.

In ChartWidget

The toolbar's Indicators opens a dialog. Type to search every indicator by its name or short name (Enter adds the best match); or pick a group down the side: Favourites, Templates, All, then each kind (moving averages, trend, oscillators, volatility, volume, bands and channels, price and patterns). A row adds its indicator and the dialog stays open for the next; a count shows how many are on the chart, and the star beside it keeps it in the favourites. On a phone the groups are a row of chips over the list.

An indicator's settings (its legend row's name, or its gear) have three tabs: Inputs; Style, a row per line (shown or not, its colours, its dash), the line width, an overlay's price scale and the levels; and Visibility, the intervals it shows on. Every edit shows at once. Cancel or Esc puts it all back, OK keeps it. Defaults resets it, or saves it as the default: new indicators of its kind then start with these inputs and this look, in this browser.

On the price pane (51)

idNameDefault paramsLines
smaSimple Moving Average· sourceperiod: 20, source: "close"SMA
emaExponential Moving Average· sourceperiod: 20, source: "close"EMA
bbBollinger Bands· sourceperiod: 20, stdDev: 2, source: "close"Upper, Basis, Lower
vwapVolume Weighted Average Priceanchor: "session"VWAP
ichimokuIchimoku Cloudtenkan: 9, kijun: 26, senkou: 52, displacement: 26Conversion, Base, Lead A, Lead B, Lagging Span
psarParabolic SARstep: 0.02, max: 0.2SAR
supertrendSupertrendperiod: 10, multiplier: 3Supertrend
keltnerKeltner ChannelemaPeriod: 20, atrPeriod: 10, multiplier: 1.5Upper, Basis, Lower
donchianDonchian Channelperiod: 20Upper, Basis, Lower
pivotsPivot Pointslookback: 24, type: "traditional"R3, R2, R1, P, S1, S2, S3
avwapAnchored VWAPanchorTime: 0AVWAP
zigzagZigZagdeviation: 5Pivot
lrcLinear Regression Channel· sourceperiod: 100, stdDev: 2, source: "close"Upper, Basis, Lower
hmaHull Moving Average· sourceperiod: 21, source: "close"HMA
mtfmaMTF Moving Average· sourceperiod: 50, timeframe: "1d", source: "close"MA
svwapSession VWAPbands: 1VWAP, +1σ, −1σ, +2σ, −2σ, +3σ, −3σ
chandelierChandelier Exitperiod: 22, multiplier: 3Long, Short
alligatorAlligatorjaw: 13, teeth: 8, lips: 5, jawShift: 8, teethShift: 5, lipsShift: 3Jaw, Teeth, Lips
vwmaVolume Weighted Moving Average· sourceperiod: 20, source: "close"VWMA
wmaWeighted Moving Average· sourceperiod: 20, source: "close"WMA
envelopeMoving Average Envelope· sourceperiod: 20, percent: 2.5, source: "close"Upper, Basis, Lower
temaTriple EMA· sourceperiod: 20, source: "close"TEMA
volumeProfileVolume Profilerows: 24—
demaDouble Exponential Moving Average· sourceperiod: 20, source: "close"DEMA
smmaSmoothed Moving Average· sourceperiod: 14, source: "close"SMMA
almaArnaud Legoux Moving Average· sourceperiod: 9, offset: 0.85, sigma: 6, source: "close"ALMA
kamaKaufman Adaptive Moving Average· sourceperiod: 10, fast: 2, slow: 30, source: "close"KAMA
lsmaLeast Squares Moving Average· sourceperiod: 25, offset: 0, source: "close"LSMA
mcginleyMcGinley Dynamic· sourceperiod: 14, source: "close"McGinley
macrossMA Cross· sourcefast: 9, slow: 21, type: "sma", source: "close"Fast, Slow
fractalsWilliams Fractalsperiod: 2Up, Down
cksChande Kroll Stopp: 10, x: 1, q: 9Stop Long, Stop Short
sebStandard Error Bandsperiod: 21, mult: 2, smooth: 3Upper, Middle, Lower
gmmaGuppy Multiple Moving Average—EMA 3, EMA 5, EMA 8, EMA 10, EMA 12, EMA 15, EMA 30, EMA 35, EMA 40, EMA 45, EMA 50, EMA 60
maribbonMoving Average Ribbonma1: 20, ma2: 50, ma3: 100, ma4: 200, exponential: 0MA 1, MA 2, MA 3, MA 4
avgpriceAverage Price—Average
medpriceMedian Price—Median
typpriceTypical Price—Typical
machannelMoving Average ChannelupperLength: 20, lowerLength: 20, upperOffset: 0, lowerOffset: 0Upper, Lower
hammingMoving Average Hamming· sourceperiod: 10, source: "close"MA
madoubleMoving Average Double· sourcefirst: 20, second: 50, type: "sma", source: "close"MA 1, MA 2
matripleMoving Average Triple· sourcefirst: 10, second: 20, third: 50, type: "sma", source: "close"MA 1, MA 2, MA 3
volindexVolatility Indexperiod: 7, mult: 3Stop
tsfTime Series Forecastperiod: 14TSF
wcloseWeighted Close—Weighted
demarkDeMark Projected Range—Projected high, Projected low
rainbowMoving Average Rainbowfirst: 10, step: 10, count: 10, exponential: 0MA 1, MA 2, MA 3, MA 4, MA 5, MA 6, MA 7, MA 8, MA 9, MA 10, MA 11, MA 12, MA 13, MA 14, MA 15, MA 16, MA 17, MA 18, MA 19, MA 20
candlepatternsCandlestick PatternstrendPeriod: 10, reversal: 1, continuation: 1, indecision: 0Bullish, Bearish, Indecision
fvgFair Value GapsminPercent: 0, showFilled: 0Bullish top, Bullish bottom, Bearish top, Bearish bottom
svpSession Volume Profilerows: 24, valueArea: 70POC, VAH, VAL
orderblocksOrder Blockslength: 5, showBroken: 0, count: 5Bullish top, Bullish bottom, Bearish top, Bearish bottom

mtfma plots a moving average from a higher timeframe on the current chart — the daily 50-MA on 1h bars, say. It averages only completed higher-timeframe closes, so it steps at each boundary and never repaints.

vwap starts again at its anchor: 'session', the default, each trading day, from midnight in the exchange's time zone (the symbol's timeZone, else the market's, else UTC); 'week' each Monday; 'month' on the 1st; 'all' never: it averages every bar loaded, so it moves when older bars are paged in. On daily bars the session VWAP is each bar's typical price: choose 'week' or 'month' there. svwap is the session VWAP with σ bands, and avwap starts at the bar you anchor it to. svwap, mtfma, the prior-day lines and the market profile's sessions count their days in the same zone. mtfma's 2h to 12h frames start at the exchange's midnight too, while a feed's own 4h candles stay on UTC's grid, and on daily bars svwap gives its line alone, without bands. In ChartWidget a VWAP at another anchor is named by it ('VWAP Week') in the legend, the chips and the Objects panel, and the anchor and its choices read in the widget's language; the CSV column stays VWAP.

chart.addIndicator('vwap')                      // starts again each trading day
chart.addIndicator('vwap', { anchor: 'week' })  // each Monday: for daily bars
chart.addIndicator('vwap', { anchor: 'all' })   // every bar loaded, as it was before

volumeProfile draws one row per price band from the left edge of the plot; each row's length follows the volume traded in that band. The rows are see-through, so the legend over them and the candles under them stay readable; give the indicator a lower opacity with updateIndicatorStyle to fade it further.

In a pane of their own (87)

idNameDefault paramsLinesLevels
rsiRelative Strength Index· sourceperiod: 14, source: "close"RSI30, 70
macdMACD· sourcefast: 12, slow: 26, signal: 9, source: "close"Histogram, MACD, Signal—
stochasticStochastic OscillatorkPeriod: 14, dPeriod: 3, smooth: 3%K, %D20, 80
atrAverage True Rangeperiod: 14ATR—
adxAverage Directional Indexperiod: 14ADX, +DI, −DI—
obvOn Balance Volume—OBV—
williamsRWilliams %Rperiod: 14%R-80, -20
cciCommodity Channel Indexperiod: 20CCI-100, 0, 100
mfiMoney Flow Indexperiod: 14MFI20, 80
aroonAroonperiod: 25Up, Down—
rocRate of Change· sourceperiod: 12, source: "close"ROC0
tsiTrue Strength Index· sourcelongPeriod: 25, shortPeriod: 13, signalPeriod: 7, source: "close"TSI, Signal0
cmfChaikin Money Flowperiod: 20CMF—
stddevStandard Deviation· sourceperiod: 20, source: "close"StdDev—
adAccumulation/Distribution—A/D—
vrocVolume Rate of Changeperiod: 14VROC0
aoAwesome Oscillatorfast: 5, slow: 34AO—
chaikinOscChaikin Oscillatorfast: 3, slow: 10Chaikin—
voldeltaVolume Deltamode: 0, anchor: "all"Delta—
vortexVortex Indicatorperiod: 14VI+, VI−1
chopChoppiness Indexperiod: 14CHOP38.2, 61.8
uoUltimate Oscillatorfast: 7, mid: 14, slow: 28UO30, 70
fiForce Indexperiod: 13EFI0
crsiConnors RSI· sourcersiPeriod: 3, streakPeriod: 2, rankPeriod: 100, source: "close"CRSI10, 90
coppockCoppock Curve· sourcelongRoc: 14, shortRoc: 11, wma: 10, source: "close"Coppock0
kstKnow Sure Thing· sourceroc1: 10, roc2: 15, roc3: 20, roc4: 30, sma1: 10, sma2: 10, sma3: 10, sma4: 15, signal: 9, source: "close"KST, Signal0
elderrayElder Rayperiod: 13Bull, Bear—
stcSchaff Trend Cycle· sourcefast: 23, slow: 50, cycle: 10, source: "close"STC25, 75
kvoKlinger Oscillatorfast: 34, slow: 55, signal: 13KVO, Signal0
fisherFisher Transformperiod: 9Fisher, Trigger0
dpoDetrended Price Oscillator· sourceperiod: 20, source: "close"DPO—
bopBalance of Powersmooth: 14BOP0
massindexMass Indexema: 9, sum: 25Mass26.5, 27
cmoChande Momentum· sourceperiod: 9, source: "close"CMO-50, 0, 50
trixTRIX· sourceperiod: 15, signal: 9, source: "close"TRIX, Signal0
emvEase of Movementperiod: 14EOM0
pvtPrice Volume Trend—PVT—
wadWilliams A/D—WAD—
chaikinvolChaikin Volatilityema: 10, roc: 10CV0
rviRelative Vigor Indexperiod: 10RVGI, Signal0
stochrsiStochastic RSI· sourcersiPeriod: 14, stochPeriod: 14, k: 3, d: 3, source: "close"%K, %D20, 80
ppoPercentage Price Oscillator· sourcefast: 12, slow: 26, signal: 9, source: "close"Histogram, PPO, Signal0
acAccelerator Oscillator—AC—
rmiRelative Momentum Index· sourceperiod: 20, momentum: 5, source: "close"RMI30, 70
disparityDisparity Index· sourceperiod: 14, source: "close"DI0
qstickQstickperiod: 8Qstick0
pgoPretty Good Oscillatorperiod: 14PGO-3, 0, 3
bbpbBollinger Bands %B· sourceperiod: 20, stdDev: 2, source: "close"%B0, 0.5, 1
bbwBollinger BandWidth· sourceperiod: 20, stdDev: 2, source: "close"BBW—
momMomentum· sourceperiod: 10, source: "close"MOM0
hvHistorical Volatility· sourceperiod: 10, annual: 365, source: "close"HV—
voVolume Oscillatorshort: 5, long: 10Vol Osc0
ulcerUlcer Index· sourceperiod: 14, source: "close"Ulcer—
smiStochastic Momentum Indexperiod: 10, smooth: 3, signal: 3SMI, Signal40, -40
rvixRelative Volatility Indexperiod: 10, smooth: 14RVI80, 50, 20
trendstrengthTrend Strength Indexperiod: 14Trend0
lrslopeLinear Regression Slopeperiod: 14Slope0
stderrorStandard Errorperiod: 14StdErr—
adrAverage Day Rangeperiod: 14ADR—
netvolumeNet Volume—Net0
asiAccumulative Swing Indexlimit: 10ASI—
advdeclineAdvance/Declinelength: 10Ratio—
majorityMajority Ruleperiod: 14Majority50
chopzoneChop Zone—Angle—
smiergodicSMI Ergodic· sourceshort: 5, long: 20, signal: 5, source: "close"Oscillator, Indicator, Signal—
poPrice Oscillator· sourceshort: 10, long: 21, source: "close"PO—
volohlcVolatility O-H-L-Cperiod: 10, annual: 365Volatility—
volztVolatility Zero Trend Close-to-Closeperiod: 10, annual: 365Volatility—
psyPsychological Lineperiod: 10PSY25, 75
newpsyNew Psychological Lineperiod: 10New PSY-50, 0, 50
vrVolume Ratioperiod: 20VR70, 150, 450
abratioAB Ratioperiod: 26A, B100
sonarSonarperiod: 20, lookback: 9, signal: 9Sonar, Signal0
sigmaSigmaperiod: 20Sigma-2, 0, 2
vhfVertical Horizontal Filterperiod: 28VHF—
rsquaredR-Squaredperiod: 14R²—
rwiRandom Walk Indexperiod: 14RWI High, RWI Low1
nviNegative Volume Indexsignal: 255NVI, Signal—
pviPositive Volume Indexsignal: 255PVI, Signal—
trTrue Range—TR—
iiiIntraday Intensityperiod: 21III %0
volpctVolume vs Averageperiod: 20Vol %0
volchangeVolume Change—Volume—
tradevalueTrade Value—Value—
binarywaveBinary Wavema: 20, fast: 12, slow: 26, signal: 9, roc: 12, stoch: 14Wave0
srocSmoothed Rate of Changeema: 13, roc: 21S-ROC0
rsidivRSI Divergenceperiod: 14, left: 5, right: 5, minBars: 5, maxBars: 60, hidden: 0RSI, Bullish, Bearish30, 70

voldelta (Volume Delta) is what the buyers took of each bar less what the sellers did. A bar that says who took its trades (its buyVolume) gives its true delta. One that does not is read from the way it closed: all its volume up when it closed at or over its open, down otherwise, which is the nearest an OHLCV bar comes. mode: 0 is the per-bar histogram, mode: 1 the cumulative delta, which starts again with each anchor period ('session', 'week' or 'month'; never with 'all', the default).

Indicators from Asian price boards

Indicators that traders in Korea, Japan and Vietnam expect on their price boards: the Psychological Line (psy) and the New Psychological Line (newpsy), Volume Ratio (vr), AB Ratio (abratio), sonar, sigma, Binary Wave (binarywave), Trade Value (tradevalue) with Volume Change (volchange), the DeMark projected range (demark) and a moving-average rainbow of up to 20 lines. Trade Value is an estimate, close × volume per bar; the exchange's own figure comes from its feed.

chart.addIndicator('psy', { period: 10 }, 'bottom')              // share of up closes; 25 and 75 marked
chart.addIndicator('vr', { period: 20 }, 'bottom')                // volume of up days against down days
chart.addIndicator('tradevalue', {}, 'bottom')                    // close × volume, each bar
chart.addIndicator('rainbow', { first: 10, step: 10, count: 10 }) // ten averages, 10 to 100 bars

Candlestick patterns

64 patterns from one to five bars: dojis, hammers and shooting stars, marubozu and belt holds; engulfing bars, harami, piercing lines and dark clouds, tweezers, kicking; morning and evening stars, abandoned babies, three soldiers and crows, three inside and outside, tasuki gaps; three-line strikes, three methods, mat holds, breakaways and ladder bottoms. A reversal counts only after the trend it reverses (the close before it past both its 10-bar average and the close 10 bars back, trendPeriod), and a body is long or short against the average body of the bars before. The indicator draws an arrow under a bullish pattern and over a bearish one, with its short name once the bars are wide enough; a bar that ends several shows the longest. reversal, continuation and indecision (1 or 0) choose the kinds.

chart.addIndicator('candlepatterns')                  // an arrow and the name on each bar that ends one
chart.addIndicator('candlepatterns', { indecision: 1 }) // dojis and spinning tops too

import { detectCandlePatterns, CANDLE_PATTERNS } from '@tradecanvas/chart'

const found = detectCandlePatterns(bars, { patterns: ['bullishEngulfing', 'hammer'] })
// [{ index, time, pattern: { id, name, short, direction, kind, bars } }]
CANDLE_PATTERNS.length                                 // 64

A page that finds patterns and draws no chart (a scanner, a screener) imports the two from @tradecanvas/core/patterns: the detector alone, about 4 kB gzipped, in a chunk of its own, so the page does not load the chart's engine even when other pages of the app do. List @tradecanvas/core in the app's dependencies to import it.

import { detectCandlePatterns, CANDLE_PATTERNS } from '@tradecanvas/core/patterns'

Fair value gaps

Three bars leave a fair value gap where the third bar's low is over the first bar's high (or, going down, its high under the first bar's low): between the two, only the middle bar traded. The chart draws a box over those prices, from the middle bar to the right edge while the gap is open, teal for a gap going up and pink for a gap going down (the colours of the candlestick patterns' marks, kept apart from the candles' green and red; the indicator's style changes them). A gap is filled by the first later bar that trades through all of it, and is then taken off the chart unless showFilled is 1. detectFairValueGaps gives them all with no chart, with the bar that filled each.

chart.addIndicator('fvg')                              // a box over each gap still open
chart.addIndicator('fvg', { minPercent: 0.1 })         // leave out gaps under 0.1% of the price
chart.addIndicator('fvg', { showFilled: 1 })           // keep the filled ones, fainter, to the bar that filled them

import { detectFairValueGaps } from '@tradecanvas/chart'

detectFairValueGaps(bars, { minPercent: 0.1 })
// [{ index, formed, direction: 'up' | 'down', top, bottom, filledAt }]

Divergences

A divergence is the price and an oscillator turning twice and not the same way. Bullish, at two lows: the price makes a lower low and the oscillator a higher one. Bearish, at two highs: the price makes a higher high and the oscillator a lower one. rsidiv is the RSI with a line between its two turns at each divergence and a mark at the second; hidden: 1 adds the hidden ones (the price holds, the RSI does not), dashed. A turn stands out from left bars before it and right bars after, so a divergence is known right bars late and, once the bar that confirms it has closed, does not change (on that bar, still forming, it can come and go); the two turns are minBars to maxBars apart. detectDivergences(bars, line, options) reads any line with one value a bar (null where it has none) and needs no chart.

chart.addIndicator('rsidiv', {}, 'bottom')                    // the RSI, its divergences marked
chart.addIndicator('rsidiv', { hidden: 1 }, 'bottom')         // the hidden ones too, dashed
chart.addIndicator('rsidiv', { left: 3, right: 3 }, 'bottom') // nearer turns: known 3 bars late, and more of them

import { detectDivergences } from '@tradecanvas/chart'

detectDivergences(bars, macdHistogram, { left: 5, right: 5, minBars: 5, maxBars: 60, hidden: true })
// [{ kind: 'bullish' | 'bearish', hidden, from, to, confirmed, valueFrom, valueTo, priceFrom, priceTo }]

Session volume profile

svp draws each trading day's volume by price: the day's range split into rows, each bar's volume shared by the rows its range covers, drawn as rows growing right from the day's first bar. Over them, the day's point of control (the busiest row) and its value area (the rows around it holding valueArea percent of the day's volume, 70 by default, taken on two rows at a time from the heavier side, as Market Profile counts it) are lines across the day. A day starts at midnight on the exchange's clock (setExchangeTimeZone), as Session VWAP's does. Each bar's poc, vah and val are its whole day's, the bars after it included: on a past day a morning bar carries the day's closing profile, and on the day still trading they move as it trades. They are for reading a day, not for signals or a backtest at that bar. volumeProfile is one profile of every bar loaded; sessionVolumeProfiles gives the days' rows with no chart.

chart.addIndicator('svp')                           // a profile a day, with its POC and value area
chart.addIndicator('svp', { rows: 40, valueArea: 68 }) // finer rows, a narrower value area

import { sessionVolumeProfiles } from '@tradecanvas/chart'

sessionVolumeProfiles(bars, { rows: 24, valueArea: 70, timeZone: 'America/New_York' })
// [{ start, end, time, low, high, rowHeight, volumes, total, poc, valueAreaLow, valueAreaHigh, valueAreaRows }]

Order blocks

A swing high is a bar higher than the length bars before it and no lower than the length after (5), so it is known length bars late; a swing low the same way down. When a close goes over the latest swing high not yet broken, the lowest bar between the swing and that close is a bullish order block, its high to its low; a close under the latest swing low makes the highest bar between a bearish one. A swing makes one block. orderblocks draws each as a box, in the colours of fair value gaps, to the right edge while it stands; a close through it (under a bullish block, over a bearish one) breaks it and takes it off, unless showBroken is 1. Only the latest count standing blocks of each side are drawn (5; 0 for all): older far ones only clutter. detectOrderBlocks gives them all with no chart, with the bar that broke each.

chart.addIndicator('orderblocks')                    // the blocks standing
chart.addIndicator('orderblocks', { count: 3 })        // the latest three a side
chart.addIndicator('orderblocks', { length: 3 })       // shorter swings: more blocks, known sooner
chart.addIndicator('orderblocks', { showBroken: 1 })   // the broken ones too, fainter, to the bar that broke them

import { detectOrderBlocks } from '@tradecanvas/chart'

detectOrderBlocks(bars, { length: 5 })
// [{ kind: 'bullish' | 'bearish', index, formed, top, bottom, swing, brokenAt }]

Your own indicator

The short way is defineIndicator: its inputs, and one function that returns its lines from the bars, with ta for the sums (ta.ema, ta.rsi, ta.crossover…).

import { defineIndicator } from '@tradecanvas/chart'

chart.registerIndicator(defineIndicator({
  id: 'smoothRsi',
  name: 'Smoothed RSI',
  inputs: { period: { default: 14, kind: 'int', min: 2 }, smooth: { default: 5, kind: 'int', min: 1 } },
  scale: { min: 0, max: 100 },
  levels: [30, 70],
  calculate: ({ bars, inputs, ta }) => ({ value: ta.ema(ta.rsi(bars.close, inputs.period), inputs.smooth) }),
}))
chart.addIndicator('smoothRsi')

For an indicator that keeps up with ticks on a long history, or draws something of its own, extend IndicatorBase and declare what it draws (plots), its pane scale, levels and inputs; the chart draws it, scales its pane, tags its values and lists it in the widget's legend and settings without rendering code of yours. Its category ('oscillators', 'volume'…) puts it in that group of the Indicators dialog; without one it is under Other. A group of your own, { id: 'my-app', label: 'My App' }, lists your app's indicators together under its name, before the built-in kinds. See the custom indicator recipe. An indicator that groups bars by day, week or month reads the exchange's zone as config.exchangeTimeZone (set by the chart; unset: UTC). A new zone computes again only the indicators that read it and those that read their lines: one of yours that doesn't can say readsExchangeTimeZone: false in its descriptor, and is left as it is. The chart's interval is config.interval (unset: not known); one whose values depend on it says readsInterval: true, and is computed again when it changes.

Each input's kind ('int', 'number', 'boolean', 'choice', 'source', 'color', 'text') and its min, max and step decide its field in the settings: an 'int' is rounded as it is typed, as a period is read. Without a kind it is read from the default (a number is a 'number': only a declared 'int' is rounded). describeInputs(descriptor) lists the inputs as the settings dialog, these docs and the MCP server read them.

inputs: {
  period: { kind: 'int', min: 2, max: 500 },
  mult: { kind: 'number', min: 0.1, step: 0.1 },
  source: { source: true },
  type: { kind: 'choice', options: [{ value: 'ema', label: 'Exponential' }, { value: 'sma', label: 'Simple' }] },
}

A choice's options are values, or values with the label the settings show for them ({ value, label }), in your app's language; the indicator is given the value.

The descriptor also says how its plots look, and the chart draws them so: fills shade between two plots where both have a value, under the lines; a plot's width keeps it at that width whatever the indicator's (a thin middle line); lineStyle dashes it until its style says otherwise, and the settings show and restore that dash; opacity sets it back; breakOn names a field that numbers periods, and the line breaks where it changes. The built-in channels, bands, Supertrend and Parabolic SAR are drawn this way.

plots: [
  { key: 'upper', title: 'Upper', color: 0 },
  { key: 'middle', title: 'Basis', color: 1, width: 1, lineStyle: 'dashed' },
  { key: 'lower', title: 'Lower', color: 0 },
],
fills: [{ between: ['upper', 'lower'], color: 0, opacity: 0.1 }],

A plot of kind: 'markers' marks the bars where its field has a value (a turn, a signal) with a shape ('triangleUp', 'triangleDown', 'arrowUp', 'arrowDown', 'dot', 'square' or 'diamond'), at the value or, on the price pane, above the bar's high or below its low (position: 'aboveBar', 'belowBar'). It is not a value to read: it gets none in the legend, no tag on the axis and no column in an export, and is not offered as a line another indicator can read. In a pane, its marks are at their values. Leave the field unset on the bars without a mark.

Its marks are as wide as the bars allow, 4 to 8 px. A viewer picks another shape and a size in the indicator's Style tab, and code sets them in the plot's style: shape, and size in pixels across (2 to 40) or 'auto'. Williams Fractals is drawn this way: a triangle above a high and one below a low.

chart.updateIndicatorStyle(fractals, { plots: { up: { shape: 'arrowUp', size: 14 }, down: { size: 'auto' } } });
plots: [
  { key: 'value', title: 'MACD', color: 0 },
  { key: 'turn', title: 'Turn', color: 1, kind: 'markers', shape: 'triangleUp', position: 'belowBar' },
],

Panes: resize, fold, maximise, reorder

Drag the divider above a pane to resize it. In ChartWidget each pane has buttons at its top right: move it up or down, fold it to its header, maximise it (the other panes fold and the price pane keeps a strip). Saved layouts keep each pane's size, order, fold and maximise. The same from code:

chart.setPanelSize(rsi, 180)        // px, clamped to a minimum
chart.setPaneCollapsed(macd, true)  // fold to its header
chart.setMaximizedPane(rsi)         // null puts the panes back
chart.movePane(rsi, -1)             // one place up; 1 = down
chart.on('paneChange', (e) => e.payload.change)  // 'collapsed' | 'maximized' | 'order' | 'scale'
chart.setPaneScale(atr, { log: true, invert: false })  // log while its values are above 0
chart.setPaneScale(atr, { percent: true })             // labels in percent of its first value on screen

Right-click a pane in ChartWidget for its own logarithmic, inverted or percent scale.

Moving an indicator to another pane

An indicator can join another indicator's pane (it then shares that pane's scale), take a pane of its own, or go back to the price pane. When it leaves a pane it owned, the others in it stay (the next pane indicator takes the pane over), and those reading its lines follow it. In ChartWidget, the ⋯ button on a legend row offers the pane above, the pane below, a new pane and the price pane.

chart.moveIndicatorToPane(cci, rsi)      // into RSI's pane
chart.moveIndicatorToPane(cci, 'new')    // a pane of its own
chart.moveIndicatorToPane(ema, 'price')  // an overlay back to the price pane
chart.canMoveIndicatorToPane(cci, rsi)   // whether it would move

Undo, and templates

Adding, removing, editing and moving indicators are undo steps in the same history as drawings (Ctrl/⌘ Z, Ctrl/⌘ Shift Z); an undone indicator comes back under its own id, so alerts on its lines still match. A burst of edits to one indicator (a colour dragged, a period typed) is one step. A loaded layout starts a fresh history.

The indicators can be taken and put back as a whole, which is what ChartWidget's indicator templates do: Save indicators as template… on the Templates tab of the Indicators dialog keeps them (inputs, style, levels, panes) under a name, and picking a template puts them in place of the chart's, as one undo step.

const setup = chart.getIndicatorSetup()   // what a layout keeps of them
chart.applyIndicatorSetup(setup)          // in place of the chart's indicators

new ChartWidget(host, { indicatorTemplates: true })  // the default

Computing outside the chart

IndicatorWorkerHost computes an indicator from bars in the worker the package ships (createIndicatorWorker()), the one the chart uses with indicatorWorker: 'auto'. Pass null instead and register the plugins to compute in place (SSR, tests, scripts):

import { IndicatorWorkerHost, RSIIndicator, createIndicatorWorker } from '@tradecanvas/core'

const config = { id: 'rsi', instanceId: 'rsi-1', params: { period: 14 } }

const inWorker = new IndicatorWorkerHost(await createIndicatorWorker())
const output = await inWorker.calculate('rsi', config, bars)

const inPlace = new IndicatorWorkerHost(null)
inPlace.registerFallbackPlugin(new RSIIndicator())
const same = await inPlace.calculate('rsi', config, bars)