Skip to main content

Chart API Reference

The Chart API provides complete control over your financial charts. You can add indicators, draw shapes, manage trading lines, export charts, and much more.

Getting the API

After creating a chart, get the API instance:

// Create the chart
const chart = new Chart({
container: document.getElementById('chart'),
datafeed: yourDataFeed,
symbol: 'AAPL',
interval: '1D'
});

// Get the API
const api = chart.getApi();

// Or wait for chart to be ready
chart.onChartReady(() => {
const api = chart.getApi();
// Use the API here
});

Core Chart Control

Control the basic chart settings like symbol, timeframe, and chart type.

setSymbol(symbol)

Change the symbol displayed on the chart.

Parameters:

  • symbol (SymbolState) - Symbol object with name, description, etc.

Example:

api.setSymbol({
name: 'GOOGL',
full_name: 'Alphabet Inc',
description: 'Alphabet Inc Class C',
type: 'stock',
session: '24x7',
timezone: 'America/New_York',
minmov: 1,
pricescale: 100,
has_intraday: true,
supported_resolutions: ['1', '5', '15', '1D', '1W'],
volume_precision: 2
});

getSymbol()

Get the current symbol.

Returns: SymbolState object

Example:

const symbol = api.getSymbol();
console.log(symbol.name); // 'AAPL'

setResolution(resolution, addToHistory?)

Change the timeframe.

Parameters:

  • resolution (string) - Timeframe like '1', '5', '15', '60', '1D', '1W'
  • addToHistory (boolean, optional) - Add to undo/redo history (default: true)

Example:

await api.setResolution('1D');
await api.setResolution('5', true);

getResolution()

Get the current timeframe.

Returns: string

Example:

const resolution = api.getResolution();
console.log(resolution); // '1D'

setChartType(type)

Change the chart type.

Parameters:

  • type (string) - Chart type: 'candle', 'line', 'bar', 'area', 'heikinAshi', 'renko', etc.

Example:

api.setChartType('candle');
api.setChartType('line');
api.setChartType('heikinAshi');

setTimezone(timezone)

Set the chart timezone.

Parameters:

  • timezone (string) - Timezone like 'America/New_York', 'Europe/London', 'Asia/Tokyo'

Example:

api.setTimezone('America/New_York');

getTimezone()

Get the current timezone.

Returns: string

Example:

const timezone = api.getTimezone();
console.log(timezone); // 'America/New_York'

Indicators

Add, remove, and manage technical indicators.

addIndicator(indicatorType, options?)

Add an indicator to the chart.

Parameters:

  • indicatorType (string) - Indicator name like 'SMA', 'RSI', 'MACD', 'EMA'
  • options (object, optional) - Indicator settings

Returns: string (indicator ID) or false

Example:

// Add Simple Moving Average
const smaId = api.addIndicator('SMA', {
period: 20,
color: '#ff0000',
lineWidth: 2
});

// Add RSI
const rsiId = api.addIndicator('RSI', {
period: 14,
overbought: 70,
oversold: 30
});

// Add MACD
const macdId = api.addIndicator('MACD', {
fastPeriod: 12,
slowPeriod: 26,
signalPeriod: 9
});

removeIndicator(indicatorId)

Remove an indicator.

Parameters:

  • indicatorId (string) - ID returned by addIndicator

Returns: boolean

Example:

const removed = api.removeIndicator(smaId);

getIndicators()

Get all active indicators.

Returns: Array of indicator objects

Example:

const indicators = api.getIndicators();
indicators.forEach(ind => {
console.log(ind.name, ind.id, ind.visible);
});

updateIndicator(id, options, paneId)

Update indicator settings.

Parameters:

  • id (string) - Indicator ID
  • options (object) - New settings with inputs, styles, or visible
  • paneId (number) - Pane ID

Example:

api.updateIndicator(smaId, {
inputs: { period: 50 },
styles: { color: '#00ff00' }
}, 0);

