Here is a list of methods supported by the chart.
Before version 1.4. You can call these methods using widget object returned to you by widget's constructor.
Starting from version 1.5. You can call these methods using chart object returned to you by widget's methods chart(index) or activeChart().
- Subscribing To Chart Events
- Chart Actions
- Studies And Shapes
- getAllShapes()
- getAllStudies()
- setEntityVisibility(id, isVisible) [obsolete]
- createStudy(name, forceOverlay, lock, inputs, overrides, options)
- getStudyById(entityId)
- getSeries()
- showPropertiesDialog(entityId)
- createShape(point, options)
- createMultipointShape(points, options)
- getShapeById(entityId)
- removeEntity(entityId)
- removeAllShapes()
- removeAllStudies()
- getPanes()
- Z-order operations
- Study Templates
- Trading Primitives
- Getters
- Other
You can subscribe using Subscription object returned by this function to be notified when new history bars are loaded. You can also use the same object to unsubscribe from the event.
Example:
widget.activeChart().onDataLoaded().subscribe(
null,
() => console.log('New history bars are loaded'),
true
);
You can subscribe using Subscription object returned by this function to be notified when the symbol is changed. You can also use the same object to unsubscribe from the event.
Example:
widget.activeChart().onSymbolChanged().subscribe(null, () => console.log('The symbol is changed'));
You can subscribe using Subscription object returned by this function to be notified when the interval is changed. You can also use the same object to unsubscribe from the event. When the event is fired it will provide the following arguments:
-
interval
: new interval -
timeframeObj
: object with the only fieldtimeframe
.It contains a timeframe or dates range. It presents if the user clicks on the timeframe panel or changes the dates range.
Otherwise
timeframe
isundefined
and you can change it to display a certain range of bars. Valid timeframe is aTimeFrameValue
object.TimeFrameValue
can be:- a timeframe object,
{type, value}
:type
:period-back
.value
: valid timeframe is a number with letter D for days and M for months.
- a range object,
{type, from, to}
type
:time-range
.from
,to
: UNIX timestamps, UTC.
- a timeframe object,
Example:
widget.activeChart().onIntervalChanged().subscribe(null, (interval, timeframeObj) => timeframeObj.timeframe = { value: "12M", type: "period-back" });
widget.activeChart().onIntervalChanged().subscribe(null,
(interval, timeframeObj) => timeframeObj.timeframe = { from: new Date('2015-01-01').getTime() / 1000, to: new Date('2017-01-01').getTime() / 1000, type: "time-range" }
);
You can subscribe using Subscription object returned by this function to be notified when the chart type is changed. You can also use the same object to unsubscribe from the event.
When the event is fired it will provide the chartType
argument, possible values are described here.
Example:
widget.activeChart().onChartTypeChanged().subscribe(null, (chartType) => console.log('The type of chart is changed'));
The function returns true
if bars are already loaded and false
otherwise.
Example:
if (widget.activeChart().dataReady()) {
/* do something */
}
callback
: function(onReadyCallback)
The Charting Library will immediately call the callback function if bars are already loaded or when the bars are received.
Example:
widget.activeChart().dataReady(() => {
/* draw shapes */
});
You can subscribe using Subscription object returned by this function to be notified when visible time range is changed. You can also use the same object to unsubscribe from the event.
When the event is fired it will provide the following arguments:
params
: object{time price}
time
: unix timestamps, UTC.price
: number.
Example:
widget.activeChart().crossHairMoved().subscribe(
null,
({ time, price }) => console.log(time, price)
);
Since version 1.13.
You can subscribe using Subscription object returned by this function to be notified when visible time range is changed. You can also use the same object to unsubscribe from the event.
When the event is fired it will provide the following arguments:
range
: object,{from to}
from
,to
: unix timestamps, UTC.
Example:
widget.activeChart().onVisibleRangeChanged().subscribe(
null,
({ from, to }) => console.log(from, to)
);
range
: object,{ from, to }
from
,to
: unix timestamps, UTC
options
:{ applyDefaultRightMargin, percentRightMargin }
applyDefaultRightMargin
: indicates whether the library should apply the default right margin to the right border if it points on the last bar.percentRightMargin
: indicates whether the library should apply the percent right margin to the right border if it points on the last bar.
Forces the chart to adjust its parameters (scroll, scale) to make the selected time period fit the widget.
Returns a Promise object, which will be resolved after visible range is applied.
This method was introduced in version 1.2
.
widget.activeChart().setVisibleRange(
{ from: 1420156800, to: 1451433600 },
{ percentRightMargin: 20 }
).then(() => console.log('New visible range is applied'));
symbol
: stringcallback
: function(), optional
Makes the chart change its symbol. Callback function is called once the data for the new symbol is loaded.
widget.activeChart().setSymbol('IBM');
resolution
: string. Format is described in another article.callback
: function(), optional
Makes the chart change its resolution. Callback function is called once new data is loaded.
widget.activeChart().setResolution('2M');
Makes the chart re-request data from the data feed. The function is often called when chart's data has changed.
Before calling this function you should call onResetCacheNeededCallback
from subscribeBars
.
widget.activeChart().resetData();
Starting from version 1.3.
actionId
: string
Executes an action according to its id.
Shows a dialog:
chartProperties
compareOrAdd
scalesProperties
paneObjectTree
insertIndicator
symbolSearch
changeInterval
gotoDate
Other actions:
timeScaleReset
chartReset
seriesHide
studyHide
lineToggleLock
lineHide
scaleSeriesOnly
drawingToolbarAction
stayInDrawingModeAction
hideAllMarks
showCountdown
- for intraday resolutions onlyshowSeriesLastValue
showSymbolLabelsAction
showStudyLastValue
showStudyPlotNamesAction
undo
redo
paneRemoveAllStudiesDrawingTools
Examples:
// < ... >
widget.activeChart().executeActionById("undo");
// < ... >
widget.activeChart().executeActionById("drawingToolbarAction"); // hides or shows the drawing toolbar
// < ... >
Starting from version 1.7.
actionId
: string
Get a checkable action state (e.g. stayInDrawingModeAction
, showSymbolLabelsAction
) according to its ID (see the IDs of actions above)
if (widget.activeChart().getCheckableActionState("drawingToolbarAction")) {
/* do something */
};
When you call this method the Library re-requests Bar marks and Timescale marks.
widget.activeChart().refreshMarks();
When you call this method the Library removes all visible marks.
widget.activeChart().clearMarks();
type
: number
Sets the main series style.
Style | JavaScript type | Typescript Enum | Charting Library | Trading Terminal |
---|---|---|---|---|
Bar | 0 | ChartStyle.Bar | ✓ | ✓ |
Candle | 1 | ChartStyle.Candle | ✓ | ✓ |
Line | 2 | ChartStyle.Line | ✓ | ✓ |
Area | 3 | ChartStyle.Area | ✓ | ✓ |
Renko | 4 | ChartStyle.Renko | ✓ | |
Kagi | 5 | ChartStyle.Kagi | ✓ | |
PnF | 6 | ChartStyle.PnF | ✓ | |
Line Break | 7 | ChartStyle.LineBreak | ✓ | |
Heikin-Ashi | 8 | ChartStyle.HeikinAshi | ✓ | ✓ |
Hollow Candle | 9 | ChartStyle.HollowCandle | ✓ | ✓ |
Baseline | 10 | ChartStyle.Baseline | ✓ | ✓ |
Hi-Lo | 12 | ChartStyle.HiLo | ✓ | ✓ |
widget.activeChart().setChartType(12);
timezone
: string
See timezone for more information.
Example:
widget.activeChart().setTimezone('Asia/Singapore');
Makes the chart change its timezone.
Deprecated: Use setTimezone instead. This is going to be removed in future releases.
Since version 1.15.
Returns the current timezone of the chart.
console.log(widget.activeChart().getTimezone());
Deprecated: Use getTimezone instead. This is going to be removed in future releases.
Since version 22.
Returns a TimezoneApi that allows you to interact with the chart's timezone.
Since version 1.14.
When you call this method, the Library checks if there are any zoom events to undone.
console.log(widget.activeChart().canZoomOut());
Since version 1.14.
When you call this method, it simulates a click on the "Zoom Out" button. It works only if the chart is zoomed. Use canZoomOut
to check if you can call this method.
if(widget.activeChart().canZoomOut()) {
widget.activeChart().zoomOut();
};
Returns an array of all created shape objects. Each object has the following fields:
id
: id of a shapename
: name of a shape
widget.activeChart().getAllShapes().forEach(({ name }) => console.log(name));
Returns an array of all created shape objects. Each object has the following fields:
id
: id of a studyname
: name of a study
widget.activeChart().getAllStudies().forEach(({ name }) => console.log(name));
Sets visibility of an entity with a passed ID.
widget.activeChart().setEntityVisibility(id, false); // Hide the entity with id
Deprecated: Use a shape/study API instead (getShapeById
/getStudyById
). This is going to be removed in future releases.
name
: string, name of an indicator as shown in theIndicators
widgetforceOverlay
: forces the Charting Library to place the created study on the main panelock
: boolean, shows whether a user will be able to remove/change/hide the study or notinputs
: (starting from version1.2
Deprecated) an array of study inputs. This array is expected to contain input values in the same order as in the study properties dialog. From version v22 it's an object containing named properties from the study properties dialog.overrides
: (starting from version1.2
) an object containing properties you'd like to set for your new study. Note that you should not specify the study name. Start a property path with a plot name.options
: object with the the following keys:checkLimit
- if it istrue
then the study limit dialog will be shown if the limit is exceeded.priceScale
- preferred price scale for the study. Possible values are:new-left
- attach the study to a new left price scalenew-right
- attach the study to a new right price scaleno-scale
- do not attach the study to any price scale. The study will be added in 'No Scale' modeas-series
- attach the study to the price scale where the main series is attached (it is only applicable the study is added to the pane with the main series)
disableUndo
- prevents adding of the action to the undo stack
See here more information about panes and scales behavior in relation to studies.
Returns a Promise to entityId
of the created study.
Starting from v 1.12 the function returns the result immediately. Callback is kept to maintain compatibility.
Creates a study on the main symbol. Here are the examples:
Deprecated:
widget.activeChart().createStudy('MACD', false, false, [14, 30, "close", 9])
widget.activeChart().createStudy('Moving Average Exponential', false, false, [26])
widget.activeChart().createStudy('Stochastic', false, false, [26], {"%d.color" : "#FF0000"})
widget.activeChart().createStudy('Price Channel', true, false, [26], null, {checkLimit: false, priceScale: 'new-left'})
From version 22:
widget.activeChart().createStudy('MACD', false, false, { in_0: 14, in_1: 30, in_3: 'close', in_2: 9 })
widget.activeChart().createStudy('Moving Average Exponential', false, false, { length: 26 })
widget.activeChart().createStudy('Stochastic', false, false, { in_0: 26 }, {"%d.color" : "#FF0000"})
widget.activeChart().createStudy('Price Channel', true, false, { in_0: 26 }, null, {checkLimit: false, priceScale: 'new-left'})
Remark: The Compare
study has 2 inputs: [dataSource, symbol]
. Supported dataSource
values are: ["close", "high", "low", "open"]
.
Remark 2: You use Overlay
study when you choose to Add
series on the chart. This study has a single input -- symbol
. Here is an example of adding a symbol:
widget.activeChart().createStudy('Overlay', false, false, ['AAPL']);
Remark 3: You also use the Compare
study when you choose to compare different financial instruments. This study has two inputs -- source
and symbol
. Here is an example:
widget.activeChart().createStudy('Compare', false, false, ["open", 'AAPL']);
entityId
: object. Value that is returned when a study is created via API.
Returns an instance of the StudyApi that allows you to interact with the study.
widget.activeChart().getStudyById(id).setVisible(false);
Returns an instance of the SeriesApi that allows you to interact with the main series.
widget.activeChart().getSeries().setVisible(false);
entityId
: object. Value that is returned when a study or shape is created via API.
Shows the properties dialog for specified study or shape for user interaction.
const chart = widget.activeChart();
chart.showPropertiesDialog(chart.getAllShapes()[0].id);`
This is a shorthand for createMultipointShape method, which can be used for shapes based on one point.
point
: object{time, [price], [channel]}
time
: unix time. It's the only mandatory key in this function argument.price
: If you specifyprice
, then the shape will be placed at the same price level. If not, then the shape will be placed close to the bar according thechannel
value.channel
: If the price is not set thenchannel
value defines where the shape is placed relative to the bar. Possible values areopen
,high
,low
,close
. If no channel is specified then 'open' is a default value.
options
: object{shape, [text], [lock], [overrides]}
, it is the same as in createMultipointShape method.shape
may be one of the identifiers that require only one point.flag
is the default value.text
is an optional argument. It's the text that will be included in the shape if it's supported. Additional fieldshowLabel
in overrides may be necessary.lock
shows whether a user will be able to remove/change/hide the shape or not.disableSelection
prevents selecting of the shapedisableSave
prevents saving the shape on the chartdisableUndo
prevents adding of the action to the undo stackoverrides
is an object containing properties you'd like to set for your new shape.zOrder
can have the following valuestop
,bottom
.top
places the line tool on top of all other chart objects whilebottom
places the line tool behind all other chart objects. If not specified the line tool is placed on top of all existing chart objects.showInObjectsTree
: Displays the shape in the Objects Tree dialog. The default value istrue
.ownerStudyId
: optional argument ofEntityId
type. It can be used to bind a line tool to a study. For instance, it can be used to create a shape on an additional pane.
The function returns entityId
- unique ID of the shape if the creation was successful and null
if it wasn't.
This call creates a shape at a specific point on the chart provided that it's within the main series area.
widget.activeChart().createShape({ time: 1514764800 }, { shape: 'vertical_line' });
points
: is an array of object with the following keys[{time, [price], [channel]},...]
time
: unix time. It's the only mandatory key in this function argument.price
: If you specifyprice
, then the shape will be placed at the same price level. If not, then the shape will be placed close to the bar according thechannel
value.channel
: If the price is not set thenchannel
value defines where the shape is placed relative to the bar. Possible values areopen
,high
,low
,close
. If no channel is specified, 'open' is a default value.
options
: object{shape, [text], [lock], [overrides]}
shape
may be one of the identifierstext
is an optional argument. It's the text that will be included in the shape if it's supported. Additional fieldshowLabel
in overrides may be necessary.lock
shows whether a user will be able to remove/change/hide the shape or not.disableSelection
prevents selecting of the shapedisableSave
prevents saving the shape on the chartdisableUndo
prevents adding of the action to the undo stackoverrides
is an object containing properties you'd like to set for your new shape.zOrder
can have the following valuestop
,bottom
.top
places the line tool on top of all other chart objects whilebottom
places the line tool behind all other chart objects. If not specified the line tool is placed on top of all existing chart objects.showInObjectsTree
: Displays the shape in the Objects Tree dialog. The default value istrue
.ownerStudyId
: optional argument ofEntityId
type. It can be used to bind a line tool to a study. For instance, it can be used to create a shape on an additional pane.
The function returns entityId
- unique ID of the shape if the creation was successful and null
if it wasn't.
Check out Shapes and Overrides for more information.
This call creates a shape at a specific point on the chart provided that it's within the main series area.
const from = Date.now() / 1000 - 500 * 24 * 3600; // 500 days ago
const to = Date.now() / 1000;
widget.activeChart().createMultipointShape(
[{ time: from, price: 150 }, { time: to, price: 150 }],
{
shape: "trend_line",
lock: true,
disableSelection: true,
disableSave: true,
disableUndo: true,
text: "text",
}
);
entityId
: object. The value that is returned when a shape is created via API
Returns an instance of the ShapeApi that allows you to interact with the shape.
widget.activeChart().getShapeById(id).bringToFront();
entityId
: object. It's the value that was returned when the entity (shape or study) was created.options
is an optional object added in version 17 with one field:disableUndo
- boolean flag that shows the undo action availability.
Removes the specified entity.
widget.activeChart().removeEntity(id);
Removes all the shapes from the chart.
widget.activeChart().removeAllShapes();
Removes all the studies from the chart.
widget.activeChart().removeAllStudies();
Returns an array of instances of the PaneApi that allows you to interact with the panes.
widget.activeChart().getPanes()[1].moveTo(0);
Returns an API that can be used to work with groups of shapes.
widget.activeChart().shapesGroupController().createGroupFromSelection();
entities
is an array of identifiers
Returns an object with operations available for the specified set of objects.
This structure has the following fields:
bringForwardEnabled
: true if one can bring specified entities forwardbringToFrontEnabled
: true if one can bring specified entities to frontsendBackwardEnabled
: true if one can send specified entities backwardsendToBackEnabled
: true if one can send specified entities to back
widget.activeChart().availableZOrderOperations([id]);
entities
is an array of identifiers
Sends specified entities to back.
widget.activeChart().sendToBack([id]);
entities
is an array of identifiers
Brings specified entities to front.
widget.activeChart().bringToFront([id]);
entities
is an array of identifiers
Brings specified entities one step forward (makes it higher).
widget.activeChart().bringForward([id]);
entities
is an array of identifiers
Sends specified entities one step backward (makes it lower).
widget.activeChart().sendBackward([id]);
options
: object{ saveSymbol, saveInterval }
saveSymbol
: booleansaveInterval
: boolean
Saves the study template to JS object. Charting Library will call your callback function and pass the state object as an argument.
This call is a part of low-level save/load API.
const options = { saveSymbol: true, saveInterval: true };
const template = widget.activeChart().createStudyTemplate(options);
template
: object
Loads the study template from the template
object.
This call is a part of low-level save/load API.
widget.activeChart().applyStudyTemplate(template);
options
is a non-required object with one possible key -disableUndo
which can betrue
orfalse
. For compatibility reasons the default value is set tofalse
.
Creates a new trading order on the chart and returns an API-object that you can use to adjust its properties and behavior.
It is strongly recommended to read this article before using this call.
API object methods:
remove()
: Removes the position from the chart. You can’t this API-object after the call.onModify(callback)
/onModify(data, callback)
onMove(callback)
/onMove(data, callback)
onCancel(callback)
/onCancel(data, callback)
API object has a set of properties listed below. Each property should be used through respective accessors.
For example, if you wish to work with the Extend Left
property, then use getExtendLeft()
of setExtendLeft()
methods.
General properties:
Property | Type | Supported Values | Default Value |
---|---|---|---|
Price | Double | Double | 0.0 |
Text | String | String | "" |
Tooltip | String | String | "" |
Modify Tooltip | String | String | "" |
Cancel Tooltip | String | String | "" |
Quantity | String | String | "" |
Editable | Boolean | Boolean | true |
Cancellable | Boolean | Boolean | true |
Horizontal line properties:
Property | Type | Supported Values | Default Value |
---|---|---|---|
Extend Left | Boolean | "inherit" or Boolean | True |
Line Length | Integer | "inherit" or 0 .. 100 | 0 |
Line Style | Integer | "inherit" or 0 .. 2 | 2 |
Line Width | Integer | "inherit" or 1 .. 4 | 1 |
Fonts:
Property | Type | Default Value |
---|---|---|
Body Font | String | "bold 7pt Verdana" |
Quantity Font | String | "bold 7pt Verdana" |
Colors:
Property | Type | Default Value |
---|---|---|
Line Color | String | "rgb(255, 0, 0)" |
Body Border Color | String | "rgb(255, 0, 0)" |
Body Background Color | String | "rgba(255, 255, 255, 0.75)" |
Body Text Color | String | "rgb(255, 0, 0)" |
Quantity Border Color | String | "rgb(255, 0, 0)" |
Quantity Background Color | String | "rgba(255, 0, 0, 0.75)" |
Quantity Text Color | String | "rgb(255, 255, 255)" |
Cancel Button Border Color | String | "rgb(255, 0, 0)" |
Cancel Button Background Color | String | "rgba(255, 255, 255, 0.75)" |
Cancel Button Icon Color | String | "rgb(255, 0, 0)" |
Example:
widget.activeChart().createOrderLine()
.setTooltip("Additional order information")
.setModifyTooltip("Modify order")
.setCancelTooltip("Cancel order")
.onMove(function() {
this.setText("onMove called");
})
.onModify("onModify called", function(text) {
this.setText(text);
})
.onCancel("onCancel called", function(text) {
this.setText(text);
})
.setText("STOP: 73.5 (5,64%)")
.setQuantity("2");
options
is an object with one possible key -disableUndo
which can betrue
orfalse
. For compatibility reasons the default value is set tofalse
.
Creates a new trading position on the chart and returns an API-object that you can use to adjust its properties and behavior.
It is strongly recommended to read this article before using this call.
API object methods:
remove()
: Removes the position from the chart. You can’t use this API-object after the call.onClose(callback)
/onClose(data, callback)
onModify(callback)
/onModify(data, callback)
onReverse(callback)
/onReverse(data, callback)
API object has a set of properties listed below. Each property should be used through respective accessors.
For example, if you wish to work with Extend Left
property, use getExtendLeft()
of setExtendLeft()
methods.
General properties:
Property | Type | Supported Values | Default Value |
---|---|---|---|
Price | Double | Double | 0.0 |
Text | String | String | "" |
Tooltip | String | String | "" |
Protect Tooltip | String | String | "" |
Reverse Tooltip | String | String | "" |
Close Tooltip | String | String | "" |
Quantity | String | String | "" |
Horizontal line properties:
Property | Type | Supported Values | Default Value |
---|---|---|---|
Extend Left | Boolean | "inherit" or Boolean | True |
Line Length | Integer | "inherit" or 0 .. 100 | 0 |
Line Style | Integer | "inherit" or 0 .. 2 | 2 |
Line Width | Integer | "inherit" or 1 .. 4 | 1 |
Fonts:
Property | Type | Default Value |
---|---|---|
Body Font | String | "bold 7pt Verdana" |
Quantity Font | String | "bold 7pt Verdana" |
Colors:
Property | Type | Default Value |
---|---|---|
Line Color | String | "rgb(0, 113, 224)" |
Body Border Color | String | "rgb(0, 113, 224)" |
Body Background Color | String | "rgba(255, 255, 255, 0.75)" |
Body Text Color | String | "rgb(0, 113, 224)" |
Quantity Border Color | String | "rgb(0, 113, 224)" |
Quantity Background Color | String | "rgba(0, 113, 224, 0.75)" |
Quantity Text Color | String | "rgb(255, 255, 255)" |
Reverse Button Border Color | String | "rgb(0, 113, 224)" |
Reverse Button Background Color | String | "rgba(255, 255, 255, 0.75)" |
Reverse Button Icon Color | String | "rgb(0, 113, 224)" |
Close Button Border Color | String | "rgb(0, 113, 224)" |
Close Button Background Color | String | "rgba(255, 255, 255, 0.75)" |
Close Button Icon Color | String | "rgb(0, 113, 224)" |
Example:
widget.chart().createPositionLine()
.onModify(function() {
this.setText("onModify called");
})
.onReverse("onReverse called", function(text) {
this.setText(text);
})
.onClose("onClose called", function(text) {
this.setText(text);
})
.setText("PROFIT: 71.1 (3.31%)")
.setTooltip("Additional position information")
.setProtectTooltip("Protect position")
.setCloseTooltip("Close position")
.setReverseTooltip("Reverse position")
.setQuantity("8.235")
.setPrice(160)
.setExtendLeft(false)
.setLineStyle(0)
.setLineLength(25);
options
is an object with one possible key -disableUndo
which can betrue
orfalse
. For compatibility reasons the default value is set tofalse
.
Creates a new trade execution on the chart and returns an API-object that you can use to control the execution properties.
It is strongly recommended to read this article before using this call.
API object has a set of properties listed below. Each property should be used through respective accessors.
For example, if you wish to work with Extend Left
property, then use getExtendLeft()
of setExtendLeft()
methods.
API object methods:
remove()
: Removes the execution shape from the chart. You can’t use this API-object after the call.
General properties:
Property | Type | Supported Values | Default Value |
---|---|---|---|
Price | Double | Double | 0.0 |
Time | Integer | Unix time | 0 |
Direction | String | "buy" or "sell" | "buy" |
Text | String | String | "execution" |
Tooltip | String | String | |
Arrow Height | Integer | Integer | 8 |
Arrow Spacing | Integer | Integer | 1 |
Fonts:
Property | Type | Default Value |
---|---|---|
Font | String | "8pt Verdana" |
Colors:
Property | Type | Default Value |
---|---|---|
Text Color | String | "rgb(0, 0, 0)"" |
Arrow Color | String | "rgba(0, 0, 255)" |
Example:
widget.activeChart().createExecutionShape()
.setText("@1,320.75 Limit Buy 1")
.setTooltip("@1,320.75 Limit Buy 1")
.setTextColor("rgba(0,255,0,0.5)")
.setArrowColor("#0F0")
.setDirection("buy")
.setTime(widget.activeChart().getVisibleRange().from)
.setPrice(160);
Returns the current symbol of the chart.
console.log(widget.activeChart().symbol());
Returns the current symbol information of the chart. The object has the following fields:
symbol
: is the same as the result of symbol() methodfull_name
: the full name of the symbolexchange
: the exchange of the symboldescription
: the description of the symboltype
: the type of the symbol
console.log(widget.activeChart().symbolExt().full_name);
Returns the chart's time interval. The format is described in this article.
console.log(widget.activeChart().resolution());
Returns the object {from, to}
. from
and to
are Unix timestamps in the UTC timezone.
console.log(widget.activeChart().getVisibleRange());
Starting from version 1.7.
Deprecated, use Price Scale API instead.
Returns the object {from, to}
. from
and to
are boundaries of the price scale visible range in main series area.
console.log(widget.activeChart().getVisiblePriceRange());
Starting from version 1.15.
Returns the distance from the right edge of the chart to the last bar, measured in bars. This is actually the current scrolling position of the chart, including the right margin.
console.log(widget.activeChart().scrollPosition());
Starting from version 1.15.
Returns the default distance from the right edge of the chart to the last bar, measured in bars.
console.log(widget.activeChart().defaultScrollPosition());
Returns the object with format
function that you can use to format the prices.
widget.activeChart().priceFormatter().format(123);
Returns the main series style type.
console.log(widget.activeChart().chartType());
Returns the Price To Bar ratio or null if none is defined.
console.log(widget.activeChart().getPriceToBarRatio());
Returns the state of the Price to Bar ratio option.
console.log(widget.activeChart().isPriceToBarRatioLocked());
Returns all panes' heights in an array.
console.log(widget.activeChart().getAllPanesHeight());
heights
is an array of numbers
Set the height for each panes in the order provided by the array.
console.log(widget.activeChart().setAllPanesHeight([250, 400, 200]));
Starting from version 1.14.
options
(optional) is an object, which can contain the following properties:from
(number
) - date of the first exporting bar (UNIX timestamp in seconds). By default the time of the leftmost loaded bar is used.to
(number
) - date of the last exporting bar (UNIX timestamp in seconds). By default the time of the rightmost (real-time) bar is used.includeTime
(boolean
, defaulttrue
) - defines whether each item of the exported data should contain time.includeUserTime
(boolean
, defaultfalse
) - defines whether each item of the exported data should contain user time.includeSeries
(boolean
, defaulttrue
) - defines whether the exported data should contain the main series (open, high, low, close).includedStudies
- which studies should be included in the exported data (by default, the value is'all'
which means that all studies are included, but if you want to export only some of them then you can assign an array of studies' ids).includeDisplayedValues
(boolean
, defaultfalse
) - returns formatted values for every value according to data source's formatter and params.
Exports data from the chart, returns a Promise object. This method doesn't load data. The result has the following structure:
-
schema
is an array of field descriptors, each descriptor might be one the following types:TimeFieldDescriptor
- description of the time field. It contains only one field -type
with the'time'
value.UserTimeFieldDescriptor
- description of the user time field. It contains only one field -type
with the'userTime'
value.SeriesFieldDescriptor
- description of a series field. It contains the following fields:type
('value'
)sourceType
('series'
)plotTitle
(string
) - the name of the plot (open, high, low, close).sourceTitle
(string
) - title of the series
StudyFieldDescriptor
- description of a study field. It contains the following fields:type
('value'
)sourceType
('study'
)sourceId
(string
) - id of the studysourceTitle
(string
) - title of the studyplotTitle
(string
) - title of the plot
-
data
is an array of Float64Arrays. EachFloat64Array
array has the same length asschema
array and represents the associated field's item. -
displayedData
is an array of arrays of strings (i.e.string[][]
). Each inner array has the same length asschema
array and represents the display value of the associated field element. Note that this array will be empty ifincludeDisplayedValues
option isfalse
.
Examples:
widget.activeChart().exportData({ includeTime: false, includedStudies: [] })
- to export series' data only.widget.activeChart().exportData({ includedStudies: [] })
- to export series' data with times.widget.activeChart().exportData({ includeTime: false, includeUserTime: true, includedStudies: [] })
- to export series' data with user time.widget.activeChart().exportData({ includeTime: false, includeSeries: false, includedStudies: ['STUDY_ID'] })
- to export data for the study with the idSTUDY_ID
.widget.activeChart().exportData({ includeUserTime: true })
- to export all available data from the chart.widget.activeChart().exportData({ includeTime: false, to: Date.UTC(2018, 0, 1) / 1000 })
- to export series' data before2018-01-01
.widget.activeChart().exportData({ includeTime: false, from: Date.UTC(2018, 0, 1) / 1000 })
- to export series' data in the range before2018-01-01
.widget.activeChart().exportData({ includeTime: false, from: Date.UTC(2018, 0, 1) / 1000, to: Date.UTC(2018, 1, 1) / 1000 })
- to export series' data in the range between2018-01-01
and2018-02-01
.widget.activeChart().exportData({ includeDisplayedValues: true })
- to export all displayed data on the chart.
User time is the time that is displayed to the user on the chart, taking into account the selected time zone and resolution.
Starting from version 1.15.
Returns SelectionApi to that can be used to change the chart selection and subscribe to chart selection changes.
widget.activeChart().selection().clear();
Starting from version 1.15.
Enables (if the parameter is true) or disables (if the parameter is false) zooming of the chart.
widget.activeChart().setZoomEnabled(false);
Starting from version 1.15.
Enables (if the parameter is true) or disables (if the parameter is false) scrolling of the chart.
widget.activeChart().setScrollEnabled(false);
Starting from version 18.
Returns an instance of the TimeScaleApi with methods associated with the time axis.
var time = widget.activeChart().getTimeScale().coordinateToTime(100);
Starting from version 18.
Returns whether the bar selection mode is active or not.
var isRequested = widget.activeChart().isSelectBarRequested();
Starting from version 18.
Switches the chart state to the bar selection mode. For example, it is used to start Bar Replay.
Returns a Promise object, which will be resolved with a time (unix timestamp) of the bar selected by a user, or will be rejected if the bar selection was either already requested or cancelled (by a user action or by the cancelSelectBar()
method).
widget.activeChart().requestSelectBar()
.then(function(time) {
console.log('user selects bar with time', time);
})
.catch(function() {
console.log('bar selection was rejected');
});
Starting from version 18.
Cancels active select bar request if it exists, or do nothing otherwise.
widget.activeChart().cancelSelectBar();
value
is the new ratio to set (number)options
is an object only containing thedisableUndo
boolean property
Set a new ratio along with some options.
widget.activeChart().setPriceToBarRatio(0.4567, { disableUndo: true });
value
is used to lock/unlock the Price To Bar Ratio (boolean)options
is an object only containing thedisableUndo
boolean property
Set/unset the lock property along with some options.
widget.activeChart().setPriceToBarRatioLocked(true, { disableUndo: false });