Widget methods
Overview
After you create a widget with Widget Constructor, you can control the widget
object using the methods defined in the IChartingLibraryWidget
interface. This article describes the most commonly used methods. Refer to the IChartingLibraryWidget
page to see the full list of methods.
Advanced Charts methods
onChartReady
The onChartReady
method calls a callback when all data is loaded and the widget is ready. Therefore, you should call other widget methods only after the onChartReady
callback.
const widget = new TradingView.widget(/* Widget properties */);
widget.onChartReady(function() {
widget.getChartLanguage();
});
chart
The chart
method returns an instance of the IChartWidgetApi
interface that provides an extensive API for controlling the specific chart.
For example, you can handle chart events, create indicators and drawings, change chart properties on the fly, and more. Consider the code sample below that adds the Bollinger Bands indicator at the launch.
widget.onChartReady(() => {
const chart = widget.chart();
chart.createStudy(
"Bollinger Bands", // Indicator's name
true, // forceOverlay
false, // lock
{
in_0: 25, // length
in_1: 1, // 'mult' indicator setting
}
);
});
The chart
method has an optional index
parameter. If you want to interact with a certain chart on the multiple-chart layout, you should call the chart
method with the corresponding index as a parameter.
activeChart
The activeChart
method retrieves IChartWidgetApi
to interact with the currently selected chart. For example, the code sample below draws a vertical line on the chart.
widget.activeChart().createMultipointShape(
[{ price: 168, time: Date.UTC(2017, 10, 13) / 1000 }],
{ shape: 'vertical_line'}
);
You can also subscribe to events on the active chart, such as onIntervalChanged
.
widget.activeChart().onIntervalChanged().subscribe(null, (interval, timeframeObj) =>
timeframeObj.timeframe = {
value: "12M",
type: "period-back"
});
Note that the library does not manage the event subscriptions when users switch between the charts on the multiple-chart layout.
If necessary, you should manually unsubscribe from the previous chart and subscribe to the newly selected one using the corresponding methods. To track the currently active chart, use the activeChartChanged
event.
You can also find out the active chart's index using the activeChartIndex
method and subscribe to this chart using the chart
method.
const index = widget.activeChartIndex();
const chart = widget.chart(index);
subscribe / unsubscribe
The subscribe
method allows you to subscribe to the widget's events and handle them. For example, the code sample below handles an event when an indicator is added to the chart and prints the indicator's name to the console.
widget.subscribe('study', (event) => { console.log(`A ${event.value} indicator was added`) });
You should use the unsubscribe
method to unsubscribe from events.
applyOverrides
The applyOverrides
method allows you to change Overrides on the fly. The code sample below hides the main series.
widget.applyOverrides({ "mainSeriesProperties.visible": false });
applyStudiesOverrides
The applyStudiesOverrides
method allows you to change Overrides that affect indicators (studies) on the fly. The code sample below changes the color of the Bollinger Bands indicator.
widget.applyStudiesOverrides({
'bollinger bands.median.color': '#33FF88'
});
Note that this method only changes the indicator's properties before the indicator is created. You should use the applyOverrides
method in IStudyApi
to change an indicator that is already on the chart.
setSymbol
The setSymbol
method sets a symbol and resolution of the active chart.
widget.setSymbol('IBM', '1D', () => {
// Your callback function
});
Note that a callback is evoked when the data for the new symbol is loaded.
changeTheme
The changeTheme
method allows you to change the theme on the fly. This method returns a promise that is resolved once the theme is applied. You can apply other style modifications after the promise is fulfilled.
widget.changeTheme('Dark').then(() => {
widget.chart().applyOverrides({ 'paneProperties.backgroundGradientStartColor': 'red' });
});
onShortcut
The onShortcut
method allows you to specify an action that happens when a user clicks on the certain buttons. To do this, you should pass a keyboard shortcut and a callback function as parameters. The shortCut
parameter depends on the key types:
If a shortcut consists of a modifier and alphabet keys, you should pass a string and use
+
as a separator.// Alt+Q
widget.onShortcut("alt+q", function() {
widget.chart().executeActionById("symbolSearch");
});If a shortcut consists of a non-alphabet key, you should pass the key code. You can refer to the keycode.info and MDN pages to find out a key code.
// F1
widget.onShortcut(112, function() {
widget.chart().executeActionById("symbolSearch");
});If a shortcut consists of modifier and non-alphabet keys, you should pass an array that contains strings and key codes.
// Ctrl+Shift+\
widget.onShortcut(['ctrl', 'shift', 220], function() {
widget.chart().executeActionById("symbolSearch");
});
takeClientScreenshot
The takeClientScreenshot
method creates a snapshot of the chart and returns it as a canvas. You can then take the canvas element and create an image from it. The code sample below saves a screenshot as PNG.
async function saveChartToPNG() {
const screenshotCanvas = await widget.takeClientScreenshot();
const linkElement = document.createElement('a');
linkElement.download = 'screenshot';
linkElement.href = screenshotCanvas.toDataURL(); // Alternatively, use `toBlob` which is a better API
linkElement.dataset.downloadurl = ['image/png', linkElement.download, linkElement.href].join(':');
document.body.appendChild(linkElement);
linkElement.click();
document.body.removeChild(linkElement);
}
saveChartToPNG(); // Call the screenshot function
customThemes
The customThemes
method retrieves ICustomThemesApi
that allows you to manage custom themes. For example, you can reset the applied themes to the default values.
let customThemesAPI = (await widget.customThemes());
customThemesAPI.resetCustomThemes();
Trading Platform methods
The methods below are available in Trading Platform only.
widgetbar
The widgetbar
method retrieves IWidgetbarApi
that allows you to interact with the widget bar.
widget.onChartReady(() => {
widget.widgetbar().then(widgetbarApi => {
widgetbarApi.isPageVisible('data_window');
});
});
watchList
The watchList
method retrieves IWatchListApi
that allows you to interact with the Watchlist widget.
const watchlistApi = await widget.watchList();
const activeListId = watchlistApi.getActiveListId();
const currentListItems = watchlistApi.getList(activeListId);
// Adds a new section and item to the current Watchlist
watchlistApi.updateList(activeListId, [...currentListItems, '###NEW SECTION', 'AMZN']);
news
The news
method retrieves INewsApi
that allows you to interact with the News widget.
widget.onChartReady(() => {
widget.news().then(newsApi => {
// newsApi is ready to use
});
});
chartsCount
The chartsCount
method counts a number of charts on the multiple-chart layout. In the code sample below, this method is used to interact with all the charts on the layout one by one.
for (let i = 0; i < widget.chartsCount(); i++) { console.log(widget.chart(i).symbolExt().symbol) }