setIndicatorVisibility(id, visible, paneId)

Show or hide an indicator.

Parameters:

  • id (string) - Indicator ID
  • visible (boolean) - true to show, false to hide
  • paneId (number) - Pane ID

Example:

api.setIndicatorVisibility(smaId, false, 0); // Hide
api.setIndicatorVisibility(smaId, true, 0); // Show

getIndicatorVisibility(id)

Check if indicator is visible.

Returns: boolean

Example:

const isVisible = api.getIndicatorVisibility(smaId);

registerCustomIndicator(definition)

Register a custom indicator.

Parameters:

  • definition (object) - Custom indicator definition with inputs, calculate, and plots

Example:

api.registerCustomIndicator({
name: 'MyCustomSMA',
inputs: [
{ name: 'period', type: 'number', default: 20 }
],
calculate: (getRealBar, getDerivedBar, index, options) => {
const { period } = options.inputs;
if (index < period - 1) return null;

let sum = 0;
for (let i = 0; i < period; i++) {
sum += getRealBar(index - i).close;
}
return sum / period;
},
plots: [
{
type: 'line',
dataKey: 'value',
color: '#2196F3',
lineWidth: 2
}
]
});

getIndicatorsInfo()

Get information about all available indicators.

Returns: Array of indicator metadata

Example:

const indicators = api.getIndicatorsInfo();
console.log(indicators);
// [
// { name: 'SMA', description: 'Simple Moving Average', category: 'Moving Averages' },
// { name: 'RSI', description: 'Relative Strength Index', category: 'Oscillators' }
// ]

getIndicatorInfo(indicatorName)

Get information about a specific indicator.

Parameters:

  • indicatorName (string) - Indicator name

Returns: Indicator metadata or undefined

Example:

const info = api.getIndicatorInfo('RSI');
console.log(info.description); // 'Relative Strength Index'

onIndicatorAdded(callback)

Listen for indicator added events.

Example:

api.onIndicatorAdded((indicator) => {
console.log('Indicator added:', indicator.name, indicator.id);
});

onIndicatorRemoved(callback)

Listen for indicator removed events.

Example:

api.onIndicatorRemoved((indicatorId) => {
console.log('Indicator removed:', indicatorId);
});

Drawings & Shapes

Add and manage drawings on the chart.

addShape(type, points, options?)

Add a drawing to the chart.

Parameters:

  • type (string) - Drawing type: 'trend_line', 'horizontal_line', 'rectangle', 'fib_retracement', etc.
  • points (array) - Array of points with time, price, and barIndex properties
  • options (object, optional) - Drawing options like color, lineWidth

Returns: string (drawing ID)

Example:

// Add horizontal line
const lineId = api.addShape('horizontal_line', [
{ time: 1234567890000, price: 150.00, barIndex: 100 }
], {
color: '#ff0000',
lineWidth: 2
});

// Add trend line
const trendLineId = api.addShape('trend_line', [
{ time: 1234567890000, price: 145.00, barIndex: 50 },
{ time: 1234567890000, price: 155.00, barIndex: 100 }
], {
color: '#00ff00',
lineWidth: 3
});

// Add rectangle
const rectId = api.addShape('rectangle', [
{ time: 1234567890000, price: 140.00, barIndex: 50 },
{ time: 1234567890000, price: 160.00, barIndex: 100 }
], {
color: '#0000ff',
backgroundColor: 'rgba(0, 0, 255, 0.2)'
});

removeShape(id)

Remove a drawing.

Parameters:

  • id (string) - Drawing ID

Example:

api.removeShape(lineId);

updateShape(id, updates)

Update a drawing.

Parameters:

  • id (string) - Drawing ID
  • updates (object) - Updates to apply

Example:

api.updateShape(lineId, {
options: {
color: '#ffff00',
lineWidth: 4
}
});

getShape(id)

Get a drawing by ID.

Returns: Drawing object or undefined

Example:

const drawing = api.getShape(lineId);
console.log(drawing.type, drawing.points);

