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)
| id | Name | Default params | Lines |
|---|---|---|---|
sma | Simple Moving Average· source | period: 20, source: "close" | SMA |
ema | Exponential Moving Average· source | period: 20, source: "close" | EMA |
bb | Bollinger Bands· source | period: 20, stdDev: 2, source: "close" | Upper, Basis, Lower |
vwap | Volume Weighted Average Price | anchor: "session" | VWAP |
ichimoku | Ichimoku Cloud | tenkan: 9, kijun: 26, senkou: 52, displacement: 26 | Conversion, Base, Lead A, Lead B, Lagging Span |
psar | Parabolic SAR | step: 0.02, max: 0.2 | SAR |
supertrend | Supertrend | period: 10, multiplier: 3 | Supertrend |
keltner | Keltner Channel | emaPeriod: 20, atrPeriod: 10, multiplier: 1.5 | Upper, Basis, Lower |
donchian | Donchian Channel | period: 20 | Upper, Basis, Lower |
pivots | Pivot Points | lookback: 24, type: "traditional" | R3, R2, R1, P, S1, S2, S3 |
avwap | Anchored VWAP | anchorTime: 0 | AVWAP |
zigzag | ZigZag | deviation: 5 | Pivot |
lrc | Linear Regression Channel· source | period: 100, stdDev: 2, source: "close" | Upper, Basis, Lower |
hma | Hull Moving Average· source | period: 21, source: "close" | HMA |
mtfma | MTF Moving Average· source | period: 50, timeframe: "1d", source: "close" | MA |
svwap | Session VWAP | bands: 1 | VWAP, +1σ, −1σ, +2σ, −2σ, +3σ, −3σ |
chandelier | Chandelier Exit | period: 22, multiplier: 3 | Long, Short |
alligator | Alligator | jaw: 13, teeth: 8, lips: 5, jawShift: 8, teethShift: 5, lipsShift: 3 | Jaw, Teeth, Lips |
vwma | Volume Weighted Moving Average· source | period: 20, source: "close" | VWMA |
wma | Weighted Moving Average· source | period: 20, source: "close" | WMA |
envelope | Moving Average Envelope· source | period: 20, percent: 2.5, source: "close" | Upper, Basis, Lower |
tema | Triple EMA· source | period: 20, source: "close" | TEMA |
volumeProfile | Volume Profile | rows: 24 | — |
dema | Double Exponential Moving Average· source | period: 20, source: "close" | DEMA |
smma | Smoothed Moving Average· source | period: 14, source: "close" | SMMA |
alma | Arnaud Legoux Moving Average· source | period: 9, offset: 0.85, sigma: 6, source: "close" | ALMA |
kama | Kaufman Adaptive Moving Average· source | period: 10, fast: 2, slow: 30, source: "close" | KAMA |
lsma | Least Squares Moving Average· source | period: 25, offset: 0, source: "close" | LSMA |
mcginley | McGinley Dynamic· source | period: 14, source: "close" | McGinley |
macross | MA Cross· source | fast: 9, slow: 21, type: "sma", source: "close" | Fast, Slow |
fractals | Williams Fractals | period: 2 | Up, Down |
cks | Chande Kroll Stop | p: 10, x: 1, q: 9 | Stop Long, Stop Short |
seb | Standard Error Bands | period: 21, mult: 2, smooth: 3 | Upper, Middle, Lower |
gmma | Guppy 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 |
maribbon | Moving Average Ribbon | ma1: 20, ma2: 50, ma3: 100, ma4: 200, exponential: 0 | MA 1, MA 2, MA 3, MA 4 |
avgprice | Average Price | — | Average |
medprice | Median Price | — | Median |
typprice | Typical Price | — | Typical |
machannel | Moving Average Channel | upperLength: 20, lowerLength: 20, upperOffset: 0, lowerOffset: 0 | Upper, Lower |
hamming | Moving Average Hamming· source | period: 10, source: "close" | MA |
madouble | Moving Average Double· source | first: 20, second: 50, type: "sma", source: "close" | MA 1, MA 2 |
matriple | Moving Average Triple· source | first: 10, second: 20, third: 50, type: "sma", source: "close" | MA 1, MA 2, MA 3 |
volindex | Volatility Index | period: 7, mult: 3 | Stop |
tsf | Time Series Forecast | period: 14 | TSF |
wclose | Weighted Close | — | Weighted |
demark | DeMark Projected Range | — | Projected high, Projected low |
rainbow | Moving Average Rainbow | first: 10, step: 10, count: 10, exponential: 0 | MA 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 |
candlepatterns | Candlestick Patterns | trendPeriod: 10, reversal: 1, continuation: 1, indecision: 0 | Bullish, Bearish, Indecision |
fvg | Fair Value Gaps | minPercent: 0, showFilled: 0 | Bullish top, Bullish bottom, Bearish top, Bearish bottom |
svp | Session Volume Profile | rows: 24, valueArea: 70 | POC, VAH, VAL |
orderblocks | Order Blocks | length: 5, showBroken: 0, count: 5 | Bullish 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)
| id | Name | Default params | Lines | Levels |
|---|---|---|---|---|
rsi | Relative Strength Index· source | period: 14, source: "close" | RSI | 30, 70 |
macd | MACD· source | fast: 12, slow: 26, signal: 9, source: "close" | Histogram, MACD, Signal | — |
stochastic | Stochastic Oscillator | kPeriod: 14, dPeriod: 3, smooth: 3 | %K, %D | 20, 80 |
atr | Average True Range | period: 14 | ATR | — |
adx | Average Directional Index | period: 14 | ADX, +DI, −DI | — |
obv | On Balance Volume | — | OBV | — |
williamsR | Williams %R | period: 14 | %R | -80, -20 |
cci | Commodity Channel Index | period: 20 | CCI | -100, 0, 100 |
mfi | Money Flow Index | period: 14 | MFI | 20, 80 |
aroon | Aroon | period: 25 | Up, Down | — |
roc | Rate of Change· source | period: 12, source: "close" | ROC | 0 |
tsi | True Strength Index· source | longPeriod: 25, shortPeriod: 13, signalPeriod: 7, source: "close" | TSI, Signal | 0 |
cmf | Chaikin Money Flow | period: 20 | CMF | — |
stddev | Standard Deviation· source | period: 20, source: "close" | StdDev | — |
ad | Accumulation/Distribution | — | A/D | — |
vroc | Volume Rate of Change | period: 14 | VROC | 0 |
ao | Awesome Oscillator | fast: 5, slow: 34 | AO | — |
chaikinOsc | Chaikin Oscillator | fast: 3, slow: 10 | Chaikin | — |
voldelta | Volume Delta | mode: 0, anchor: "all" | Delta | — |
vortex | Vortex Indicator | period: 14 | VI+, VI− | 1 |
chop | Choppiness Index | period: 14 | CHOP | 38.2, 61.8 |
uo | Ultimate Oscillator | fast: 7, mid: 14, slow: 28 | UO | 30, 70 |
fi | Force Index | period: 13 | EFI | 0 |
crsi | Connors RSI· source | rsiPeriod: 3, streakPeriod: 2, rankPeriod: 100, source: "close" | CRSI | 10, 90 |
coppock | Coppock Curve· source | longRoc: 14, shortRoc: 11, wma: 10, source: "close" | Coppock | 0 |
kst | Know Sure Thing· source | roc1: 10, roc2: 15, roc3: 20, roc4: 30, sma1: 10, sma2: 10, sma3: 10, sma4: 15, signal: 9, source: "close" | KST, Signal | 0 |
elderray | Elder Ray | period: 13 | Bull, Bear | — |
stc | Schaff Trend Cycle· source | fast: 23, slow: 50, cycle: 10, source: "close" | STC | 25, 75 |
kvo | Klinger Oscillator | fast: 34, slow: 55, signal: 13 | KVO, Signal | 0 |
fisher | Fisher Transform | period: 9 | Fisher, Trigger | 0 |
dpo | Detrended Price Oscillator· source | period: 20, source: "close" | DPO | — |
bop | Balance of Power | smooth: 14 | BOP | 0 |
massindex | Mass Index | ema: 9, sum: 25 | Mass | 26.5, 27 |
cmo | Chande Momentum· source | period: 9, source: "close" | CMO | -50, 0, 50 |
trix | TRIX· source | period: 15, signal: 9, source: "close" | TRIX, Signal | 0 |
emv | Ease of Movement | period: 14 | EOM | 0 |
pvt | Price Volume Trend | — | PVT | — |
wad | Williams A/D | — | WAD | — |
chaikinvol | Chaikin Volatility | ema: 10, roc: 10 | CV | 0 |
rvi | Relative Vigor Index | period: 10 | RVGI, Signal | 0 |
stochrsi | Stochastic RSI· source | rsiPeriod: 14, stochPeriod: 14, k: 3, d: 3, source: "close" | %K, %D | 20, 80 |
ppo | Percentage Price Oscillator· source | fast: 12, slow: 26, signal: 9, source: "close" | Histogram, PPO, Signal | 0 |
ac | Accelerator Oscillator | — | AC | — |
rmi | Relative Momentum Index· source | period: 20, momentum: 5, source: "close" | RMI | 30, 70 |
disparity | Disparity Index· source | period: 14, source: "close" | DI | 0 |
qstick | Qstick | period: 8 | Qstick | 0 |
pgo | Pretty Good Oscillator | period: 14 | PGO | -3, 0, 3 |
bbpb | Bollinger Bands %B· source | period: 20, stdDev: 2, source: "close" | %B | 0, 0.5, 1 |
bbw | Bollinger BandWidth· source | period: 20, stdDev: 2, source: "close" | BBW | — |
mom | Momentum· source | period: 10, source: "close" | MOM | 0 |
hv | Historical Volatility· source | period: 10, annual: 365, source: "close" | HV | — |
vo | Volume Oscillator | short: 5, long: 10 | Vol Osc | 0 |
ulcer | Ulcer Index· source | period: 14, source: "close" | Ulcer | — |
smi | Stochastic Momentum Index | period: 10, smooth: 3, signal: 3 | SMI, Signal | 40, -40 |
rvix | Relative Volatility Index | period: 10, smooth: 14 | RVI | 80, 50, 20 |
trendstrength | Trend Strength Index | period: 14 | Trend | 0 |
lrslope | Linear Regression Slope | period: 14 | Slope | 0 |
stderror | Standard Error | period: 14 | StdErr | — |
adr | Average Day Range | period: 14 | ADR | — |
netvolume | Net Volume | — | Net | 0 |
asi | Accumulative Swing Index | limit: 10 | ASI | — |
advdecline | Advance/Decline | length: 10 | Ratio | — |
majority | Majority Rule | period: 14 | Majority | 50 |
chopzone | Chop Zone | — | Angle | — |
smiergodic | SMI Ergodic· source | short: 5, long: 20, signal: 5, source: "close" | Oscillator, Indicator, Signal | — |
po | Price Oscillator· source | short: 10, long: 21, source: "close" | PO | — |
volohlc | Volatility O-H-L-C | period: 10, annual: 365 | Volatility | — |
volzt | Volatility Zero Trend Close-to-Close | period: 10, annual: 365 | Volatility | — |
psy | Psychological Line | period: 10 | PSY | 25, 75 |
newpsy | New Psychological Line | period: 10 | New PSY | -50, 0, 50 |
vr | Volume Ratio | period: 20 | VR | 70, 150, 450 |
abratio | AB Ratio | period: 26 | A, B | 100 |
sonar | Sonar | period: 20, lookback: 9, signal: 9 | Sonar, Signal | 0 |
sigma | Sigma | period: 20 | Sigma | -2, 0, 2 |
vhf | Vertical Horizontal Filter | period: 28 | VHF | — |
rsquared | R-Squared | period: 14 | R² | — |
rwi | Random Walk Index | period: 14 | RWI High, RWI Low | 1 |
nvi | Negative Volume Index | signal: 255 | NVI, Signal | — |
pvi | Positive Volume Index | signal: 255 | PVI, Signal | — |
tr | True Range | — | TR | — |
iii | Intraday Intensity | period: 21 | III % | 0 |
volpct | Volume vs Average | period: 20 | Vol % | 0 |
volchange | Volume Change | — | Volume | — |
tradevalue | Trade Value | — | Value | — |
binarywave | Binary Wave | ma: 20, fast: 12, slow: 26, signal: 9, roc: 12, stoch: 14 | Wave | 0 |
sroc | Smoothed Rate of Change | ema: 13, roc: 21 | S-ROC | 0 |
rsidiv | RSI Divergence | period: 14, left: 5, right: 5, minBars: 5, maxBars: 60, hidden: 0 | RSI, Bullish, Bearish | 30, 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)