Quick reference
A quick reference guide for creating custom studies in DXcharts.
Basic template
__CHART_REACT_API.addCustomStudy({
name: 'My Indicator',
metainfo: {
id: 'MY_INDICATOR',
title: 'My Indicator',
overlaying: true, // true = overlay, false = separate pane
precision: 2, // optional; defaults to instrument precision
parameters: [{ id: 'length', title: 'Length', type: 'INTEGER_RANGE', defaultValue: 14, min: 1, max: 500 }],
lines: [{ id: 'output', title: 'Output', type: 'LINEAR', color: '#2962FF', thickness: 2 }],
},
constructor: {
main: function (ctx) {
const input = ctx.input;
const state = ctx.state;
const index = ctx.index;
if (!state.data) {
state.data = [];
}
const value = input.close(0);
state.data[index] = value;
// Your calculation here
return [value];
},
},
});
Set precision in metainfo to control the number of decimal places for the
indicator. If omitted, the current instrument precision is used.
Parameter types
| Type | Description | Example |
|---|---|---|
INTEGER_RANGE | Integer with min/max | { type: 'INTEGER_RANGE', defaultValue: 14, min: 1, max: 500 } |
DOUBLE_RANGE | Floating point with min/max | { type: 'DOUBLE_RANGE', defaultValue: 2.0, min: 0.1, max: 10, precision: 2 } |
BOOLEAN | True/false toggle | { type: 'BOOLEAN', defaultValue: true } |
STRING | Text input | { type: 'STRING', defaultValue: 'CLOSE' } |
ENUM | Predefined options | { type: 'ENUM', defaultValue: 'SMA', options: ['SMA', 'EMA', 'WMA'] } |
COLOR | Color picker | { type: 'COLOR', defaultValue: '#2962FF' } |
DATE | Calendar date (YYYYMMDD) | { type: 'DATE', defaultValue: '20240101' } or '-1' (today) |
TIME | Time of day (HHMM) | { type: 'TIME', defaultValue: '0930' } |
Parameter options: group (settings section title), visible (show/hide)
Line types
| Type | Description |
|---|---|
LINEAR | Continuous line |
POINTS | Point markers |
HISTOGRAM | Vertical bars from zero |
TREND_HISTOGRAM | Histogram colored by trend |
DIFFERENCE | Area between two lines |
LINEAR_TREND | Line colored by trend |
TREND_POINTS | Points colored by trend |
ABOVE_CANDLE_TEXT | Text above candles |
BELOW_CANDLE_TEXT | Text below candles |
COLOR_CANDLE | Colors candles |
UNIVERSAL_MARKER | Universal drawer (marker + line) |
VERTICAL_LINE | Vertical line at candle time |
Per-candle styling: return [{ value: 42, color: '#FF0000', fillColor: '#FF000033', text: 'Signal', markerStyle: 'DOT', lineStyle: 'SOLID', timeAnchor: 'center' }]
Init function
constructor: {
init: function(ctx) {
ctx.requestSecondaryData('daily', { period: { duration: 1, durationType: 'd' } });
return {
recalcCandles: 50, // or 'all' for full recalculation
displaces: [0, 26], // one shift per output line (candles backward on time axis)
expansionCandles: 20, // maximum 100
};
},
main: function(ctx) { /* ... */ },
}
Context API
export interface CustomStudyContext {index: number;candlesCount: number;input: CustomStudyInputAccessors;parameters: Record<string, unknown>;state: Record<string, unknown>;utils: CustomStudyUtils;drawings: CustomStudyDrawings;alert: CustomStudyAlertFn;chart: CustomStudyChartInfo;requestSecondaryData: (id: string, options?: SecondaryDataOptions) => void;secondaryData: (id: string) => CustomStudyInputAccessors;getSecondaryIndex: (id: string) => number;events: Event[];news: News[];sessions: TradingSession[];}
Price data
// Basic OHLCV (offset = 0 means current, 1 means previous, etc.)
const close = input.close(0); // Current close
const open = input.open(1); // Previous open
const high = input.high(0); // Current high
const low = input.low(0); // Current low
const volume = input.volume(0); // Current volume
// Timestamp
const time = input.time(0); // Candle timestamp (milliseconds)
// Advanced market data (may be undefined)
const vwap = input.vwap(0); // Volume Weighted Average Price
const openInterest = input.openInterest(0); // Open Interest
const impVol = input.impVolatility(0); // Implied Volatility
// Price helpers
const median = input.median(0); // (high + low) / 2
const typical = input.typical(0); // (high + low + close) / 3
const ohlcAvg = input.ohlcAverage(0); // (open + high + low + close) / 4
// Generic price accessor (works with PRICE_FIELD parameters)
const price = input.getPrice('CLOSE', 0);
const price = input.getPrice('TYPICAL', 0);
// Types: 'OPEN', 'HIGH', 'LOW', 'CLOSE', 'VOLUME', 'MEDIAN', 'TYPICAL', 'OHLC_AVERAGE'
// Chart information
const symbol = ctx.chart.symbol; // Current symbol
const period = ctx.chart.period; // Period in minutes
const mintick = ctx.chart.mintick; // Minimum price movement
// Secondary data (request in init(), access in main())
// In init():
ctx.requestSecondaryData('eurusd', { symbol: 'EUR/USD' });
ctx.requestSecondaryData('daily', { period: { duration: 1, durationType: 'd' } });
ctx.requestSecondaryData('hourly', { period: { duration: 1, durationType: 'h' } });
// In main():
const eurusdClose = ctx.secondaryData('eurusd').close(0);
const dailyClose = ctx.secondaryData('daily').close(0);
const secondaryIndex = ctx.getSecondaryIndex('eurusd');
// Trading sessions
const sessions = ctx.sessions; // Array of {from, to, type}
const regularSessions = sessions.filter(s => s.type === 'REGULAR');
const hasRegularSession = sessions.some(s => s.type === 'REGULAR');
// Session types: 'REGULAR' | 'PRE_MARKET' | 'AFTER_MARKET' | 'NO_TRADING'
Events and news
// Events: earnings, dividends, splits, conference-calls
const events = ctx.events; // Event[]
const earnings = events.filter(e => e.kind === 'earnings');
const splits = events.filter(e => e.kind === 'splits');
// News
const news = ctx.news; // News[] (title, timestamp, sourceLink)
// Find events/news near the current candle
const candleTime = ctx.input.time(0);
const dayMs = 24 * 60 * 60 * 1000;
const nearby = events.filter(e => Math.abs(e.timestamp - candleTime) < dayMs);
For detailed documentation on event types and examples, see Events and news data.
Graphics and alerts
// Persistent managed primitives (store IDs in ctx.state)
const lineId = ctx.drawings.line.new(x1, y1, x2, y2, { xloc: 'bar_index', extend: 'right' });
const boxId = ctx.drawings.box.new(left, top, right, bottom, { bgColor: '#2962FF33' });
const labelId = ctx.drawings.primitiveLabel.new(x, y, 'Text', { yloc: 'abovebar' });
// Per-bar graphics
ctx.drawings.label(visible, 'Signal', '#2962FF', 'ABOVE');
ctx.drawings.bubble(visible, price, 'Signal', '#2962FF');
ctx.drawings.plotcandle(open, high, low, close, { color: '#00A86B' });
// Alerts: ONCE, CANDLE, or TICK; sound NO or BELL
ctx.alert(condition, 'Message', 'CANDLE', 'BELL', 'stable-alert-id');
Managed lines, boxes, and primitive labels default to 50 objects each and are capped at 500. Configure metainfo.maxLinesCount, maxBoxesCount, and maxLabelsCount. See Graphics and alerts.
Common utilities
For complete documentation of all utility functions, see Utility Functions Reference.
Note: Most utility functions accept data as either an array or an accessor function:
// Using array directly
utils.sma(state.prices, 20, index);
// Using accessor function
utils.sma(
function (i) {
return state.prices[i];
},
20,
index,
);
Moving Averages
// Simple MA
utils.sma(data, period, index);
utils.sma(i => data[i], period, index);
// Exponential MA
utils.ema(data, period, index, 'key');
utils.ema(i => data[i], period, index, 'key');
// Weighted MA
utils.wma(data, period, index);
// Running MA
utils.rma(data, period, index, 'key');
Statistics
// Standard deviation
utils.stdev(data, period, index);
// Variance
utils.variance(data, period, index);
// Correlation
utils.correlation(data1, data2, period, index);
Price Analysis
// Max in period
utils.highest(data, period, index);
// Min in period
utils.lowest(data, period, index);
utils.tr(index); // True Range
utils.atr(period, index, 'key'); // Average TR
utils.rsi(data, period, index, 'key'); // Relative Strength Index
Utilities
utils.na(value); // Check if N/A
utils.nz(value, replacement); // Replace N/A
// Value change
utils.change(data, index, period);
// Sum over period
utils.sum(data, period, index);
utils.abs(value); // Absolute value
utils.max(...values); // Maximum
utils.min(...values); // Minimum
utils.avg(...values);
utils.sqrt(value);
utils.pow(base, exponent);
utils.round(value, precision);
utils.cross(data1, data2, index);
utils.cum(data, index, 'key');
utils.dev(data, period, index);
utils.rising(data, period, index);
utils.falling(data, period, index);
utils.highestbars(data, period, index);
utils.lowestbars(data, period, index);
utils.vwma(price, volume, period, index);
utils.stoch(source, high, low, period, index);
utils.dmi(diPeriod, adxPeriod, index, 'key'); // [DI+, DI-, DX, ADX, ADXR]
State Management
main: function(ctx) {
const input = ctx.input;
const utils = ctx.utils;
const state = ctx.state;
const index = ctx.index;
// Initialize arrays on first use
if (!state.prices) {
state.prices = [];
state.emaValues = [];
state.output = [];
}
// Store at current index
state.prices[index] = input.close(0);
// Use unique keys for utils
state.emaValues[index] = utils.ema(function(i) {
return state.prices[i];
}, 9, index, 'ema_unique');
}
Common patterns
Parameter grouping
parameters: [
{ id: 'length', title: 'Length', type: 'INTEGER_RANGE', defaultValue: 14, group: 'inputs' },
{ id: 'lineColor', title: 'Color', type: 'COLOR', defaultValue: '#2962FF', group: 'style' },
],
Simple Moving Average
constructor: {
main: function(ctx) {
const input = ctx.input;
const utils = ctx.utils;
const parameters = ctx.parameters;
const state = ctx.state;
const index = ctx.index;
if (!state.prices) {
state.prices = [];
}
state.prices[index] = input.close(0);
const sma = utils.sma(function(i) {
return state.prices[i];
}, parameters.length, index);
return [sma];
}
}
Exponential Moving Average
constructor: {
main: function(ctx) {
const input = ctx.input;
const utils = ctx.utils;
const parameters = ctx.parameters;
const state = ctx.state;
const index = ctx.index;
if (!state.prices) {
state.prices = [];
}
state.prices[index] = input.close(0);
const ema = utils.ema(function(i) {
return state.prices[i];
}, parameters.length, index, 'ema');
return [ema];
}
}
Bollinger Bands
constructor: {
main: function(ctx) {
const input = ctx.input;
const utils = ctx.utils;
const parameters = ctx.parameters;
const state = ctx.state;
const index = ctx.index;
if (!state.prices) {
state.prices = [];
}
state.prices[index] = input.close(0);
const basis = utils.sma(function(i) {
return state.prices[i];
}, parameters.length, index);
const dev = utils.stdev(function(i) {
return state.prices[i];
}, parameters.length, index);
if (utils.na(basis) || utils.na(dev)) {
return [NaN, NaN, NaN];
}
const upper = basis + parameters.mult * dev;
const lower = basis - parameters.mult * dev;
return [upper, basis, lower];
}
}
Removing studies
__CHART_REACT_API.removeCustomStudy('MY_INDICATOR');
Common errors
-
Not initializing state arrays
// Badmain: function(ctx) { state.prices[index] = value; }// Goodmain: function(ctx) {if (!ctx.state.prices) {ctx.state.prices = [];}} -
Reusing state keys
// Bad - same keyutils.ema(function (i) {return data1[i];},9,index,'ema',);utils.ema(function (i) {return data2[i];},9,index,'ema',);// Good - unique keysutils.ema(function (i) {return data1[i];},9,index,'ema1',);utils.ema(function (i) {return data2[i];},9,index,'ema2',); -
Not checking for N/A
// Badreturn [value1 + value2];// Goodif (utils.na(value1) || utils.na(value2)) {return [NaN];}return [value1 + value2];