getAllShapes()

Get all drawings on the chart.

Returns: Array of drawing objects

Example:

const allShapes = api.getAllShapes();
console.log(`Found ${allShapes.length} drawings`);

setDrawingLocked(id, locked)

Lock or unlock a drawing.

Parameters:

  • id (string) - Drawing ID
  • locked (boolean) - true to lock, false to unlock

Example:

api.setDrawingLocked(lineId, true); // Prevent editing

setDrawingVisible(id, visible)

Show or hide a drawing.

Parameters:

  • id (string) - Drawing ID
  • visible (boolean) - true to show, false to hide

Example:

api.setDrawingVisible(lineId, false);

cloneDrawing(id)

Clone a drawing.

Parameters:

  • id (string) - Drawing ID to clone

Returns: New drawing ID or null

Example:

const clonedId = api.cloneDrawing(lineId);

selectDrawing(id)

Select a drawing.

Example:

api.selectDrawing(lineId);

clearSelection()

Clear all selected drawings.

Example:

api.clearSelection();

getSelectedDrawingIds()

Get IDs of selected drawings.

Returns: Array of strings

Example:

const selected = api.getSelectedDrawingIds();

Trading Lines

Create and manage order and position lines.

createOrderLine()

Create an order line for trading.

Returns: Promise<TradingLineHandle>

Example:

const orderLine = await api.createOrderLine();

orderLine
.onMove((payload) => {
console.log('Order moved to:', payload.price);
})
.onModify((payload) => {
console.log('Order modified');
})
.onCancel((payload) => {
console.log('Order cancelled');
})
.onClose((payload) => {
console.log('Order closed');
})
.setText('Buy AAPL')
.setTpText('Take Profit')
.setSlText('Stop Loss');

createPositionLine()

Create a position line for trading.

Returns: Promise<TradingLineHandle>

Example:

const positionLine = await api.createPositionLine();

positionLine
.onMove((payload) => {
console.log('Position moved to:', payload.price);
})
.onClose((payload) => {
console.log('Position closed');
});

TradingLineHandle Methods

The trading line handle provides these methods:

  • getId() - Get the line ID
  • onMove(callback) - Listen to move events
  • onModify(callback) - Listen to modify events
  • onCancel(callback) - Listen to cancel events
  • onReverse(callback) - Listen to reverse events
  • onClose(callback) - Listen to close events
  • setText(text) - Set the label text
  • setTpText(text) - Set take profit text
  • setSlText(text) - Set stop loss text
  • setTooltip(tooltip) - Set tooltip
  • remove() - Remove the line

Example:

orderLine.setText('Buy 100 shares');
orderLine.setTpText('TP at $160');
orderLine.setSlText('SL at $140');
orderLine.setTooltip('My order');

Zoom & Navigation

Control chart zoom and visible range.

zoomIn()

Zoom in on the chart.

Example:

api.zoomIn();

zoomOut()

Zoom out on the chart.

Example:

api.zoomOut();

resetZoom()

Reset zoom to default level.

Example:

api.resetZoom();

scrollToRealTime()

Scroll to the latest data (rightmost).

Example:

api.scrollToRealTime();

setVisibleRange(from, to)

Set the visible time range.

Parameters:

  • from (number) - Start time (Unix timestamp)
  • to (number) - End time (Unix timestamp)

Example:

const from = Date.now() - 30 * 24 * 60 * 60 * 1000; // 30 days ago
const to = Date.now();
api.setVisibleRange(from, to);

setRangePreset(period)

Set a preset time range.

Parameters:

  • period (string) - '1D', '5D', '1M', '3M', '6M', 'YTD', '1Y', '5Y', 'ALL'

Example:

api.setRangePreset('1M'); // Last month
api.setRangePreset('YTD'); // Year to date
api.setRangePreset('1Y'); // Last year

getVisibleRange()

Get the current visible range.

Returns: { from: number, to: number }

Example:

const range = api.getVisibleRange();
console.log('From:', range.from, 'To:', range.to);

Replay Mode

Replay historical data bar by bar.

startReplay(startIndex)

Start replay mode.

Parameters:

  • startIndex (number) - Bar index to start from

Example:

const lastBar = api.getLastBarIndex();
api.startReplay(lastBar - 100); // Start 100 bars ago

stopReplay()

Stop replay mode.

Example:

api.stopReplay();

stepForward()

Move forward one bar in replay.

Example:

api.stepForward();

stepBackward()

Move backward one bar in replay.

Example:

api.stepBackward();

playReplay()

Start playing replay automatically.

Example:

api.playReplay();

pauseReplay()

Pause replay.

Example:

api.pauseReplay();

setReplaySpeed(speed)

Set replay playback speed.

Parameters:

  • speed (number) - Speed multiplier (1 = normal, 2 = 2x faster, etc.)

Example:

api.setReplaySpeed(2); // 2x speed

Export & Save

Export charts as images or save/load layouts.

takeScreenshot(options?)

Take a screenshot of the chart.

Parameters:

  • options (object, optional) - Export options

Returns: Promise<string> (base64 image)

Example:

const screenshot = await api.takeScreenshot();
// Use the base64 string
console.log(screenshot);

saveAsPNG(options?)

Save the chart as a PNG file.

Example:

await api.saveAsPNG({
width: 1920,
height: 1080,
backgroundColor: '#ffffff'
});

saveAsSVG(options?)

Save the chart as an SVG file.

Example:

await api.saveAsSVG();

copyToClipboard(options?)

Copy chart image to clipboard.

Example:

await api.copyToClipboard();

saveLayoutToJSON()

Export the current chart layout as JSON.

Returns: string (JSON)

Example:

const layoutJSON = api.saveLayoutToJSON();
// Save to localStorage or server
localStorage.setItem('myChartLayout', layoutJSON);

loadLayoutFromJSON(jsonString)

Load a chart layout from JSON.

Parameters:

  • jsonString (string) - JSON layout string

Example:

const layoutJSON = localStorage.getItem('myChartLayout');
if (layoutJSON) {
api.loadLayoutFromJSON(layoutJSON);
}

Undo & Redo

Undo and redo chart actions.

undo()

Undo the last action.

Returns: boolean

Example:

const success = api.undo();

redo()

Redo the last undone action.

Returns: boolean

Example:

const success = api.redo();

Crosshair & Tooltips

Control crosshair and tooltip visibility.

enableCrosshair()

Show the crosshair.

Example:

api.enableCrosshair();

disableCrosshair()

Hide the crosshair.

Example:

api.disableCrosshair();

isCrosshairVisible()

Check if crosshair is visible.

Returns: boolean

Example:

const isVisible = api.isCrosshairVisible();

setCrosshairMode(mode)

Set crosshair behavior.

Parameters:

  • mode (string) - 'normal', 'x-only', 'y-only', 'hidden'

Example:

api.setCrosshairMode('x-only'); // Only show vertical line

getCrosshairMode()

Get current crosshair mode.

Returns: string

Example:

const mode = api.getCrosshairMode();

enableTooltip()

Show tooltips.

Example:

api.enableTooltip();

disableTooltip()

Hide tooltips.

Example:

api.disableTooltip();

Fullscreen

Control fullscreen mode.

toggleFullscreen()

Toggle fullscreen on/off.

Example:

api.toggleFullscreen();

enterFullscreen()

Enter fullscreen mode.

Example:

api.enterFullscreen();

exitFullscreen()

Exit fullscreen mode.

Example:

api.exitFullscreen();

isFullscreen()

Check if in fullscreen.

Returns: boolean

Example:

const isFS = api.isFullscreen();

onFullscreenChange(callback)

Listen to fullscreen changes.

Example:

api.onFullscreenChange((isFullscreen) => {
console.log('Fullscreen:', isFullscreen);
});

Pattern Recognition

Detect chart patterns automatically.

enablePattern(patternType)

Enable detection for a specific pattern.

Parameters:

  • patternType (string) - Pattern type like 'bearish_flag', 'bullish_flag', etc.

Example:

api.enablePattern('bearish_flag');

disablePattern(patternType)

Disable pattern detection.

Example:

api.disablePattern('bearish_flag');

isPatternEnabled(patternType)

Check if pattern detection is enabled.

Returns: boolean

Example:

const enabled = api.isPatternEnabled('bearish_flag');

getDetectedPatterns(paneId?)

Get all detected patterns.

Parameters:

  • paneId (number, optional) - Pane ID (default: 0)

Returns: Array of detected patterns

Example:

const patterns = api.getDetectedPatterns();
patterns.forEach(pattern => {
console.log(pattern.type, pattern.points);
});

clearPatterns()

Clear all detected patterns.

Example:

api.clearPatterns();

Volume & Market Profile

Add volume and market profile indicators.

addVolumeProfile(config)

Add a volume profile indicator.

Parameters:

  • config (object) - Volume profile configuration

Returns: string (indicator ID)

Example:

const vpId = api.addVolumeProfile({
profileType: 'visible_range',
valueAreaPercent: 70,
showPOC: true,
showVAHVAL: true
});

updateVolumeProfile(id, config)

Update volume profile settings.

Example:

api.updateVolumeProfile(vpId, {
valueAreaPercent: 80,
profileWidthPx: 200
});

removeVolumeProfile(id)

Remove volume profile.

Example:

api.removeVolumeProfile(vpId);

getAllVolumeProfiles()

Get all volume profiles.

Returns: Array of volume profile objects

Example:

const profiles = api.getAllVolumeProfiles();

addMarketProfile(config)

Add a market profile (TPO) indicator.

Returns: string (indicator ID)

Example:

const mpId = api.addMarketProfile({
profileType: 'session',
valueAreaPercent: 70
});

updateMarketProfile(id, config)

Update market profile settings.

Example:

api.updateMarketProfile(mpId, {
profileType: 'rolling',
rollingBars: 10
});

removeMarketProfile(id)

Remove market profile.

Example:

api.removeMarketProfile(mpId);

getMarketProfileLevels(id)

Get TPO levels (POC, VAH, VAL, etc.).

Returns: MarketProfileLevels object or null

Example:

const levels = api.getMarketProfileLevels(mpId);
if (levels) {
console.log('POC:', levels.poc);
console.log('VAH:', levels.vah);
console.log('VAL:', levels.val);
}

Data Access

Access chart data directly.

getCandleBar(index)

Get bar data at a specific index.

Parameters:

  • index (number) - Bar index

Returns: Bar data object

Example:

const bar = api.getCandleBar(100);
console.log(bar.open, bar.high, bar.low, bar.close, bar.volume);

getSeriesData(seriesName, index)

Get data for a specific series.

Parameters:

  • seriesName (string) - Series name
  • index (number) - Bar index

Returns: Series data

Example:

const smaData = api.getSeriesData('SMA_20', 100);

getLastBarIndex()

Get the index of the last bar.

Returns: number or null

Example:

const lastIndex = api.getLastBarIndex();

getDataFeedConfig()

Get the datafeed configuration.

Returns: DataFeedConfiguration or null

Example:

const config = api.getDataFeedConfig();

Layout & Workspace

Manage workspace layouts and panels.

createLayout(type)

Create a new workspace layout.

Parameters:

  • type (string) - Layout type: '1', '2h', '2v', '4', '8'

Example:

api.createLayout('4'); // 4-panel layout

setActivePanel(panelId)

Set the active panel.

Parameters:

  • panelId (string) - Panel ID

Example:

api.setActivePanel('panel-1');

setSyncMode(settings)

Set synchronization mode between panels.

Parameters:

  • settings (object) - Sync settings

Example:

api.setSyncMode({
symbol: true,
interval: true,
crosshair: true
});

updatePaneScales(paneId, logScale, autoScale, percentageScale?)

Update price scale settings for a pane.

Example:

api.updatePaneScales(0, true, true, false); // Log scale on

Events

Subscribe to chart events.

onChartReady(callback)

Listen for chart ready event.

Example:

api.onChartReady(() => {
console.log('Chart is ready!');
});

subscribeCrosshairMove(callback)

Listen for crosshair move events.

Example:

api.subscribeCrosshairMove((data) => {
console.log('Crosshair at:', data.time, data.price);
});

subscribeMouseMove(callback)

Listen for mouse move events.

Example:

api.subscribeMouseMove((data) => {
console.log('Mouse at:', data.x, data.y);
});

Other Mouse Events

  • subscribeMouseEnter(callback) - Mouse enters chart
  • subscribeMouseLeave(callback) - Mouse leaves chart
  • subscribeMouseOver(callback) - Mouse over chart
  • subscribeMousedown(callback) - Mouse button down
  • subscribeMouseup(callback) - Mouse button up
  • subscribeDblclick(callback) - Double click
  • subscribeWheel(callback) - Mouse wheel

Touch Events

  • subscribeTouchstart(callback) - Touch start
  • subscribeTouchmove(callback) - Touch move
  • subscribeTouchend(callback) - Touch end

Unsubscribe

Each subscribe method returns a subscription ID. Use it to unsubscribe:

Example:

const subId = api.subscribeMouseMove(handler);
api.unsubscribeMouseMove(subId);

Notifications

Manage chart notifications.

addNotification(notification)

Add a notification.

Example:

api.addNotification({
title: 'Price Alert',
message: 'AAPL reached $150',
type: 'info',
duration: 5000
});

removeNotification(id)

Remove a notification.

Example:

api.removeNotification(notificationId);

removeAllNotifications()

Remove all notifications.

Example:

api.removeAllNotifications();

getNotifications()

Get all notifications.

Returns: Array of notifications

Example:

const notifications = api.getNotifications();

Theme & Features

Control chart theme and features.

setTheme(theme)

Set the chart theme.

Parameters:

  • theme (string or object) - 'light', 'dark', or custom theme object

Example:

api.setTheme('dark');
api.setTheme('light');

getTheme()

Get the current theme.

Returns: Theme object

Example:

const theme = api.getTheme();

enableFeature(feature)

Enable a chart feature.

Example:

api.enableFeature('drawingTools');

disableFeature(feature)

Disable a chart feature.

Example:

api.disableFeature('drawingTools');

Quick Examples

Complete Setup Example

// Create chart
const chart = new Chart({
container: document.getElementById('chart'),
datafeed: yourDataFeed,
symbol: 'AAPL',
interval: '1D'
});

// Wait for ready
chart.onChartReady(() => {
const api = chart.getApi();

// Add indicators
const sma = api.addIndicator('SMA', { period: 20 });
const rsi = api.addIndicator('RSI', { period: 14 });

// Add drawing
const line = api.addShape('horizontal_line', [
{ time: Date.now(), price: 150.00, barIndex: 100 }
], { color: '#ff0000' });

// Set visible range
api.setRangePreset('3M');

// Listen to events
api.subscribeCrosshairMove((data) => {
console.log('Crosshair:', data.price);
});

console.log('Chart setup complete!');
});

Save and Load Layout

// Save layout
chart.onChartReady(() => {
const api = chart.getApi();

// Save
const json = api.saveLayoutToJSON();
localStorage.setItem('chartLayout', json);

// Load later
const saved = localStorage.getItem('chartLayout');
if (saved) {
api.loadLayoutFromJSON(saved);
}
});

Take Screenshot

chart.onChartReady(async () => {
const api = chart.getApi();

// Take screenshot
const screenshot = await api.takeScreenshot();

// Download as PNG
await api.saveAsPNG({
width: 1920,
height: 1080
});
});

Next Steps