/** * TradingView Charting Library * @packageDocumentation * @module Charting Library */ // Generated by dts-bundle-generator v7.0.0 /* eslint-disable jsdoc/require-jsdoc */ declare const dateFormatFunctions: { readonly "dd MMM 'yy": (date: Date, local: boolean) => string; readonly "MMM dd, yyyy": (date: Date, local: boolean) => string; readonly "MMM dd": (date: Date, local: boolean) => string; readonly "dd MMM": (date: Date, local: boolean) => string; readonly "yyyy-MM-dd": (date: Date, local: boolean) => string; readonly "yy-MM-dd": (date: Date, local: boolean) => string; readonly "yy/MM/dd": (date: Date, local: boolean) => string; readonly "yyyy/MM/dd": (date: Date, local: boolean) => string; readonly "dd-MM-yyyy": (date: Date, local: boolean) => string; readonly "dd-MM-yy": (date: Date, local: boolean) => string; readonly "dd/MM/yy": (date: Date, local: boolean) => string; readonly "dd/MM/yyyy": (date: Date, local: boolean) => string; readonly "MM/dd/yy": (date: Date, local: boolean) => string; readonly "MM/dd/yyyy": (date: Date, local: boolean) => string; }; /* eslint-enable jsdoc/require-jsdoc */ declare enum HHistDirection { LeftToRight = "left_to_right", RightToLeft = "right_to_left" } declare enum LineStudyPlotStyle { /** * Line plot style. */ Line = 0, /** * Histogram plot style. */ Histogram = 1, /** * Cross plot style. */ Cross = 3, /** * Area plot style. */ Area = 4, /** * Column plot style. */ Columns = 5, /** * Circles plot style. */ Circles = 6, /** * Line with breaks plot style. */ LineWithBreaks = 7, /** * Area with breaks plot style. */ AreaWithBreaks = 8, /** * Step line plot style. */ StepLine = 9, /** * Step line with diamonds plot style. */ StepLineWithDiamonds = 10, /** * Step line with breaks, like LineWithBreaks */ StepLineWithBreaks = 11 } declare enum LineStyle { /** * Solid line style. */ Solid = 0, /** * Dotted line style. */ Dotted = 1, /** * Dashed line style. */ Dashed = 2 } declare enum MarkLocation { AboveBar = "AboveBar", BelowBar = "BelowBar", Top = "Top", Bottom = "Bottom", Right = "Right", Left = "Left", Absolute = "Absolute", AbsoluteUp = "AbsoluteUp", AbsoluteDown = "AbsoluteDown" } declare enum OrderOrPositionMessageType { Information = "information", Warning = "warning", Error = "error" } declare enum PlotSymbolSize { Auto = "auto", Tiny = "tiny", Small = "small", Normal = "normal", Large = "large", Huge = "huge" } declare enum PriceAxisLastValueMode { LastPriceAndPercentageValue = 0, LastValueAccordingToScale = 1 } declare enum StopType { StopLoss = 0, TrailingStop = 1 } export declare const enum ActionId { ChartAddIndicatorToAllCharts = "Chart.AddIndicatorToAllCharts", ChartAddSymbolToWatchList = "Chart.AddSymbolToWatchList", ChartApplyIndicatorsToAllCharts = "Chart.ApplyIndicatorsToAllCharts", ChartChangeTimeZone = "Chart.ChangeTimeZone", ChartClipboardCopyPrice = "Chart.Clipboard.CopyPrice", ChartClipboardCopyLineTools = "Chart.Clipboard.CopyLineTools", ChartClipboardCopySource = "Chart.Clipboard.CopySource", ChartClipboardPasteSource = "Chart.Clipboard.PasteSource", ChartCrosshairLockVerticalCursor = "Chart.Crosshair.LockVerticalCursor", ChartCrosshairPlusButtonDrawHorizontalLine = "Chart.Crosshair.PlusButton.DrawHorizontalLine", ChartCustomActionId = "Chart.CustomActionId", ChartDialogsShowChangeInterval = "Chart.Dialogs.ShowChangeInterval", ChartDialogsShowChangeSymbol = "Chart.Dialogs.ShowChangeSymbol", ChartDialogsShowCompareOrAddSymbol = "Chart.Dialogs.ShowCompareOrAddSymbol", ChartDialogsShowGeneralSettings = "Chart.Dialogs.ShowGeneralSettings", ChartDialogsShowGeneralSettingsLegendTab = "Chart.Dialogs.ShowGeneralSettings.LegendTab", ChartDialogsShowGeneralSettingsSymbolTab = "Chart.Dialogs.ShowGeneralSettings.SymbolTab", ChartDialogsShowGoToDate = "Chart.Dialogs.ShowGoToDate", ChartDialogsShowInsertIndicators = "Chart.Dialogs.ShowInsertIndicators", ChartDialogsShowSymbolInfo = "Chart.Dialogs.ShowSymbolInfo", ChartDrawingToolbarToggleVisibility = "Chart.DrawingToolbar.ToggleVisibility", ChartExternalActionId = "Chart.ExternalActionId", ChartFavoriteDrawingToolsToolbarHide = "Chart.FavoriteDrawingToolsToolbar.Hide", ChartIndicatorShowSettingsDialog = "Chart.Indicator.ShowSettingsDialog", ChartLegendToggleBarChangeValuesVisibility = "Chart.Legend.ToggleBarChangeValuesVisibility", ChartLegendTogglePriceSourceVisibility = "Chart.Legend.TogglePriceSourceVisibility", ChartLegendToggleIndicatorArgumentsVisibility = "Chart.Legend.ToggleIndicatorArgumentsVisibility", ChartLegendToggleIndicatorTitlesVisibility = "Chart.Legend.ToggleIndicatorTitlesVisibility", ChartLegendToggleIndicatorValuesVisibility = "Chart.Legend.ToggleIndicatorValuesVisibility", ChartLegendToggleOhlcValuesVisibility = "Chart.Legend.ToggleOhlcValuesVisibility", ChartLegendToggleOpenMarketStatusVisibility = "Chart.Legend.ToggleOpenMarketStatusVisibility", ChartLegendToggleSymbolVisibility = "Chart.Legend.ToggleSymbolVisibility", ChartLegendToggleVolumeVisibility = "Chart.Legend.ToggleVolumeVisibility", ChartLines = "Chart.Lines", ChartLinesToggleBidAskLinesVisibility = "Chart.Lines.ToggleBidAskLinesVisibility", ChartLinesToggleHighLowLinesVisibility = "Chart.Lines.ToggleHighLowLinesVisibility", ChartLinesToggleAverageLineVisibility = "Chart.Lines.ToggleAverageLineVisibility", ChartLinesToggleSeriesPrevCloseLineVisibility = "Chart.Lines.ToggleSeriesPrevCloseLineVisibility", ChartLinesToggleSeriesPriceLineVisibility = "Chart.Lines.ToggleSeriesPriceLineVisibility", ChartLineToolBarsPatternToggleFlipped = "Chart.LineTool.BarsPattern.ToggleFlipped", ChartLineToolBarsPatternToggleMirrored = "Chart.LineTool.BarsPattern.ToggleMirrored", ChartLineToolClone = "Chart.LineTool.Clone", ChartLineToolCreateLimitOrderFromState = "Chart.LineTool.CreateLimitOrderFromState", ChartLineToolElliotChangeDegreeProperty = "Chart.LineTool.Elliot.ChangeDegreeProperty", ChartLineToolNoSync = "Chart.LineTool.NoSync", ChartLineToolPitchforkChangeTypeToInside = "Chart.LineTool.Pitchfork.ChangeTypeToInside", ChartLineToolPitchforkChangeTypeToModifiedSchiff = "Chart.LineTool.Pitchfork.ChangeTypeToModifiedSchiff", ChartLineToolPitchforkChangeTypeToOriginal = "Chart.LineTool.Pitchfork.ChangeTypeToOriginal", ChartLineToolPitchforkChangeTypeToSchiff = "Chart.LineTool.Pitchfork.ChangeTypeToSchiff", ChartLineToolSyncInLayout = "Chart.LineTool.SyncInLayout", ChartLineToolTemplates = "Chart.LineTool.Templates", ChartLineToolTemplatesApply = "Chart.LineTool.Templates.Apply", ChartLineToolTemplatesApplyDefaults = "Chart.LineTool.Templates.ApplyDefaults", ChartLineToolTemplatesSaveAs = "Chart.LineTool.Templates.SaveAs", ChartLineToolToolbarChangeFontSizeProperty = "Chart.LineTool.Toolbar.ChangeFontSizeProperty", ChartLineToolToolbarChangeLineStyleToDashed = "Chart.LineTool.Toolbar.ChangeLineStyleToDashed", ChartLineToolToolbarChangeLineStyleToDotted = "Chart.LineTool.Toolbar.ChangeLineStyleToDotted", ChartLineToolToolbarChangeLineStyleToSolid = "Chart.LineTool.Toolbar.ChangeLineStyleToSolid", ChartMarksToggleVisibility = "Chart.Marks.ToggleVisibility", ChartMoveChartInLayout = "Chart.MoveChartInLayout", ChartMoveChartInLayoutBack = "Chart.MoveChartInLayout.Back", ChartMoveChartInLayoutForward = "Chart.MoveChartInLayout.Forward", ChartObjectTreeShow = "Chart.ObjectTree.Show", ChartPaneControlsDeletePane = "Chart.PaneControls.DeletePane", ChartPaneControlsMaximizePane = "Chart.PaneControls.MaximizePane", ChartPaneControlsMinimizePane = "Chart.PaneControls.MinimizePane", ChartPaneControlsMovePaneDown = "Chart.PaneControls.MovePaneDown", ChartPaneControlsMovePaneUp = "Chart.PaneControls.MovePaneUp", ChartPaneControlsCollapsePane = "Chart.PaneControls.CollapsePane", ChartPaneControlsRestorePane = "Chart.PaneControls.RestorePane", ChartPriceScaleLabels = "Chart.PriceScale.Labels", ChartPriceScaleLabelsToggleBidAskLabelsVisibility = "Chart.PriceScale.Labels.ToggleBidAskLabelsVisibility", ChartPriceScaleLabelsToggleHighLowPriceLabelsVisibility = "Chart.PriceScale.Labels.ToggleHighLowPriceLabelsVisibility", ChartPriceScaleLabelsToggleAveragePriceLabelVisibility = "Chart.PriceScale.Labels.ToggleAveragePriceLabelVisibility", ChartPriceScaleLabelsToggleIndicatorsNameLabelsVisibility = "Chart.PriceScale.Labels.ToggleIndicatorsNameLabelsVisibility", ChartPriceScaleLabelsToggleIndicatorsValueLabelsVisibility = "Chart.PriceScale.Labels.ToggleIndicatorsValueLabelsVisibility", ChartPriceScaleLabelsToggleNoOverlappingLabelsVisibility = "Chart.PriceScale.Labels.ToggleNoOverlappingLabelsVisibility", ChartPriceScaleLabelsToggleSeriesLastValueVisibility = "Chart.PriceScale.Labels.ToggleSeriesLastValueVisibility", ChartPriceScaleLabelsToggleSymbolNameLabelsVisibility = "Chart.PriceScale.Labels.ToggleSymbolNameLabelsVisibility", ChartPriceScaleLabelsToggleSymbolPrevCloseValueVisibility = "Chart.PriceScale.Labels.ToggleSymbolPrevCloseValueVisibility", ChartPriceScaleMergeAllScales = "Chart.PriceScale.MergeAllScales", ChartPriceScaleMergeAllScalesToLeft = "Chart.PriceScale.MergeAllScalesToLeft", ChartPriceScaleMergeAllScalesToRight = "Chart.PriceScale.MergeAllScalesToRight", ChartPriceScaleMoveToLeft = "Chart.PriceScale.MoveToLeft", ChartPriceScaleMoveToRight = "Chart.PriceScale.MoveToRight", ChartPriceScaleReset = "Chart.PriceScale.Reset", ChartPriceScaleToggleAddOrderPlusButtonVisibility = "Chart.PriceScale.ToggleAddOrderPlusButtonVisibility", ChartPriceScaleToggleAutoScale = "Chart.PriceScale.ToggleAutoScale", ChartPriceScaleToggleAutoScaleSeriesOnly = "Chart.PriceScale.ToggleAutoScaleSeriesOnly", ChartPriceScaleToggleCountdownToBarCloseVisibility = "Chart.PriceScale.ToggleCountdownToBarCloseVisibility", ChartPriceScaleToggleIndexedTo100 = "Chart.PriceScale.ToggleIndexedTo100", ChartPriceScaleToggleInvertScale = "Chart.PriceScale.ToggleInvertScale", ChartPriceScaleToggleLogarithmic = "Chart.PriceScale.ToggleLogarithmic", ChartPriceScaleTogglePercentage = "Chart.PriceScale.TogglePercentage", ChartPriceScaleToggleRegular = "Chart.PriceScale.ToggleRegular", ChartRedo = "Chart.Redo", ChartRemoveAllIndicators = "Chart.RemoveAllIndicators", ChartRemoveAllIndicatorsAndLineTools = "Chart.RemoveAllIndicatorsAndLineTools", ChartRemoveAllLineTools = "Chart.RemoveAllLineTools", ChartScalesReset = "Chart.Scales.Reset", ChartScalesToggleLockPriceToBarRatio = "Chart.Scales.ToggleLockPriceToBarRatio", ChartScrollToLineTool = "Chart.ScrollToLineTool", ChartSelectedObjectHide = "Chart.SelectedObject.Hide", ChartSelectedObjectRemove = "Chart.SelectedObject.Remove", ChartSelectedObjectShow = "Chart.SelectedObject.Show", ChartSelectedObjectShowSettingsDialog = "Chart.SelectedObject.ShowSettingsDialog", ChartSelectedObjectToggleLocked = "Chart.SelectedObject.ToggleLocked", ChartSeriesPriceScaleToggleAutoScale = "Chart.Series.PriceScale.ToggleAutoScale", ChartSeriesPriceScaleToggleIndexedTo100 = "Chart.Series.PriceScale.ToggleIndexedTo100", ChartSeriesPriceScaleToggleInvertPriceScale = "Chart.Series.PriceScale.ToggleInvertPriceScale", ChartSeriesPriceScaleToggleLogarithmic = "Chart.Series.PriceScale.ToggleLogarithmic", ChartSeriesPriceScaleTogglePercentage = "Chart.Series.PriceScale.TogglePercentage", ChartSeriesPriceScaleToggleRegular = "Chart.Series.PriceScale.ToggleRegular", ChartSessionBreaksToggleVisibility = "Chart.SessionBreaks.ToggleVisibility", ChartSetSession = "Chart.SetSession", ChartSourceChangePriceScale = "Chart.Source.ChangePriceScale", ChartSourceMergeDown = "Chart.Source.MergeDown", ChartSourceMergeUp = "Chart.Source.MergeUp", ChartSourceMoveToNoScale = "Chart.Source.MoveToNoScale", ChartSourceMoveToOtherScale = "Chart.Source.MoveToOtherScale", ChartSourceMoveToPane = "Chart.Source.MoveToPane", ChartSourceUnmergeDown = "Chart.Source.UnmergeDown", ChartSourceUnmergeUp = "Chart.Source.UnmergeUp", ChartSourceVisualOrder = "Chart.Source.VisualOrder", ChartSourceVisualOrderBringForward = "Chart.Source.VisualOrder.BringForward", ChartSourceVisualOrderBringToFront = "Chart.Source.VisualOrder.BringToFront", ChartSourceVisualOrderSendBackward = "Chart.Source.VisualOrder.SendBackward", ChartSourceVisualOrderSendToBack = "Chart.Source.VisualOrder.SendToBack", ChartTimeScaleReset = "Chart.TimeScale.Reset", ChartUndo = "Chart.Undo", ChartSourceIntervalsVisibility = "Chart.Source.IntervalsVisibility", ChartSourceIntervalsVisibilityCurrentAndAbove = "Chart.Source.IntervalsVisibility.CurrentAndAbove", ChartSourceIntervalsVisibilityCurrentAndBelow = "Chart.Source.IntervalsVisibility.CurrentAndBelow", ChartSourceIntervalsVisibilityOnlyCurrent = "Chart.Source.IntervalsVisibility.Current", ChartSourceIntervalsVisibilityAll = "Chart.Source.IntervalsVisibility.All", ObjectsTreeCreateGroup = "ObjectsTree.CreateGroup", ObjectsTreeRemoveItem = "ObjectsTree.RemoveItem", ObjectsTreeRenameItem = "ObjectsTree.RenameItem", ObjectsTreeToggleItemLocked = "ObjectsTree.ToggleItemLocked", ObjectsTreeToggleItemVisibility = "ObjectsTree.ToggleItemVisibility", TradingCancelOrder = "Trading.CancelOrder", TradingClosePosition = "Trading.ClosePosition", TradingCustomActionId = "Trading.CustomActionId", TradingDomePlaceLimitOrder = "Trading.DomePlaceLimitOrder", TradingDomePlaceMarketOrder = "Trading.DomePlaceMarketOrder", TradingDomePlaceStopLimitOrder = "Trading.DomePlaceStopLimitOrder", TradingDomePlaceStopOrder = "Trading.DomePlaceStopOrder", TradingEditOrder = "Trading.EditOrder", TradingModifyPosition = "Trading.ModifyPosition", TradingReversePosition = "Trading.ReversePosition", TradingSellBuyButtonsToggleVisibility = "Trading.SellBuyButtonsToggleVisibility", TradingTradeFromChart = "Trading.TradeFromChart", TradingNoOverlapMode = "Trading.NoOverlapMode", WatchlistAddSymbol = "Watchlist.AddSymbol", WatchlistAddSymbolToCompare = "Watchlist.AddSymbolToCompare", WatchlistAddSelectedSymbolsToCompare = "Watchlist.AddSelectedSymbolsToCompare " } export declare const enum ChartStyle { Bar = 0, Candle = 1, Line = 2, Area = 3, Renko = 4, Kagi = 5, PnF = 6, LineBreak = 7, HeikinAshi = 8, HollowCandle = 9, Baseline = 10, HiLo = 12, Column = 13 } export declare const enum ConnectionStatus { Connected = 1, Connecting = 2, Disconnected = 3, Error = 4 } /** * Filled area type. */ export declare const enum FilledAreaType { /** * Filled area type for plots. */ TypePlots = "plot_plot", /** * Filled area type for bands. */ TypeHlines = "hline_hline" } export declare const enum MenuItemType { Separator = "separator", Action = "action" } export declare const enum NotificationType { Error = 0, Success = 1 } export declare const enum OhlcStudyPlotStyle { OhlcBars = "ohlc_bars", OhlcCandles = "ohlc_candles" } export declare const enum OrderStatus { Canceled = 1, Filled = 2, Inactive = 3, Placing = 4, Rejected = 5, Working = 6 } export declare const enum OrderStatusFilter { All = 0, Canceled = 1, Filled = 2, Inactive = 3, Rejected = 5, Working = 6 } export declare const enum OrderTicketFocusControl { LimitPrice = 1, StopPrice = 2, TakeProfit = 3, StopLoss = 4, Quantity = 5 } export declare const enum OrderType { Limit = 1, Market = 2, Stop = 3, StopLimit = 4 } export declare const enum ParentType { Order = 1, Position = 2, Trade = 3 } export declare const enum PriceScaleMode { /** Normal mode of the price scale */ Normal = 0, /** Logarithmic mode of the price scale */ Log = 1, /** Percentage mode of the price scale */ Percentage = 2, /** Indexed to 100 mode of the price scale */ IndexedTo100 = 3 } export declare const enum SeriesStyle { Bars = 0, Candles = 1, Line = 2, Area = 3, HeikenAshi = 8, HollowCandles = 9, Baseline = 10, HiLo = 12, Column = 13, Renko = 4, Kagi = 5, PointAndFigure = 6, LineBreak = 7 } export declare const enum Side { Buy = 1, Sell = -1 } export declare const enum StandardFormatterName { Date = "date", DateOrDateTime = "dateOrDateTime", Default = "default", Fixed = "fixed", VariablePrecision = "variablePrecision", FormatQuantity = "formatQuantity", FormatPrice = "formatPrice", FormatPriceForexSup = "formatPriceForexSup", IntegerSeparated = "integerSeparated", LocalDate = "localDate", LocalDateOrDateTime = "localDateOrDateTime", Percentage = "percentage", Pips = "pips", Profit = "profit", ProfitInInstrumentCurrency = "profitInInstrumentCurrency", Side = "side", PositionSide = "positionSide", Status = "status", Symbol = "symbol", Text = "text", Type = "type", MarginPercent = "marginPercent", Empty = "empty" } export declare const enum StudyInputType { Integer = "integer", Float = "float", Price = "price", Bool = "bool", Text = "text", Symbol = "symbol", Session = "session", Source = "source", Resolution = "resolution", Time = "time", BarTime = "bar_time", Color = "color", Textarea = "text_area" } export declare const enum StudyPlotDisplayTarget { None = 0, Pane = 1, DataWindow = 2, PriceScale = 4, StatusLine = 8, All = 15 } export declare const enum StudyPlotType { Line = "line", Colorer = "colorer", BarColorer = "bar_colorer", BgColorer = "bg_colorer", TextColorer = "text_colorer", OhlcColorer = "ohlc_colorer", CandleWickColorer = "wick_colorer", CandleBorderColorer = "border_colorer", UpColorer = "up_colorer", DownColorer = "down_colorer", Shapes = "shapes", Chars = "chars", Arrows = "arrows", Data = "data", DataOffset = "dataoffset", OhlcOpen = "ohlc_open", OhlcHigh = "ohlc_high", OhlcLow = "ohlc_low", OhlcClose = "ohlc_close" } export declare const enum StudyTargetPriceScale { Right = 0, Left = 1, NoScale = 2 } export declare const enum TimeFrameType { PeriodBack = "period-back", TimeRange = "time-range" } export declare const enum TimeHoursFormat { TwentyFourHours = "24-hours", TwelveHours = "12-hours" } export declare const enum VisibilityType { AlwaysOn = "alwaysOn", VisibleOnMouseOver = "visibleOnMouseOver", AlwaysOff = "alwaysOff" } export declare const widget: ChartingLibraryWidgetConstructor; /** * Returns a build version string. For example "CL v23.012 (internal id e0d59dc3 @ 2022-08-23T06:07:00.808Z)". * * @returns The build version string. */ export declare function version(): string; /** * This is the generic type useful for declaring a nominal type, * which does not structurally matches with the base type and * the other types declared over the same base type * * Usage: * @example * type Index = Nominal; * // let i: Index = 42; // this fails to compile * let i: Index = 42 as Index; // OK * @example * type TagName = Nominal; */ export declare type Nominal = T & { /* eslint-disable-next-line jsdoc/require-jsdoc */ [Symbol.species]: Name; }; /** * Defines a whitelist / blacklist of studies or drawing tools. */ export interface AccessList { /** * List type. * Supported values are: * `black` (all listed items should be disabled), * `white` (only the listed items should be enabled). */ type: "black" | "white"; /** Array of items which should be considered part of the access list */ tools: AccessListItem[]; } export interface AccessListItem { /** * Name of the study / drawing tool. * Use the same name as seen in the UI for drawings, * and use the same names as in the pop-ups for indicators. */ name: string; /** * Whether this study should be visible but look as if it's disabled. * If the study is grayed out and user clicks it, then the `onGrayedObjectClicked` function is called. */ grayed?: boolean; } /** Column description for an account manager table */ export interface AccountManagerColumnBase { /** Column title. It will be displayed in the table's header row. */ label: string; /** * Horizontal alignment of the cell value. The default value is `left`. * * | alignment | description | * |--------------|----------------| * | left | It aligns the cell value to the left | * | right | It aligns the cell value to the right | */ alignment?: CellAlignment; /** Column id. Unique identifier of column. */ id: string; /** * Name of the formatter to be used for data formatting. It can be one of two types - `StandardFormatterName` or `FormatterName`. If `formatter` is not set, then the value is displayed as is. * Formatter can be a default or a custom one. * * Default formatter names are listed in `StandardFormatterName` enumerator. If you want to use a custom formatter, you must typecast its name to `FormatterName` to confirm your confidence that you are using the correct name. * * Here is the list of default formatters: * * | name | description | * | ---- | ----------- | * | `StandardFormatterName.Date` | Displays the date or time. | * | `StandardFormatterName.DateOrDateTime` | Displays the date or date and time. This formatter accepts an `{dateOrDateTime: number, hasTime: boolean}` object. If `hasTime` is set to `true` then the date and time are displayed. Otherwise only the date is displayed.| * | `StandardFormatterName.Fixed` | Displays a number with 2 decimal places. | * | `StandardFormatterName.FormatPrice` | Displays symbol's price. | * | `StandardFormatterName.FormatQuantity` | Displays an integer or floating point quantity, separates thousands groups with a space. | * | `StandardFormatterName.FormatPriceForexSup` | The same as `formatPrice`, but it makes the last character of the price superscripted. It works only if instrument type is set to `forex`.| * | `StandardFormatterName.LocalDate` | Displays the local date or time. | * | `StandardFormatterName.LocalDateOrDateTime` | The same as `StandardFormatterName.DateOrDateTime`, but it displays time in the local timezone. | * | `StandardFormatterName.Pips` | Displays a number with 1 decimal place. | * | `StandardFormatterName.Profit` | Displays profit in account currency. It also adds the `+` sign, separates thousands and changes the cell text color to red or green. | * | `StandardFormatterName.ProfitInInstrumentCurrency` | Displays profit in instrument currency. It also adds the `+` sign, separates thousands and changes the cell text color to red or green. | * | `StandardFormatterName.Side` | It is used to display the side: Sell or Buy. | * | `StandardFormatterName.PositionSide` | It is used to display the position side: Short or Long. | * | `StandardFormatterName.Status` | It is used to format the `status`. | * | `StandardFormatterName.Symbol` | It is used for a symbol field. It displays `brokerSymbol`, but when you click on a symbol the chart changes according to the `symbol` field. | * | `StandardFormatterName.Text` | Displays a text value. | * | `StandardFormatterName.Type` | It is used to display the type of order: Limit/Stop/StopLimit/Market. | * | `StandardFormatterName.VariablePrecision` | Displays a number with variable precision. | */ formatter?: TFormatterName; /** * `dataFields` is an array with data object fields that is used to get the data to display in a column. * * The displayed value in the column will only change if one of the corresponding data object values change. * * If the `formatter` is not set, the displayed values will be space-separated in the column. * * If a `formatter` is specified, it will only get the specified values. * * Specify an empty array as the `dataFields` and the formatter will receive the entire data object. * * **Example** * Example * * - If you have column with `dataFields` set as `['avgPrice', 'qty']`, then displayed value will update only if `avgPrice` or `qty` values of the data object have been changed. * - If you have column with `dataFields` set as `[]`, then displayed value will update if some data object values have been changed. */ dataFields: TFormatterName extends StandardFormatterName ? StandardFormattersDependenciesMapping[TFormatterName] : string[]; /** * Data object key that is used for data sorting * * If `sortProp` is not provided, then the first element of the `dataFields` array will be used. If the `dataFields` array is empty, then column sorting will be unavailable. */ sortProp?: string; /** When set to `true` will prevent column sorting. */ notSortable?: boolean; /** Tooltip string for the column. */ help?: string; /** * `highlightDiff` can be set with `StandardFormatterName.FormatPrice` and `StandardFormatterName.FormatPriceForexSup` formatters to highlight the changes of the field. If set to `true` then custom formatters will also get previous values. */ highlightDiff?: boolean; /** When set to `true` will prevent the column from hiding. */ notHideable?: boolean; /** When set to `true` will hide the column by default */ hideByDefault?: boolean; /** Key of the row object that is used to get the tooltip to display when hovering over a cell. * The tooltip property refers to an object whose keys are property names and * values are the corresponding tooltips. */ tooltipProperty?: string; /** If set to `true`, the first character of every word in the sentence in the column * will be capitalized. The default value is `true`. */ isCapitalize?: boolean; /** When set to `true` any zero values will be hidden. Default is `true` */ showZeroValues?: boolean; } export interface AccountManagerInfo { /** Name of the broker */ accountTitle: string; /** Custom fields which will always be displayed above the pages. */ summary: AccountManagerSummaryField[]; /** * Optional array to define custom formatters. * Each description is an object with the following fields: * * 1. `name`: FormatterName * - Unique name of a formatter. * * 1. `formatText`: [TableFormatTextFunction](#tableformattextfunction) * -Function that is used for formatting of a cell value to `string`. Required because used to generate exported data. * * 1. `formatElement`: [CustomTableFormatElementFunction](#customtableformatelementfunction) | undefined * - Optional function that is used for formatting of a cell value to `string` or `HTMLElement`. * * If the `formatElement` function is provided, then only it will be used to format the displayed values, otherwise * `formatText` will be used. If you need to only display `string` values it is better to use only `formatText` for performance reasons. * * **Example** * ```ts * { * name: 'closeButton' as FormatterName, // Typecast to FormatterName. Use constant in real code * formatText: () => '', // Returns an empty string because we don't need to display this in the exported data * formatElement: ({ values: [id] }: TableFormatterInputs<[id: string]>) => { * const button = document.createElement('button'); * * button.innerText = 'Close'; * * button.addEventListener('click', () => { * event.stopPropagation(); * * closePosition(id); * }); * * return button; * }, * } * ``` */ customFormatters?: CustomTableElementFormatter[]; /** Columns description that you want to be displayed on the Orders page. * You can display any field of an {@link Order} * or add your own fields to an order object and display them. */ orderColumns: OrderTableColumn[]; /** Optional sorting of the orders table. */ orderColumnsSorting?: SortingParameters; /** History page will be displayed if it exists. All orders from previous sessions will be shown in the History. */ historyColumns?: AccountManagerColumn[]; /** Optional sorting of the history table. */ historyColumnsSorting?: SortingParameters; /** * You can display any field of a {@link Position} * or add your own fields to a position object and display them. */ positionColumns?: AccountManagerColumn[]; /** * You can display any field of a {@link Trade} * or add your own fields to a trade object and display them. */ tradeColumns?: AccountManagerColumn[]; /** You can add new tabs in the Account Manager by using `pages`. Each tab is a set of tables. */ pages: AccountManagerPage[]; /** Optional list of statuses to be used in the orders filter. Default list is used if it hasn't been set. */ possibleOrderStatuses?: OrderStatus[]; /** Margin used */ marginUsed?: IWatchedValue; /** * Optional function to create a custom context menu. * @param contextMenuEvent - MouseEvent or TouchEvent object passed by a browser * @param activePageActions - array of `ActionMetaInfo` items for the current page * @returns `Promise` that is resolved with an array of `ActionMetaInfo` */ contextMenuActions?(contextMenuEvent: MouseEvent | TouchEvent, activePageActions: ActionMetaInfo[]): Promise; } /** A description of an additional Account Manager tab. */ export interface AccountManagerPage { /** Unique identifier of a page */ id: string; /** Page title. It is the tab name. */ title: string; /** It is possible to display one or more tables in this tab. */ tables: AccountManagerTable[]; } /** Custom field that will always be shown above the pages of the Account manager */ export interface AccountManagerSummaryField { /** Text to display for the summary field */ text: string; /** A WatchedValue object that can be used to read the state of field. */ wValue: IWatchedValueReadonly; /** * Name of the formatter to be used for data formatting. If `formatter` is not * set the value is displayed as is. Formatter can be a default or a custom one. */ formatter?: StandardFormatterName; /** Optional parameter which can be set to display the field by default. */ isDefault?: boolean; } /** * Account Summary table meta-info * **NOTE**: make sure that you have a unique string `id` field in each row to identify it. */ export interface AccountManagerTable { /** Unique identifier of a table. */ id: string; /** Optional title of a table. */ title?: string; /** Table columns */ columns: AccountManagerColumn[]; /** Optional sorting of the table. If set, then the table will be sorted by these parameters, if the user has not enabled sorting by a specific column. */ initialSorting?: SortingParameters; /** This delegate is used to watch the data changes and update the table. * Pass new account manager data row by row to the `fire` method of the delegate. */ changeDelegate: ISubscription<(data: {}) => void>; /** Option flags for the table. */ flags?: AccountManagerTableFlags; /** * This function is used to request table data. It should return Promise (or Deferred) and resolve it with an array of data rows. * * Each row is an object. Keys of this object are column names with the corresponding values. * * There is a predefined field `isTotalRow` which can be used to mark a row that should be at the bottom of the table. * @param paginationLastId - Last pagination id */ getData(paginationLastId?: string | number): Promise<{}[]>; } /** Boolean options for the account manager table */ export interface AccountManagerTableFlags { /** Does the table support pagination */ supportPagination?: boolean; } export interface ActionDescription { /** Displayed text for action */ text?: "-" | string; /** Is a menu separator */ separator?: boolean; /** Keyboard shortcut for the action. Displayed as hint text. */ shortcut?: string; /** Tooltip text to be displayed when hovering over the action item. */ tooltip?: string; /** Value of the checkbox. */ checked?: boolean; /** Getter to retrieve the current checkbox value. */ checkedStateSource?: () => boolean; /** Whether menu action represents a checkbox state. Set it to true if you need a checkbox. */ checkable?: boolean; /** Whether the action is enabled. Set to false to disabled the action. */ enabled?: boolean; /** External link (url) which will be opened upon clicking the menu item. */ externalLink?: boolean; /** * A string of SVG icon for an action. A string should be a string representation of SVG (not a path/URL). */ icon?: string; } /** Menu action which provides a callback function to be executed. Action is executed when user clicks the item. */ export interface ActionDescriptionWithCallback extends ActionDescription { /** Action to be executed when user clicks the menu item. */ action: (a?: ActionDescription) => void; } export interface ActionOptions extends Partial>, Pick { /** * A function which will be called when an action should be executed (e.g. when a user clicks on the item). */ onExecute?: OnActionExecuteHandler; } export interface ActionState { /** * Human-readable, non-unique ID of an action item. Similar to {@link label}, but language-agnostic. */ actionId: ActionId; /** Is active */ active: boolean; /** * Text title of an action */ label: string; /** * Whether an action is disabled or not (disabled actions are usually cannot be executed and displayed grayed out) */ disabled: boolean; /** * Sub-items of an action */ subItems: IActionVariant[]; /** * Whether an action should have a checkbox next to it. */ checkable: boolean; /** * If {@link checkable} is `true` then whether current state is checked or not. */ checked: boolean; /** * A hint of an action. */ hint?: string; /** * A string of SVG icon for an action. A string should be a string representation of SVG (not a path/URL). */ icon?: string; /** * If {@link checkable} is `true` then an icon to be used when {@link checked} is `true`. */ iconChecked?: string; /** * Whether an action is still in loading state (it means that it's data is not ready yet). * Usually in this case a spinner/loader will be displayed instead of this action. */ loading: boolean; /** * A string that represents a shortcut hint for this action. */ shortcutHint?: string; } export interface ActionsFactory { /** * Creates an action with provided options. */ createAction: (options: ActionOptions) => IUpdatableAction; /** * Creates an action that will wait for a promise to get its options. * In terms of GUI until a promise is resolved the loader/spinner will be displayed. */ createAsyncAction: (loader: () => Promise) => IUpdatableAction; /** * Creates a separator item. */ createSeparator: () => ISeparator; } /** * custom symbol info fields to be shown in the Symbol Info dialog */ export interface AdditionalSymbolInfoField { /** the name of the new symbol info */ title: string; /** used to look up a property from the symbol info returned from the chart's datafeed */ propertyName: string; } export interface AreaStylePreferences { /** Top color */ color1: string; /** Bottom color */ color2: string; /** Line Color */ linecolor: string; /** Line Style {@link LineStyle} */ linestyle: number; /** Line width */ linewidth: number; /** * Transparency. Range [0..100] * `0` - fully opaque, * `100` - fully transparent. * * **Note**: Rather use `rgba` color string for setting transparency. */ transparency: number; } export interface AvailableZOrderOperations { /** 'Bring Forward' is possible */ bringForwardEnabled: boolean; /** 'Bring to Front' is possible */ bringToFrontEnabled: boolean; /** 'Send Backward' is possible */ sendBackwardEnabled: boolean; /** 'Send to Back' is possible */ sendToBackEnabled: boolean; } /** * Bar data point */ export interface Bar { /** Bar time. * Amount of **milliseconds** since Unix epoch start in **UTC** timezone. * `time` for daily bars is expected to be a trading day (not session start day) at 00:00 UTC. * Charting Library adjusts time according to `session` from {@link LibrarySymbolInfo}. */ time: number; /** Opening price */ open: number; /** High price */ high: number; /** Low price */ low: number; /** Closing price */ close: number; /** Trading Volume */ volume?: number; } export interface BarStylePreferences { /** Up bar color */ upColor: string; /** Down bar color */ downColor: string; /** Bar color determined by previous close value */ barColorsOnPrevClose: boolean; /** Whether to draw opening value for bar */ dontDrawOpen: boolean; /** Draw thin bars. Default - `true` */ thinBars: boolean; } export interface BaseInputFieldValidatorResult { /** Is the base input value valid */ valid: boolean; } export interface BaselineStylePreferences { /** Top fill color of positive area */ topFillColor1: string; /** Bottom fill color of positive area */ topFillColor2: string; /** Top fill color of negative area */ bottomFillColor1: string; /** Bottom fill color of negative area */ bottomFillColor2: string; /** Positive area line color */ topLineColor: string; /** Negative area line color */ bottomLineColor: string; /** Baseline line color */ baselineColor: string; /** Positive area line width */ topLineWidth: number; /** Negative area line width */ bottomLineWidth: number; /** * Transparency. Range [0..100] * `0` - fully opaque, * `100` - fully transparent. * * **Note**: Rather use `rgba` color string for setting transparency. */ transparency: number; /** Baseline level percentage */ baseLevelPercentage: number; } export interface BracketOrder extends BracketOrderBase, CustomFields { } export interface BracketOrderBase extends PlacedOrderBase { /** If order is a bracket then this should contain base order/position id. */ parentId: string; /** Type of the bracket's parent */ parentType: ParentType; } export interface Brackets { /** Stop loss */ stopLoss?: number; /** Take Profit */ takeProfit?: number; /** Trailing Stop Pips */ trailingStopPips?: number; } export interface BrokerConfigFlags { /** * Display broker symbol name in the symbol search. You may usually want to disable it if broker symbols are the same or you are using internal numbers as broker symbol names. * @default true */ supportDisplayBrokerNameInSymbolSearch?: boolean; /** * This flag can be used to change "Amount" to "Quantity" in the Order Dialog. * @default false */ showQuantityInsteadOfAmount?: boolean; /** * Broker supports brackets (take profit and stop loss) for orders. * @default false */ supportOrderBrackets?: boolean; /** * Broker supports trailing stop orders. * If this flag is set to `true`, then the chart displays trailing stop orders and a user can place a trailing stop order using the Order Dialog. * @default false */ supportTrailingStop?: boolean; /** * Broker supports positions. * If it is set to `false`, the Positions tab in the Account Manager will be hidden. * @default true */ supportPositions?: boolean; /** * Broker supports brackets (take profit and stop loss orders) for positions. * If this flag is set to `true` the Chart will display an Edit button for positions and add `Edit position...` to the context menu of a position. * @default false */ supportPositionBrackets?: boolean; /** * Broker supports brackets for trades (take profit and stop loss orders). * If this flag is set to `true` the Chart will display an Edit button for trades (individual positions) and add `Edit position...` to the context menu of a trade. * @default false */ supportTradeBrackets?: boolean; /** * Broker supports individual positions (trades). * If it is set to `true`, there will be two tabs in the Account Manager - Individual Positions and Net Positions. * @default false */ supportTrades?: boolean; /** * Broker supports closing of a position. * If it is not supported by broker, Chart will have the close button, but it will place a closing order. * @default false */ supportClosePosition?: boolean; /** * Individual positions (trades) can be closed. * @default false */ supportCloseTrade?: boolean; /** * Using this flag you can disable existing order's price modification. * @default true */ supportModifyOrderPrice?: boolean; /** * Using this flag you can disable existing order's quantity modification. * @default true */ supportEditAmount?: boolean; /** * Using this flag you can disable existing order's brackets modification. If you set it to `false`, * additional fields will be disabled in the Order Dialog on the chart, * and 'Modify' button will be hidden from the chart and in the Account Manager. * @default true */ supportModifyBrackets?: boolean; /** * Level2 data is used for DOM widget. `subscribeDepth` and `unsubscribeDepth` should be implemented. * @default false */ supportLevel2Data?: boolean; /** * Does broker support Depth of Market. * @default false */ supportDOM?: boolean; /** * Supporting multiposition prevents creating the default implementation for a reversing position. * @default false */ supportMultiposition?: boolean; /** * Broker provides PL for a position. If the broker calculates profit/loss by itself it should call `plUpdate` as soon as PL is changed. * Otherwise Chart will calculate PL as a difference between the current trade and an average price of the position. * @default true */ supportPLUpdate?: boolean; /** * Broker supports reversing of a position. * If it is not supported by broker, the reverse position button will be hidden. * @default false */ supportReversePosition?: boolean; /** * Broker natively supports reversing of a position. * If it is not natively supported by broker, Chart will place a reversing order. * @default false */ supportNativeReversePosition?: boolean; /** * This flag adds market orders type to the Order Dialog. * @default true */ supportMarketOrders?: boolean; /** * This flag adds limit orders type to the Order Dialog. * @default true */ supportLimitOrders?: boolean; /** * This flag adds stop orders type to the Order Dialog. * @default true */ supportStopOrders?: boolean; /** * This flag adds stop-limit orders type to the Order Dialog. * @default false */ supportStopLimitOrders?: boolean; /** * Does broker support demo live switcher. * @default true */ supportDemoLiveSwitcher?: boolean; /** * Using this flag you can disable brackets for market orders. * @default true */ supportMarketBrackets?: boolean; /** * Broker supports symbol search * @default false */ supportSymbolSearch?: boolean; /** * Using this flag you can enable modification of the duration of the existing order. * @default false */ supportModifyDuration?: boolean; /** * Broker supports modifying trailing stop orders. * @default true */ supportModifyTrailingStop?: boolean; /** * Broker supports margin. * If the broker supports margin it should call `marginAvailableUpdate` ({@link IBrokerConnectionAdapterHost.marginAvailableUpdate}) when the Trading Terminal subscribes using `subscribeMarginAvailable` ({@link IBrokerWithoutRealtime.subscribeMarginAvailable}). * @default false */ supportMargin?: boolean; /** * Calculate Profit / Loss using last value. * @default false */ calculatePLUsingLast?: boolean; /** * Broker provides the estimated commission, fees, margin and other order information before placing the order without actually placing it. * @default false */ supportPlaceOrderPreview?: boolean; /** * Broker provides the estimated commission, fees, margin and other order information before modifying the order without actually modifying it. * @default false */ supportModifyOrderPreview?: boolean; /** * Broker supports leverage. If the flag is set to `true`, broker will calculate leverage using `leverageInfo` ({@link IBrokerWithoutRealtime.leverageinfo}) method. * @default false */ supportLeverage?: boolean; /** * Broker supports leverage button. If the flag is set to `true`, a leverage input field will appear in the Order Widget. Click on the input field will activate a dedicated Leverage Dialog. * @default true */ supportLeverageButton?: boolean; /** * Broker supports orders history. If it is set to `true`, there will be an additional tab in the Account Manager - Orders History. * The `ordersHistory` method should be implemented. It should return a list of orders with the `filled`, `cancelled` and `rejected` statuses from previous trade sessions. * @default false */ supportOrdersHistory?: boolean; /** * Using this flag you can disable adding brackets to the existing order. * @default true */ supportAddBracketsToExistingOrder?: boolean; /** * Used for crypto currencies only. Allows to get crypto balances for an account. Balances are displayed as the first table of the Account Summary tab. * @default false */ supportBalances?: boolean; /** * Closing a position cancels its brackets. * @default false */ closePositionCancelsOrders?: boolean; /** * `Stop Loss` and `Take Profit` are added or removed only together. * @default false */ supportOnlyPairPositionBrackets?: boolean; /** * Whether the account is used to exchange(trade) crypto currencies. * This flag switches the Order Dialog to the Crypto Exchange mode. It adds second currency quantity control, currency labels etc. * @default false */ supportCryptoExchangeOrderTicket?: boolean; /** * With this flag you can show a checkbox to disable the confirmation dialog display * @default false */ supportConfirmations?: boolean; /** * Using this flag you can display PL in instrument currency. * @default false */ positionPLInInstrumentCurrency?: boolean; /** * Does broker support partial position closing * @default false */ supportPartialClosePosition?: boolean; /** * Does broker support partial trade closing * @default false */ supportPartialCloseTrade?: boolean; /** * Cancelling a bracket (take profit or stop loss) cancels its pair. * @default false */ supportCancellingBothBracketsOnly?: boolean; /** * Does broker support crypto brackets * @default false */ supportCryptoBrackets?: boolean; /** * Using this flag you can show/hide the `Notifications log` tab in the account manager. * @default true */ showNotificationsLog?: boolean; /** * Whether stop orders should behave like Market-if-touched in both directions. * Enabling this flag prevents the check of stop price direction from the stop limit order dialog. * @default false */ supportStopOrdersInBothDirections?: boolean; /** * Enabling this flag prevents the check of stop price direction from the stop limit order dialog. */ supportStopLimitOrdersInBothDirections?: boolean; /** * Broker supports executions. * If this flag is set to `true` the Chart will display executions. * @default false */ supportExecutions?: boolean; /** * Does broker support modifying order type * @default false */ supportModifyOrderType?: boolean; /** * Trading account requires closing of trades in FIFO order. * @default false */ requiresFIFOCloseTrades?: boolean; /** * @deprecated */ supportBrackets?: boolean; /** * Use supportModifyOrderPrice, supportEditAmount and supportModifyBrackets instead. * @deprecated */ supportModifyOrder?: boolean; } export interface BrokerCustomUI { /** * Shows standard Order Dialog to create or modify an order and executes handler if Buy/Sell/Modify is pressed. * @param {OrderTemplate|Order} order - order to be placed or modified * @param {OrderTicketFocusControl} focus? - Control to focus on when dialog is opened */ showOrderDialog?: (order: OrderTemplate | Order, focus?: OrderTicketFocusControl) => Promise; /** * Shows the Position Dialog * @param {Position|Trade} position - position to be placed or modified * @param {Brackets} brackets - brackets for the position * @param {OrderTicketFocusControl} focus? - Control to focus on when dialog is opened */ showPositionDialog?: (position: Position | Trade, brackets: Brackets, focus?: OrderTicketFocusControl) => Promise; /** * Shows a confirmation dialog and executes handler if YES/OK is pressed. * @param {Order} order - order to be cancelled */ showCancelOrderDialog?: (order: Order) => Promise; /** * Shows the Close Position Dialog. * @param {Position} position - position to be closed */ showClosePositionDialog?: (position: Position) => Promise; } export interface CandleStylePreferences { /** Body color for an up candle */ upColor: string; /** Body color for a down candle */ downColor: string; /** Whether to draw the candle wick */ drawWick: boolean; /** Whether to draw the candle body border */ drawBorder: boolean; /** Whether to draw the candle body */ drawBody: boolean; /** Candle border color */ borderColor: string; /** Up candle border color */ borderUpColor: string; /** Down candle border color */ borderDownColor: string; /** Candle wick color */ wickColor: string; /** Up candle wick color */ wickUpColor: string; /** Down candle wick color */ wickDownColor: string; /** Bar color determined by previous close value */ barColorsOnPrevClose: boolean; } export interface ChangeAccountSolution { /** id of a sub-account suitable for trading the symbol */ changeAccount: AccountId; } export interface ChangeSymbolSolution { /** the symbol suitable for trading with current sub-account */ changeSymbol: string; } export interface ChangeThemeOptions { /** Disable undo for the theme change */ disableUndo: boolean; } /** * Saved chart data */ export interface ChartData { /** unique ID of the chart (may be `undefined` if it wasn't saved before) */ id: string | undefined; /** name of the chart */ name: string; /** symbol of the chart */ symbol: string; /** resolution of the chart */ resolution: ResolutionString; /** content of the chart */ content: string; } /** * Meta information about a saved chart */ export interface ChartMetaInfo { /** unique ID of the chart. */ id: number; /** name of the chart */ name: string; /** symbol of the chart */ symbol: string; /** resolution of the chart */ resolution: ResolutionString; /** UNIX time when the chart was last modified */ timestamp: number; } /** * Property overrides that can be used with {@link IChartingLibraryWidget.applyOverrides}. */ export interface ChartPropertiesOverrides extends StudyOverrides { /** * A timezone ID. The default value depends on the locale. */ "timezone": TimezoneId; /** * A price scale selection strategy. Determines where price scales should be placed: on the left, on the right, or spread evenly (auto). * * @default 'auto' */ "priceScaleSelectionStrategyName": "left" | "right" | "auto"; /** * Pane background type. * * @default 'solid' */ "paneProperties.backgroundType": ColorTypes; /** * Pane background color. * * @default '#ffffff' */ "paneProperties.background": string; /** * Pane background gradient start color. * * @default '#ffffff' */ "paneProperties.backgroundGradientStartColor": string; /** * Pane background gradient end color. * * @default '#ffffff' */ "paneProperties.backgroundGradientEndColor": string; /** * Pane vertical grid color. * * @default 'rgba(42, 46, 57, 0.06)' */ "paneProperties.vertGridProperties.color": string; /** * Pane vertical grid line style. * * @default LineStyle.Solid */ "paneProperties.vertGridProperties.style": LineStyle; /** * Pane horizontal grid color. * * @default 'rgba(42, 46, 57, 0.06)' */ "paneProperties.horzGridProperties.color": string; /** * Pane horizontal grid line style. * * @default LineStyle.Solid */ "paneProperties.horzGridProperties.style": LineStyle; /** * Crosshair color. * * @default '#9598A1' */ "crossHairProperties.color": string; /** * Crosshair style. * * @default LineStyle.Dashed */ "crossHairProperties.style": LineStyle; /** * Crosshair transparency. * * @default 0 */ "crossHairProperties.transparency": number; /** * Crosshair width. * * @default 1 */ "crossHairProperties.width": number; /** * Pane auto scaling top margin percentage. * * @default 10 */ "paneProperties.topMargin": number; /** * Pane auto scaling bottom margin percentage. * * @default 8 */ "paneProperties.bottomMargin": number; /** * Study legend input values visiblity. * * @default true */ "paneProperties.legendProperties.showStudyArguments": boolean; /** * Study legend title visibility. * * @default true */ "paneProperties.legendProperties.showStudyTitles": boolean; /** * Study legend value visibility. * * @default true */ "paneProperties.legendProperties.showStudyValues": boolean; /** * Series legend title visibility. * * @default true */ "paneProperties.legendProperties.showSeriesTitle": boolean; /** * Study legend OHLC values visibility. * * @default true */ "paneProperties.legendProperties.showSeriesOHLC": boolean; /** * Series legend change value visibility. * * @default true */ "paneProperties.legendProperties.showBarChange": boolean; /** * Series legend volume value visibility. * * @default false */ "paneProperties.legendProperties.showVolume": boolean; /** * Legend background visibility. * * @default true */ "paneProperties.legendProperties.showBackground": boolean; /** * Legend background transparency percentage. * * @default 50 */ "paneProperties.legendProperties.backgroundTransparency": number; /** * Legend separator color. * * @default '#E0E3EB' */ "paneProperties.paneProperties.separatorColor": string; /** * Scales (axis) border line color. * * @default 'rgba(42, 46, 57, 0)' */ "scalesProperties.lineColor": string; /** * Scales (axis) text color. * * @default '#131722' */ "scalesProperties.textColor": string; /** * Scales (axis) font size. * * @default 12 */ "scalesProperties.fontSize": number; /** * Series last value label visibility. * * @default true */ "scalesProperties.showSeriesLastValue": boolean; /** * Series last value label display mode. * * @default PriceAxisLastValueMode.LastValueAccordingToScale */ "scalesProperties.seriesLastValueMode": PriceAxisLastValueMode; /** * Study label value label visibility. * * @default true */ "scalesProperties.showStudyLastValue": boolean; /** * Symbol name label visibility. * * @default false */ "scalesProperties.showSymbolLabels": boolean; /** * Study plot labels visibility. * * @default false */ "scalesProperties.showStudyPlotLabels": boolean; /** * Bid/ask labels visibility. * * @default false */ "scalesProperties.showBidAskLabels": boolean; /** * Pre/post market price labels visibility. * * @default true */ "scalesProperties.showPrePostMarketPriceLabel": boolean; /** * Scales (axis) highlight color. * * @default 'rgba(41, 98, 255, 0.25)' */ "scalesProperties.axisHighlightColor": string; /** * Scales (axis) highlight label background color. * * @default '#2962FF' */ "scalesProperties.axisLineToolLabelBackgroundColorCommon": string; /** * Scales (axis) background label active background color. * * @default '#143EB3' */ "scalesProperties.axisLineToolLabelBackgroundColorActive": string; /** * Price scale crosshair label visibility. * * @default true */ "scalesProperties.showPriceScaleCrosshairLabel": boolean; /** * Time scale crosshair label visibility. * * @default true */ "scalesProperties.showTimeScaleCrosshairLabel": boolean; /** * Crosshair label light theme background color. * * @default '#131722' */ "scalesProperties.crosshairLabelBgColorLight": string; /** * Crosshair label dark theme background color. * * @default '#363A45' */ "scalesProperties.crosshairLabelBgColorDark": string; /** * Main series chart style. * * @default ChartStyle.Candle */ "mainSeriesProperties.style": ChartStyle; /** * Main series bar countdown visibility. * * @default false */ "mainSeriesProperties.showCountdown": boolean; /** * Main series bid & ask visibility * * @default false */ "mainSeriesProperties.bidAsk.visible": boolean; /** * Style of the line for bid & ask * * @default LineStyle.Dotted */ "mainSeriesProperties.bidAsk.lineStyle": LineStyle; /** * Width of the line for bid & ask * * @default 1 */ "mainSeriesProperties.bidAsk.lineWidth": number; /** * Color line for the bid * * @default '#2962FF' */ "mainSeriesProperties.bidAsk.bidLineColor": string; /** * Color line for the ask * * @default '#F7525F' */ "mainSeriesProperties.bidAsk.askLineColor": string; /** * High/low price lines visibility. * * @default false */ "mainSeriesProperties.highLowAvgPrice.highLowPriceLinesVisible": boolean; /** * High/low price lines label visibility. * * @default false */ "mainSeriesProperties.highLowAvgPrice.highLowPriceLabelsVisible": boolean; /** * Average close price lines visibility. * * @default false */ "mainSeriesProperties.highLowAvgPrice.averageClosePriceLineVisible": boolean; /** * Average close price lines label visibility. * * @default false */ "mainSeriesProperties.highLowAvgPrice.averageClosePriceLabelVisible": boolean; /** * High/low price lines color. * * @default "" */ "mainSeriesProperties.highLowAvgPrice.highLowPriceLinesColor": string; /** * * High/low price lines width. * * @default 1 */ "mainSeriesProperties.highLowAvgPrice.highLowPriceLinesWidth": number; /** * * Average close price lines color. * * @default "" */ "mainSeriesProperties.highLowAvgPrice.averagePriceLineColor": string; /** * * Average close price lines width. * * @default 1 */ "mainSeriesProperties.highLowAvgPrice.averagePriceLineWidth": number; /** * Main series visibility. * * @default true */ "mainSeriesProperties.visible": boolean; /** * Main series price line visibility. * * @default true */ "mainSeriesProperties.showPriceLine": boolean; /** * * Main series price line width. * * @default 1 */ "mainSeriesProperties.priceLineWidth": number; /** * Main series price line color. * * @default "" */ "mainSeriesProperties.priceLineColor": string; /** * Main series base line color. * * @default "#B2B5BE" */ "mainSeriesProperties.baseLineColor": string; /** * Main series previous close price line visibility. * * @default false */ "mainSeriesProperties.showPrevClosePriceLine": boolean; /** * Main series previous close price line width. * * @default 1 */ "mainSeriesProperties.prevClosePriceLineWidth": number; /** * Main series previous close price line color. * * @default "#555555" */ "mainSeriesProperties.prevClosePriceLineColor": string; /** * Main series minimum tick behaviour. * * @default "default" * * @example * * ```javascript * // reset minTick to default * tvWidget.applyOverrides({ 'mainSeriesProperties.minTick': 'default' }); * * // Set main series minTick to { priceScale: 10000, minMove: 1, frac: false } * tvWidget.applyOverrides({ 'mainSeriesProperties.minTick': '10000,1,false' }); * * // Set default minTick for overlay studies to { priceScale: 10000, minMove: 1, frac: false } * tvWidget.applyStudiesOverrides({ 'overlay.minTick': '10000,1,false' }); * ``` */ "mainSeriesProperties.minTick": string; /** * Main series legend font size. * * @default 16 */ "mainSeriesProperties.statusViewStyle.fontSize": number; /** * Main series legend exchange visibility. * * @default true */ "mainSeriesProperties.statusViewStyle.showExchange": boolean; /** * Main series legend interval visibility. * * @default true */ "mainSeriesProperties.statusViewStyle.showInterval": boolean; /** * Main series legend text style. * * @default "description" */ "mainSeriesProperties.statusViewStyle.symbolTextSource": SeriesStatusViewSymbolTextSource; /** * Main series candle style up color. * * @default "#089981" */ "mainSeriesProperties.candleStyle.upColor": string; /** * Main series candle style down color. * * @default "#F23645" */ "mainSeriesProperties.candleStyle.downColor": string; /** * Main series candle style wick visibility. * * @default true */ "mainSeriesProperties.candleStyle.drawWick": boolean; /** * Main series candle style border visibility. * * @default true */ "mainSeriesProperties.candleStyle.drawBorder": boolean; /** * * Main series candle style border color. * * @default "#378658" */ "mainSeriesProperties.candleStyle.borderColor": string; /** * * Main series candle style border up color. * * @default "#089981" */ "mainSeriesProperties.candleStyle.borderUpColor": string; /** * Main series candle style border down color. * * @default "#F23645" */ "mainSeriesProperties.candleStyle.borderDownColor": string; /** * Main series candle style wick color. * * @default "#737375" */ "mainSeriesProperties.candleStyle.wickColor": string; /** * Main series candle style wick up color. * * @default "#089981" */ "mainSeriesProperties.candleStyle.wickUpColor": string; /** * Main series candle style wick down color. * * @default "#F23645" */ "mainSeriesProperties.candleStyle.wickDownColor": string; /** * * Main series candle style color on previous close behaviour. * * @default false */ "mainSeriesProperties.candleStyle.barColorsOnPrevClose": boolean; /** * Main series candle style body visibility. * * @default true */ "mainSeriesProperties.candleStyle.drawBody": boolean; /** * Main series hollow candle style up color. * * @default "#089981" */ "mainSeriesProperties.hollowCandleStyle.upColor": string; /** * Main series hollow candle style down color. * * @default "#F23645" */ "mainSeriesProperties.hollowCandleStyle.downColor": string; /** * Main series hollow candle style wick visibility. * * @default true */ "mainSeriesProperties.hollowCandleStyle.drawWick": boolean; /** * Main series hollow candle style border visibility. * * @default true */ "mainSeriesProperties.hollowCandleStyle.drawBorder": boolean; /** * Main series hollow candle style border color. * * @default "#378658" */ "mainSeriesProperties.hollowCandleStyle.borderColor": string; /** * Main series hollow candle style border up color. * * @default "#089981" */ "mainSeriesProperties.hollowCandleStyle.borderUpColor": string; /** * Main series hollow candle style down color. * * @default "#F23645" */ "mainSeriesProperties.hollowCandleStyle.borderDownColor": string; /** * Main series hollow candle style wick color. * * @default "#737375" */ "mainSeriesProperties.hollowCandleStyle.wickColor": string; /** * Main series hollow candle style wick up color. * * @default "#089981" */ "mainSeriesProperties.hollowCandleStyle.wickUpColor": string; /** * Main series hollow candle style wick down color. * * @default "#F23645" */ "mainSeriesProperties.hollowCandleStyle.wickDownColor": string; /** * Main series hollow candle style body visibility. * * @default true */ "mainSeriesProperties.hollowCandleStyle.drawBody": boolean; /** * Main series Heikin Ashi style up color. * * @default "#089981" */ "mainSeriesProperties.haStyle.upColor": string; /** * Main series Heikin Ashi style down color. * * @default "#F23645" */ "mainSeriesProperties.haStyle.downColor": string; /** * Main series Heikin Ashi style wick visibility. * * @default true */ "mainSeriesProperties.haStyle.drawWick": boolean; /** * Main series Heikin Ashi style border visibility. * * @default true */ "mainSeriesProperties.haStyle.drawBorder": boolean; /** * Main series Heikin Ashi style border color. * * @default "#378658" */ "mainSeriesProperties.haStyle.borderColor": string; /** * Main series Heikin Ashi style border up color. * * @default "#089981" */ "mainSeriesProperties.haStyle.borderUpColor": string; /** * Main series Heikin Ashi style border down color. * * @default "#F23645" */ "mainSeriesProperties.haStyle.borderDownColor": string; /** * Main series Heikin Ashi style wick color. * * @default "#737375" */ "mainSeriesProperties.haStyle.wickColor": string; /** * Main series Heikin Ashi style wick up color. * * @default "#089981" */ "mainSeriesProperties.haStyle.wickUpColor": string; /** * Main series Heikin Ashi style wick down color. * * @default "#F23645" */ "mainSeriesProperties.haStyle.wickDownColor": string; /** * Main series Heikin Ashi style color on previous close behaviour. * * @default false */ "mainSeriesProperties.haStyle.barColorsOnPrevClose": boolean; /** * Main series Heikin Ashi style body visibility. * * @default true */ "mainSeriesProperties.haStyle.drawBody": boolean; /** * Main series bar style up color. * * @default "#089981" */ "mainSeriesProperties.barStyle.upColor": string; /** * Main series bar style down color. * * @default "#F23645" */ "mainSeriesProperties.barStyle.downColor": string; /** * Main series bar style color on previous close behaviour. * * @default false */ "mainSeriesProperties.barStyle.barColorsOnPrevClose": boolean; /** * Main series bar style don't draw open behaviour. * * @default false */ "mainSeriesProperties.barStyle.dontDrawOpen": boolean; /** * Main series bar style thin bars behaviour. * * @default true */ "mainSeriesProperties.barStyle.thinBars": boolean; /** * Main series High-low style color. * * @default "#2962FF" */ "mainSeriesProperties.hiloStyle.color": string; /** * Main series High-low style border visibility. * * @default true */ "mainSeriesProperties.hiloStyle.showBorders": boolean; /** * Main series High-low style border color. * * @default "#2962FF" */ "mainSeriesProperties.hiloStyle.borderColor": string; /** * Main series High-low style label visibility. * * @default true */ "mainSeriesProperties.hiloStyle.showLabels": boolean; /** * Main series High-low style label color. * * @default "#2962FF" */ "mainSeriesProperties.hiloStyle.labelColor": string; /** * Main series column style up color. * * @default "rgba(8, 153, 129, 0.5)" */ "mainSeriesProperties.columnStyle.upColor": string; /** * Main series column style down color. * * @default "rgba(242, 54, 69, 0.5)" */ "mainSeriesProperties.columnStyle.downColor": string; /** * Main series column style color on previous close behaviour. * * @default true */ "mainSeriesProperties.columnStyle.barColorsOnPrevClose": boolean; /** * Main series column style price source. * * @default "close" */ "mainSeriesProperties.columnStyle.priceSource": PriceSource; /** * Main series line style color. * * @default "#2962FF" */ "mainSeriesProperties.lineStyle.color": string; /** * Main series line style line style. * * @default LineStyle.Solid */ "mainSeriesProperties.lineStyle.linestyle": LineStyle; /** * Main series line style line width. * * @default 2 */ "mainSeriesProperties.lineStyle.linewidth": number; /** * Main series line style price source. * * @default "close" */ "mainSeriesProperties.lineStyle.priceSource": PriceSource; /** * Main series area style color1. * * @default "rgba(41, 98, 255, 0.28)" */ "mainSeriesProperties.areaStyle.color1": string; /** * Main series area style color2. * * @default "#2962FF" */ "mainSeriesProperties.areaStyle.color2": string; /** * Main series area style line color. * * @default "#2962FF" */ "mainSeriesProperties.areaStyle.linecolor": string; /** * Main series area style line style. * * @default LineStyle.Solid */ "mainSeriesProperties.areaStyle.linestyle": LineStyle; /** * Main series area style line width. * * @default 2 */ "mainSeriesProperties.areaStyle.linewidth": number; /** * Main series area style price source. * * @default "close" */ "mainSeriesProperties.areaStyle.priceSource": PriceSource; /** * Main series area style transparency. * * @default 100 */ "mainSeriesProperties.areaStyle.transparency": number; /** * Main series price axis percentage mode. * * @default false */ "mainSeriesProperties.priceAxisProperties.percentage": boolean; /** * Main series price axis indexed to 100 mode. * * @default false */ "mainSeriesProperties.priceAxisProperties.indexedTo100": boolean; /** * Main series price axis log mode. * * @default false */ "mainSeriesProperties.priceAxisProperties.log": boolean; /** * Main series price axis inverted mode. * * @default false */ "mainSeriesProperties.priceAxisProperties.isInverted": boolean; /** * Main series price axis label alignment behaviour. * * @default true */ "mainSeriesProperties.priceAxisProperties.alignLabels": boolean; /** * Main series Renko style up color. * * @default "#089981" */ "mainSeriesProperties.renkoStyle.upColor": string; /** * Main series Renko style down color. * * @default "#F23645" */ "mainSeriesProperties.renkoStyle.downColor": string; /** * Main series Renko style border up color. * * @default "#089981" */ "mainSeriesProperties.renkoStyle.borderUpColor": string; /** * Main series Renko style border down color. * * @default "#F23645" */ "mainSeriesProperties.renkoStyle.borderDownColor": string; /** * Main series Renko style up projection color. * * @default "#a9dcc3" */ "mainSeriesProperties.renkoStyle.upColorProjection": string; /** * Main series Renko style down projection color. * * @default "#f5a6ae" */ "mainSeriesProperties.renkoStyle.downColorProjection": string; /** * Main series Renko style up projection border color. * * @default "#a9dcc3" */ "mainSeriesProperties.renkoStyle.borderUpColorProjection": string; /** * Main series Renko style down projection border color. * * @default "#f5a6ae" */ "mainSeriesProperties.renkoStyle.borderDownColorProjection": string; /** * Main series Renko style wick up color. * * @default "#089981" */ "mainSeriesProperties.renkoStyle.wickUpColor": string; /** * Main series Renko style wick down color. * * @default "#F23645" */ "mainSeriesProperties.renkoStyle.wickDownColor": string; /** * Main series Line Break style up color. * * @default "#089981" */ "mainSeriesProperties.pbStyle.upColor": string; /** * Main series Line Break style down color. * * @default "#F23645" */ "mainSeriesProperties.pbStyle.downColor": string; /** * Main series Line Break style border up color. * * @default "#089981" */ "mainSeriesProperties.pbStyle.borderUpColor": string; /** * Main series Line Break style border down color. * * @default "#F23645" */ "mainSeriesProperties.pbStyle.borderDownColor": string; /** * Main series Line Break style up projection color. * * @default "#a9dcc3" */ "mainSeriesProperties.pbStyle.upColorProjection": string; /** * Main series Line Break style down projection color. * * @default "#f5a6ae" */ "mainSeriesProperties.pbStyle.downColorProjection": string; /** * Main series Line Break style up projection color. * * @default "#a9dcc3" */ "mainSeriesProperties.pbStyle.borderUpColorProjection": string; /** * Main series Line Break style down projection color. * * @default "#f5a6ae" */ "mainSeriesProperties.pbStyle.borderDownColorProjection": string; /** * Main series Kagi style up color. * * @default "#089981" */ "mainSeriesProperties.kagiStyle.upColor": string; /** * Main series Kagi style down color. * * @default "#F23645" */ "mainSeriesProperties.kagiStyle.downColor": string; /** * Main series Kagi style up projection color. * * @default "#a9dcc3" */ "mainSeriesProperties.kagiStyle.upColorProjection": string; /** * Main series Kagi style down projection color. * * @default "#f5a6ae" */ "mainSeriesProperties.kagiStyle.downColorProjection": string; /** * Main series Point & Figure style up color. * * @default "#089981" */ "mainSeriesProperties.pnfStyle.upColor": string; /** * Main series Point & Figure style down color. * * @default "#F23645" */ "mainSeriesProperties.pnfStyle.downColor": string; /** * Main series Point & Figure style up projection color. * * @default "#a9dcc3" */ "mainSeriesProperties.pnfStyle.upColorProjection": string; /** * Main series Point & Figure style down projection color. * * @default "#f5a6ae" */ "mainSeriesProperties.pnfStyle.downColorProjection": string; /** * Main series Baseline style baseline color. * * @default "#758696" */ "mainSeriesProperties.baselineStyle.baselineColor": string; /** * Main series Baseline style top fill color1. * * @default "rgba(8, 153, 129, 0.28)" */ "mainSeriesProperties.baselineStyle.topFillColor1": string; /** * Main series Baseline style top fill color2. * * @default "rgba(8, 153, 129, 0.05)" */ "mainSeriesProperties.baselineStyle.topFillColor2": string; /** * Main series Baseline style bottom fill color1. * * @default "rgba(242, 54, 69, 0.05)" */ "mainSeriesProperties.baselineStyle.bottomFillColor1": string; /** * Main series Baseline style bottom fill color2. * * @default "rgba(242, 54, 69, 0.28)" */ "mainSeriesProperties.baselineStyle.bottomFillColor2": string; /** * Main series Baseline style top line color. * * @default "#089981" */ "mainSeriesProperties.baselineStyle.topLineColor": string; /** * Main series Baseline style bottom line color. * * @default "#F23645" */ "mainSeriesProperties.baselineStyle.bottomLineColor": string; /** * Main series Baseline style top line width. * * @default 2 */ "mainSeriesProperties.baselineStyle.topLineWidth": number; /** * Main series Baseline style bottom line width. * * @default 2 */ "mainSeriesProperties.baselineStyle.bottomLineWidth": number; /** * Main series Baseline style price source. * * @default "close" */ "mainSeriesProperties.baselineStyle.priceSource": PriceSource; /** * Main series Baseline style transparency. * * @default 50 */ "mainSeriesProperties.baselineStyle.transparency": number; /** * Main series Baseline style base level percentage. * * @default 50 */ "mainSeriesProperties.baselineStyle.baseLevelPercentage": number; /** * Main series range style up color. * * @default "#089981" */ "mainSeriesProperties.rangeStyle.upColor": string; /** * Main series range style down color. * * @default "#F23645" */ "mainSeriesProperties.rangeStyle.downColor": string; /** * Main series range style thin bars behaviour. * * @default true */ "mainSeriesProperties.rangeStyle.thinBars": boolean; /** * Main series range style up projection color. * * @default "#a9dcc3" */ "mainSeriesProperties.rangeStyle.upColorProjection": string; /** * Main series range style down projection color. * * @default "#f5a6ae" */ "mainSeriesProperties.rangeStyle.downColorProjection": string; } export interface ChartingLibraryWidgetConstructor { /** * Constructor for the Charting Library Widget * @param {ChartingLibraryWidgetOptions|TradingTerminalWidgetOptions} options - Constructor options */ new (options: ChartingLibraryWidgetOptions | TradingTerminalWidgetOptions): IChartingLibraryWidget; } export interface ChartingLibraryWidgetOptions { /** @deprecated */ container_id?: string; /** * The `container` can either be a reference to an attribute of a DOM element inside which the iframe with the chart will be placed or the `HTMLElement` itself. * * ```javascript * container: "tv_chart_container", * ``` * * or * * ```javascript * container: document.getElementById("tv_chart_container"), * ``` */ container: HTMLElement | string; /** * JavaScript object that implements the datafeed interface ({@link IBasicDataFeed}) to supply the chart with data. See [Connecting Data](https://www.tradingview.com/charting-library-docs/latest/connecting_data/) for more information on the JS API. * * ```javascript * datafeed: new Datafeeds.UDFCompatibleDatafeed("https://demo_feed.tradingview.com") * ``` */ datafeed: IBasicDataFeed | (IBasicDataFeed & IDatafeedQuotesApi); /** * The default interval for the chart. * * Example: * ```javascript * interval: '1D', * ``` */ interval: ResolutionString; /** * The default symbol for the chart. * * Example: * ```javascript * symbol: 'AAPL', * ``` */ symbol?: string; /** * A threshold delay in seconds that is used to reduce the number of `onAutoSaveNeeded` calls. * * ```javascript * auto_save_delay: 5, * ``` */ auto_save_delay?: number; /** * Boolean value showing whether the chart should use all the available space in the container and resize when the container itself is resized. * @default false * * ```javascript * autosize: true, * ``` */ autosize?: boolean; /** * Setting this property to `true` will make the chart write detailed API logs into the browser console. * Alternatively, you can use the `charting_library_debug_mode` featureset to enable it, or use the `setDebugMode` widget method ({@link IChartingLibraryWidget.setDebugMode}) . * * ```javascript * debug: true, * ``` */ debug?: boolean; /** * The array containing names of features that should be disabled by default. `Feature` means part of the functionality of the chart (part of the UI/UX). Supported features are listed [here](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets). * * Example: * ```javascript * disabled_features: ["header_widget", "left_toolbar"], * ``` */ disabled_features?: ChartingLibraryFeatureset[]; /** * You can hide some drawings from the toolbar or add custom restrictions for applying them to the chart. * * This property has the same structure as the `studies_access` argument. Use the same names as you see in the UI. * * **Remark**: There is a special case for font-based drawings. Use the "Font Icons" name for them. * Those drawings cannot be enabled or disabled separately - the entire group will have to be either enabled or disabled. * * @example * ```javascript * drawings_access: { * type: 'black', * tools: [ * { * name: 'Trend Line', * grayed: true * }, * ] * }, * ``` */ drawings_access?: AccessList; /** * The array containing names of features that should be enabled by default. `Feature` means part of the functionality of the chart (part of the UI/UX). Supported features are listed [here](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets). * * Example: * ```javascript * enabled_features: ["move_logo_to_main_pane"], * ``` */ enabled_features?: ChartingLibraryFeatureset[]; /** * Boolean value showing whether the chart should use all the available space in the window. * @default false * * ```javascript * fullscreen: true, * ``` */ fullscreen?: boolean; /** * A path to a `static` folder. * * ```javascript * library_path: "charting_library/", * ``` * * * If you would like to host the library on a separate origin to the page containing the chart then please view the following guide: [Hosting the library on a separate origin](https://www.tradingview.com/charting-library-docs/latest/getting_started/Hosting-Library-Cross-Origin). */ library_path?: string; /** * Locale to be used by Charting Library. See [Localization](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Localization) section for details. * * ```javascript * locale: 'en', * ``` */ locale: LanguageCode; /** * The object containing formatting options for numbers. The only possible option is `decimal_sign` currently. * * ```javascript * numeric_formatting: { decimal_sign: "," }, * ``` */ numeric_formatting?: NumericFormattingParams; /** * JS object containing saved chart content. * Use this parameter when creating the widget if you have a saved chart already. * If you want to load the chart content when the chart is initialized then use `load()` method ({@link IChartingLibraryWidget.load}) of the widget. */ saved_data?: object; /** * JS object containing saved chart content meta info. */ saved_data_meta_info?: SavedStateMetaInfo; /** * You can hide some studies from the toolbar or add custom restrictions for applying them to the chart. * * @example * ```javascript * studies_access: { * type: "black" | "white", * tools: [ * { * name: "", * grayed: true * }, * < ... > * ] * } * ``` */ studies_access?: AccessList; /** * Maximum amount of studies on the chart of a multichart layout. Minimum value is 2. * * ```javascript * study_count_limit: 5, * ``` */ study_count_limit?: number; /** * A threshold delay in milliseconds that is used to reduce the number of symbol search requests when the user is typing a name of a symbol in the search box. * * ```javascript * symbol_search_request_delay: 1000, * ``` */ symbol_search_request_delay?: number; /** * Sets the default timeframe of the chart. * * The timeframe can be relative to the current date, or a range. * * A relative timeframe is a number with a letter D for days and M for months: * * ```javascript * timeframe: '3M', * ``` * * A range is an object with to and from properties. The to and from properties should be UNIX timestamps: * * ```javascript * timeframe: { from: 1640995200, to: 1643673600 } // from 2022-01-01 to 2022-02-01 * ``` * * **Note**: * When using a range the chart will still request data up to the current date. This is to enable scrolling forward in time once the chart has loaded. */ timeframe?: TimeframeOption; /** * Default timezone of the chart. The time on the timescale is displayed according to this timezone. * See the [list of supported timezones](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#timezone) for available values. Set it to `exchange` to use the exchange timezone. Use the {@link ChartingLibraryWidgetOptions.overrides} section if you wish to override the default value. * * ```javascript * timezone: "America/New_York", * ``` */ timezone?: "exchange" | Timezone; /** * Background color of the toolbars. * * ```javascript * toolbar_bg: '#f4f7f9', * ``` */ toolbar_bg?: string; /** * The desired width of a widget. Please make sure that there is enough space for the widget to be displayed correctly. * * ```javascript * width: 300, * ``` * * **Remark**: If you want the chart to use all the available space use the `fullscreen` parameter instead of setting it to '100%'. */ width?: number; /** * The desired height of a widget. Please make sure that there is enough space for the widget to be displayed correctly. * * ```javascript * height: 600, * ``` * * **Remark**: If you want the chart to use all the available space use the `fullscreen` parameter instead of setting it to '100%'. */ height?: number; /** * Set the storage url endpoint for use with the high-level saving / loading charts API. * See more details [here](https://www.tradingview.com/charting-library-docs/latest/saving_loading/). * * ```javascript * charts_storage_url: 'http://storage.yourserver.com', * ``` */ charts_storage_url?: string; /** * A version of your backend. Supported values are: `"1.0"` | `"1.1"`. Study Templates are supported starting from version `"1.1"`. * * ```javascript * charts_storage_api_version: "1.1", * ``` */ charts_storage_api_version?: AvailableSaveloadVersions; /** * Set the client ID for the high-level saving / loading charts API. * See more details [here](https://www.tradingview.com/charting-library-docs/latest/saving_loading/). * * ```javascript * client_id: 'yourserver.com', * ``` */ client_id?: string; /** * Set the user ID for the high-level saving / loading charts API. * See more details [here](https://www.tradingview.com/charting-library-docs/latest/saving_loading/). * * ```javascript * user_id: 'public_user_id', * ``` */ user_id?: string; /** * Set this parameter to `true` if you want the library to load the last saved chart for a user (you should implement [save/load](https://www.tradingview.com/charting-library-docs/latest/saving_loading/) first to make it work). * * ```javascript * load_last_chart: true, * ``` */ load_last_chart?: boolean; /** * Use this option to customize the style or inputs of the indicators. * You can also customize the styles and inputs of the `Compare` series using this argument. * See more details [here](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Studies-Overrides) * * ```javascript * studies_overrides: { * "volume.volume.color.0": "#00FFFF", * }, * ``` */ studies_overrides?: StudyOverrides; /** Alias for {@link ChartingLibraryWidgetOptions.custom_formatters} */ customFormatters?: CustomFormatters; /** * Custom formatters for adjusting the display format of price, date, and time values. * * Example: * * ```javascript * custom_formatters: { * timeFormatter: { * format: (date) => { * const _format_str = '%h:%m'; * return _format_str * .replace('%h', date.getUTCHours(), 2) * .replace('%m', date.getUTCMinutes(), 2) * .replace('%s', date.getUTCSeconds(), 2); * } * }, * dateFormatter: { * format: (date) => { * return date.getUTCFullYear() + '/' + (date.getUTCMonth() + 1) + '/' + date.getUTCDate(); * } * }, * tickMarkFormatter: (date, tickMarkType) => { * switch (tickMarkType) { * case 'Year': * return 'Y' + date.getUTCFullYear(); * * case 'Month': * return 'M' + (date.getUTCMonth() + 1); * * case 'DayOfMonth': * return 'D' + date.getUTCDate(); * * case 'Time': * return 'T' + date.getUTCHours() + ':' + date.getUTCMinutes(); * * case 'TimeWithSeconds': * return 'S' + date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds(); * } * * throw new Error('unhandled tick mark type ' + tickMarkType); * }, * priceFormatterFactory: (symbolInfo, minTick) => { * if (symbolInfo?.fractional || minTick !== 'default' && minTick.split(',')[2] === 'true') { * return { * format: (price, signPositive) => { * // return the appropriate format * }, * }; * } * return null; // this is to use default formatter; * }, * studyFormatterFactory: (format, symbolInfo) => { * if (format.type === 'price') { * const numberFormat = new Intl.NumberFormat('en-US', { notation: 'scientific' }); * return { * format: (value) => numberFormat.format(value) * }; * } * * if (format.type === 'volume') { * return { * format: (value) => (value / 1e9).toPrecision(format?.precision || 2) + 'B' * }; * } * * if (format.type === 'percent') { * return { * format: (value) => `${value.toPrecision(format?.precision || 4)} percent` * }; * } * * return null; // this is to use default formatter; * }, * } * ``` * * **Remark**: `tickMarkFormatter` must display the UTC date, and not the date corresponding to your local timezone. */ custom_formatters?: CustomFormatters; /** * Override values for the default widget properties * You can override most of the Charting Library properties (which also may be edited by user through UI) * using `overrides` parameter of Widget constructor. `overrides` is supposed to be an object. * The keys of this object are the names of overridden properties. * The values of these keys are the new values of the properties. * * Example: * ```javascript * overrides: { * "mainSeriesProperties.style": 2 * } * ``` * This code will change the default series style to "line". * All customizable properties are listed in [separate article](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/). * You can use [Drawings-Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Drawings-Overrides). */ overrides?: Overrides; /** * This URL is used to send a POST request with binary chart snapshots when a user presses the snapshot button. * This POST request contains `multipart/form-data` with the field `preparedImage` that represents binary data of the snapshot image in `image/png` format. * * This endpoint should return the full URL of the saved image in the the response. * * ```javascript * snapshot_url: "https://myserver.com/snapshot", * ``` */ snapshot_url?: string; /** * List of visible timeframes that can be selected at the bottom of the chart. See [this topic](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Time-Frames) to learn more about timeframes. Timeframe is an object containing following properties: * * Example: * * ```javascript * time_frames: [ * { text: "50y", resolution: "6M", description: "50 Years" }, * { text: "3y", resolution: "1W", description: "3 Years", title: "3yr" }, * { text: "8m", resolution: "1D", description: "8 Month" }, * { text: "3d", resolution: "5", description: "3 Days" }, * { text: "1000y", resolution: "1W", description: "All", title: "All" }, * ] * ``` */ time_frames?: TimeFrameItem[]; /** * Adds your custom CSS to the chart. `url` should be an absolute or relative path to the `static` folder. * * ```javascript * custom_css_url: 'css/style.css', * ``` */ custom_css_url?: string; /** * Change the font family used on the chart. The value should be in the same format as the `font-family` property in CSS. * If you want to use a font that is not available by default on your system, you need to first load the font in your [custom CSS](#custom_css_url). * * E.g. importing a google font in your custom CSS: * * ```css * @import url('https://fonts.googleapis.com/css2?family=Inconsolata:wght@500&display=swap'); * ``` * * Add `custom_font_family` to your widget options: * * ```javascript * custom_font_family: "'Inconsolata', monospace", * ``` */ custom_font_family?: string; /** * Items that should be marked as favorite by default. This option requires that the usage of localstorage is disabled (see [featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) to know more). The `favorites` property is supposed to be an object. The following properties are supported: * * ```javascript * favorites: { * intervals: ["1D", "3D", "3W", "W", "M"], * chartTypes: ["Area", "Line"], * drawingTools: ['LineToolBrush', 'LineToolCallout', 'LineToolCircle'] * }, * ``` */ favorites?: Favorites; /** * An object containing the save/load functions. * It is used to implement a custom save/load algorithm. * Please see details and an example on [Saving and Loading Charts page](https://www.tradingview.com/charting-library-docs/latest/saving_loading/#api-handlers). */ save_load_adapter?: IExternalSaveLoadAdapter; /** * Customization of the loading spinner. Value is an object with the following possible keys: * * * `backgroundColor` * * `foregroundColor` * * Example: * * ```javascript * loading_screen: { backgroundColor: "#000000" } * ``` */ loading_screen?: LoadingScreenOptions; /** * An object that contains set/remove functions. Use it to save chart settings to your preferred storage (including server-side). * * Example: * ```javascript * settings_adapter: { * initialSettings: { ... }, * setValue: function(key, value) { ... }, * removeValue: function(key) { ... }, * } * ``` */ settings_adapter?: ISettingsAdapter; /** * Set predefined custom theme color for the chart. Supported values are: `"Light"` | `"Dark"`. * * ```javascript * theme: "Light", * ``` */ theme?: ThemeName; /** * an array of custom compare symbols for the Compare window. * * Example: * ```javascript * compare_symbols: [ * { symbol: 'DAL', title: 'Delta Air Lines' }, * { symbol: 'VZ', title: 'Verizon' }, * ... * ]; * ``` */ compare_symbols?: CompareSymbol[]; /** * Function that returns a Promise object with an array of your custom indicators. * * `PineJS` variable will be passed as the first argument of this function and can be used inside your indicators to access internal helper functions. * * See more details [here](https://www.tradingview.com/charting-library-docs/latest/custom_studies/). * * ```javascript * custom_indicators_getter: function(PineJS) { * return Promise.resolve([ * // *** your indicator object, created from the template *** * ]); * }, * ``` */ custom_indicators_getter?: (PineJS: PineJS) => Promise; /** * An optional field containing an array of custom symbol info fields to be shown in the Symbol Info dialog. * * See [Symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology) for more information about symbol info. * * ```javascript * additional_symbol_info_fields: [ * { title: 'Ticker', propertyName: 'ticker' } * ] * ``` */ additional_symbol_info_fields?: AdditionalSymbolInfoField[]; /** * An additional optional field to change the look and feel of buttons on the top toolbar. * * By default (if option is omitted) header will be in adaptive mode (fullsize if the window width allows and icons on smaller windows). * * Example: * ```javascript * header_widget_buttons_mode: 'fullsize', * ``` */ header_widget_buttons_mode?: HeaderWidgetButtonsMode; /** * You could use this object to override context menu in some way. */ context_menu?: ContextMenuOptions; /** * An additional optional field to add more bars on screen. * * Example: * ```javascript * time_scale: { * min_bar_spacing: 10, * } * ``` */ time_scale?: TimeScaleOptions; /** * Use this property to set your own translation function. `key` and `options` will be passed to the function. * * You can use this function to provide custom translations for some strings. * * The function should return either a string with a new translation or `null` to fallback to the default translation. * * For example, if you want to rename "Trend Line" shape to "Line Shape", then you can do something like this: * * ```javascript * custom_translate_function: (key, options) => { * if (key === 'Trend Line') { * // patch the title of trend line * return 'Line Shape'; * } * * return null; * } * ``` */ custom_translate_function?: CustomTranslateFunction; /** * Use this property to set a function to override the symbol input from symbol search dialogs. * * For example for you may want to get additional input from the user before deciding which symbol should be resolved. * * The function should take two parameters: a `string` of input from the symbol search and a optional search result item. It should return a `Promise` that resolves with a symbol ticker and a human friendly symbol name. * * **NOTE:** This override is not called when adding a symbol to the watchlist. * * ```typescript * { * // `SearchSymbolResultItem` is the same interface as for items returned to the Datafeed's searchSymbols result callback. * symbol_search_complete: (symbol: string, searchResultItem?: SearchSymbolResultItem) => { * return new Promise((resolve) => { * let symbol = getNewSymbol(symbol, searchResultItem); * let name = getHumanFriendlyName(symbol, searchResultItem) * resolve({ symbol: symbol, name: name }); * }); * } * } * ``` */ symbol_search_complete?: SymbolSearchCompleteOverrideFunction; /** * The object that contains new values for values saved to the settings. * These overrides will replace any matching values from the settings, regardless of where the settings are loaded from (i.e. local storage or a custom settings adapter). * The object is similar to the [overrides](#overrides) object. * * [overrides](#overrides) will not affect values that have been saved to settings so this option can be used instead. * * ```javascript * settings_overrides: { * "linetooltrendline.linecolor": "blue" * } * ``` */ settings_overrides?: Overrides; /** * List of custom timezones. * * Please see the [timezones](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezones) documentation for more details. */ custom_timezones?: CustomAliasedTimezone[]; } export interface CheckboxFieldMetaInfo extends CustomFieldMetaInfoBase { /** @inheritDoc */ inputType: "Checkbox"; /** @inheritDoc */ value: boolean; /** Does the field support modification */ supportModify?: boolean; /** Help message for the field */ help?: string; } export interface ClientSnapshotOptions { /** Background color */ backgroundColor: string; /** Border color */ borderColor: string; /** Font */ font: string; /** Size of font */ fontSize: number; /** Legend Mode. */ legendMode: LegendMode; /** Hide resolution */ hideResolution: boolean; } export interface ColumnStylePreferences { /** Up column color */ upColor: string; /** Down column color */ downColor: string; /** Color column based on previous close */ barColorsOnPrevClose: boolean; } /** * Defines a custom compare symbol for the Compare dialog window */ export interface CompareSymbol { /** symbol identifier */ symbol: string; /** the name of instrument that will be displayed near the corresponding checkbox */ title: string; } export interface ContextMenuItem { /** Position of the context menu item */ position: "top" | "bottom"; /** Text content for the context menu item */ text: string; /** Callback event when menu item is clicked */ click: EmptyCallback; } export interface ContextMenuOptions { /** * Provide this function if you want to change the set of actions being displayed in the context menu. * * You can filter out, add yours and re-order items. * * The library will call your function each time it wants to display a context menu and with provide a list of items to display. * This function should return an array of items to display. */ items_processor?: ContextMenuItemsProcessor; /** * **Note:** This API is experimental and might be changed significantly in the future releases. * By providing this function you could override the default renderer for context menu. */ renderer_factory?: ContextMenuRendererFactory; } export interface ContextMenuPosition { /** X (horizontal) coordinate (in pixels) at which the mouse event occurred, relative to the left edge of the applications viewport. */ clientX: number; /** Y (vertical) coordinate (in pixels) at which the mouse event occurred, relative to the left edge of the applications viewport. */ clientY: number; /** Touch positions */ touches?: readonly { /** X (horizontal) coordinate (in pixels) at which the touch event occurred, relative to the left edge of the applications viewport. */ clientX: number; /** Y (vertical) coordinate (in pixels) at which the touch event occurred, relative to the left edge of the applications viewport. */ clientY: number; }[]; /** * Tells what side of the context menu widget should be used to "attach" to a provided x coordinate. * If the value is `undefined`, then you may treat it based on whether it is rtl or not (e.g. `'right'` for rtl and `'left'` otherwise). */ attachToXBy?: "left" | "right"; /** * Tells what side of the context menu widget should be used to "attach" to a provided y coordinate: * - `'auto'` means similar to `'top'` but the menu could be expanded above the coordinate if needed (if there is no enough space to place it below) * - `'auto-strict'` means `'top'` if the whole menu fits the space below the coordinate and `'bottom'` otherwise (see {@link boxHeight}) * - `'top'` means that the menu should be placed to the bottom of y coordinate (the menu should be attached by its bottom to y coordinate) * - `'bottom'` means that the menu should be placed above y coordinate (the menu should be attached by its top to y coordinate) * * You may treat `undefined` as `'auto'`. */ attachToYBy?: "auto" | "auto-strict" | "top" | "bottom"; /** * The height of a box the context menu should avoid while calculating coordinates (see {@link attachToYBy}). * * You may treat `undefined` as `0`. */ boxHeight?: number; } /** * Options for creating an anchored drawing. */ export interface CreateAnchoredShapeOptions extends CreateShapeOptionsBase { /** * A drawing to create; */ shape: "anchored_text" | "anchored_note"; } export interface CreateContextMenuParams { /** name of the menu */ menuName: string; /** * Additional details for the context menu. * `type` field can be one of the following: `series`, `study`, `shape`, or `groupOfShapes` */ detail?: { /** series type */ type: "series"; /** id */ id: string; } | { /** study type */ type: "study"; /** id */ id: string | null; } | { /** shape type */ type: "shape"; /** id */ id: number | string | null; } | { /** groupOfShapes type */ type: "groupOfShapes"; /** id */ id: string | null; }; } export interface CreateHTMLButtonOptions { /** * Alignment for the button. * @default 'left' */ align: "left" | "right"; /** * A placeholder HTMLElement will be created. */ useTradingViewStyle: false; } /** * Options for creating a multipoint drawing. */ export interface CreateMultipointShapeOptions extends CreateShapeOptionsBase { /** * A drawing to create. */ shape?: Exclude; } /** * Options for creating a drawing. */ export interface CreateShapeOptions extends CreateShapeOptionsBase { /** * A drawing to create. */ shape?: "arrow_up" | "arrow_down" | "flag" | "vertical_line" | "horizontal_line" | "long_position" | "short_position" | "icon" | "anchored_text" | "anchored_note"; /** * An optional study ID of the owner study. */ ownerStudyId?: EntityId; } /** * Options for creating a drawing. */ export interface CreateShapeOptionsBase { /** Text for drawing */ text?: string; /** Should drawing be locked */ lock?: boolean; /** * Disable/enable selecting the drawing. */ disableSelection?: boolean; /** * Disable/enable saving the drawing. */ disableSave?: boolean; /** * Disable/enable undoing the creation of the drawing. */ disableUndo?: boolean; /** * Drawing properties overrides. */ overrides?: TOverrides; /** * Create the drawing in front of all other drawings, or behind all other drawings. */ zOrder?: "top" | "bottom"; /** * Enable/disable showing the drawing in the objects tree. */ showInObjectsTree?: boolean; /** * An entity ID that can be used to associate the drawing with a study. */ ownerStudyId?: EntityId; /** * Enable/disable filling the drawing with color (if the drawing supports filling). */ filled?: boolean; /** * Specify an icon to render - Only icons listed [here](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Shapes-and-Overrides) are supported */ icon?: number; } /** * Options for creating a study. */ export interface CreateStudyOptions { /** if it is `true` then the study limit dialog will be shown if the limit is exceeded. */ checkLimit?: boolean; /** * Price scale */ priceScale?: StudyPriceScale; /** Allow the currency to be changed */ allowChangeCurrency?: boolean; /** Allow the unit to be changed */ allowChangeUnit?: boolean; /** prevents adding of the action to the undo stack */ disableUndo?: boolean; } /** * Options for creating a study template. */ export interface CreateStudyTemplateOptions { /** * An optional boolean flag to include the symbol in the saved state. */ saveSymbol?: boolean; /** * An optional boolean flag to include the interval in the saved state. */ saveInterval?: boolean; } export interface CreateTradingViewStyledButtonOptions { /** * Alignment for the button. * @default 'left' */ align: "left" | "right"; /** * A button with the built-in styles will be created in the header. */ useTradingViewStyle: true; /** * The text shown on the button. */ text: string; /** * The text shown on hovering the button. */ title?: string; /** * A function called when the button is clicked. */ onClick?: () => void; } /** * Crosshair move event information. */ export interface CrossHairMovedEventParams { /** * The time coordinate of the crosshair. */ time: number; /** * The price coordinate of the crosshair. */ price: number; } export interface CryptoBalance { /** Symbol */ symbol: string; /** Total balance */ total: number; /** Available balance */ available: number; /** Reserved balance */ reserved?: number; /** Balance value */ value?: number; /** Balance value's currency */ valueCurrency?: string; /** Long name of Crypto */ longName?: string; /** Bitcoin value of balance */ btcValue?: number; } export interface CurrencyItem { /** Unique ID */ id: string; /** Currency code. @example `USD` */ code: string; /** URL to an image of the currency. SVG logos are preferable, but please make sure that the provided image fits nicely in the currency select control (for raster images the expected size is 24x24px). */ logoUrl?: string; /** Description for the currency */ description?: string; } export interface CustomAliasedTimezone extends CustomTimezoneInfo { /** * Id for the custom timezone. */ id: CustomTimezoneId; } export interface CustomComboBoxItem { /** Combo box item text */ text: string; /** Combo box item value */ value: string; } export interface CustomComboBoxMetaInfo extends CustomInputFieldMetaInfo { /** @inheritDoc */ inputType: "ComboBox"; /** Items for the combo box input field */ items: CustomComboBoxItem[]; } export interface CustomFieldMetaInfoBase { /** Type of the input field */ inputType: string; /** Input field ID */ id: string; /** Title for the input field */ title: string; /** Value of the field */ value?: any; /** Should the input field value be saved to settings */ saveToSettings?: boolean; } /** * Custom fields to be added to an object. */ export interface CustomFields { /** Custom field */ [key: string]: any; } /** */ export interface CustomFormatter { /** Formats date and time */ format(date: Date): string; /** Converts date and time to local timezone. */ formatLocal(date: Date): string; } /** * Formatters used to adjust the displayed format of the date and time values. */ export interface CustomFormatters { /** Used to format the time displayed in the bottom toolbar (timezone) */ timeFormatter: CustomFormatter; /** Used to format the date displayed over the timescale when hover over a chart */ dateFormatter: CustomFormatter; /** * Used to format date displayed in the time axis * **Remark**: `tickMarkFormatter` must display the UTC date, and not the date corresponding to your local timezone. */ tickMarkFormatter?: (date: Date, tickMarkType: TickMarkType) => string; /** Used to format the number displayed in the price axis */ priceFormatterFactory?: SeriesFormatterFactory; /** * Used to format the numbers displayed within a custom study. */ studyFormatterFactory?: CustomStudyFormatterFactory; } export interface CustomIndicator { /** Your study name, it will be used internally by the Charting Library */ readonly name: string; /** * The metainfo field is designed to contain the main info about the custom study. * * See [Custom Studies Metainfo](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/) for more information */ readonly metainfo: StudyMetaInfo; /** * The Custom Study Constructor is a Function Constructor in terms of ES5. * The library creates an instance of a custom study by applying operator new to the constructor. * The library expects the constructor to create an instance of the study with one mandatory method - `main()` and one optional method - `init()`. * Once the study is created the library calls init (if exists) and main sequentially with empty context to collect information about all vars. * * See [Custom Studies Constructor](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Constructor) for more information. */ readonly constructor: LibraryPineStudyConstructor | ((this: LibraryPineStudy) => void); } export interface CustomInputFieldMetaInfo extends CustomFieldMetaInfoBase { /** Prevent modification */ preventModify?: boolean; /** Placeholder string for the field */ placeHolder?: string; /** Validator function for the field */ validator?: InputFieldValidator; /** Additional custom information */ customInfo?: any; } /** * An object that contains the results of broker specific user inputs (for example a digital signature). */ export interface CustomInputFieldsValues { [fieldId: string]: TextWithCheckboxValue | boolean | string | any; } /** * Study format description used in custom study formatters. */ export interface CustomStudyFormatterFormat { /** * The format of the plot. */ type: "price" | "volume" | "percent"; /** * The format precision. */ precision?: number; } export interface CustomTableElementFormatter { /** Custom formatter name */ name: FormatterName; /** Formatter to generate HTML element */ formatElement?: CustomTableFormatElementFunction; /** Formatter to generate text. Return an empty string if you don't need to display this */ formatText: TableFormatTextFunction; } export interface CustomTimezoneInfo { /** * Timezone identifier ({@link TimezoneId}) to which this custom * timezone should be mapped to. This must be a timezone supported * by library. * * Additionally, you can specify a `Etc/GMT` timezone id. * In order to conform with the POSIX style, those zone names * beginning with "Etc/GMT" have their sign reversed from the * standard ISO 8601 convention. In the "Etc" area, zones west * of GMT have a positive sign and those east have a negative * sign in their name (e.g "Etc/GMT-14" is 14 hours ahead of GMT). */ alias: TimezoneId | GmtTimezoneId; /** * Display name for the timezone */ title: string; } /** * Depth of Market (Order Book) Data */ export interface DOMData { /** * Whether the Depth of Market data is a snapshot (has the full set of depth data). * - If `true` then the data contains the full set of depth data. * - If `false` then data only contains updated levels. */ snapshot: boolean; /** Ask order levels (must be sorted by `price` in ascending order) */ asks: DOMLevel[]; /** Bid order levels (must be sorted by `price` in ascending order) */ bids: DOMLevel[]; } /** * Depth of Market Level */ export interface DOMLevel { /** Price for DOM level */ price: number; /** Volume for DOM level */ volume: number; } export interface DatafeedConfiguration { /** * List of exchange descriptors. * An empty array leads to an absence of the exchanges filter in the Symbol Search list. * Use `value=''` if you wish to include all exchanges. */ exchanges?: Exchange[]; /** * List of supported resolutions. Resolution string format is described here: {@link ResolutionString} * Setting this property to `undefined` or an empty array will result in the resolution widget * displaying the content. * * @example * `["1", "15", "240", "D", "6M"]` will give you "1 minute, 15 minutes, 4 hours, 1 day, 6 months" in resolution widget. */ supported_resolutions?: ResolutionString[]; /** * Supported unit groups. Each group can have several unit objects. * * @example * ```javascript * { * weight: [ * { id: 'kg', name: 'kg', description: 'Kilograms' }, * { id: 'lb', name: 'lb', description: 'Pounds'}, * ] * } * ``` */ units?: Record; /** * Supported currencies for currency conversion. * * When a currency code is supplied as a string then the library will automatically convert it to `{ id: value, code: value }` object. * * @example `["USD", "EUR", "GBP"]` * @example `[{ id: "USD", code: "USD", description: "$" }, { id: "EUR", code: "EUR", description: "€" }]` */ currency_codes?: (string | CurrencyItem)[]; /** Does the datafeed supports marks on bars (`true`), or not (`false | undefined`). */ supports_marks?: boolean; /** Set this one to `true` if your datafeed provides server time (unix time). It is used to adjust Countdown on the Price scale. */ supports_time?: boolean; /** Does the datafeed supports marks on the timescale (`true`), or not (`false | undefined`). */ supports_timescale_marks?: boolean; /** * List of filter descriptors. * * Setting this property to `undefined` or an empty array leads to the absence of filter types in Symbol Search list. Use `value = ''` if you wish to include all filter types. * `value` within the descriptor will be passed as `symbolType` argument to {@link IDatafeedChartApi.searchSymbols} */ symbols_types?: DatafeedSymbolType[]; /** * Set it if you want to group symbols in the symbol search. * Represents an object where keys are symbol types {@link SymbolType} and values are regular expressions (each regular expression should divide an instrument name into 2 parts: a root and an expiration). * * Sample: * ``` * { * "futures": `/^(.+)([12]!|[FGHJKMNQUVXZ]\d{1,2})$/`, * "stock": `/^(.+)([12]!|[FGHJKMNQUVXZ]\d{1,2})$/`, * } * ``` * It will be applied to the instruments with futures and stock as a type. */ symbols_grouping?: Record; /** * Supported price sources for the symbol. * * @example ['Bid', 'Ask', 'Spot Price'] */ price_sources?: SymbolInfoPriceSource[]; } /** Symbol Quote Data Value */ export interface DatafeedQuoteValues { /** Price change (usually counts as an open price on a particular day) */ ch?: number; /** Price change percentage */ chp?: number; /** Short name for the symbol */ short_name?: string; /** The name of the exchange */ exchange?: string; /** A short description of the symbol */ description?: string; /** Last traded price */ lp?: number; /** Ask price */ ask?: number; /** Bid price */ bid?: number; /** Spread (difference between the ask and bid prices) */ spread?: number; /** Today's opening price */ open_price?: number; /** Today's high price */ high_price?: number; /** Today's low price */ low_price?: number; /** Yesterday's closing price */ prev_close_price?: number; /** Today's trading volume */ volume?: number; /** Original name */ original_name?: string; [valueName: string]: string | number | undefined; } export interface DatafeedSymbolType { /** Name of the symbol type */ name: string; /** Value to be passed as the `symbolType` argument to `searchSymbols` */ value: string; } export interface DefaultContextMenuActionsParams { } export interface DefaultDropdownActionsParams { /** Show trading properties */ tradingProperties?: boolean; /** Restore confirmations */ restoreConfirmations?: boolean; } export interface DialogParams { /** Dialog title */ title: string; /** Dialog content */ body: string; /** Callback */ callback: CallbackType; } /** Item within a dropdown menu */ export interface DropdownItem { /** Title of the menu item */ title: string; /** Callback for when the item is selected by the user */ onSelect: () => void; } /** Parameters for configuring a dropdown menu */ export interface DropdownParams { /** Title for the dropdown menu */ title: string; /** Menu items */ items: DropdownItem[]; /** Dropdown menu tooltip */ tooltip?: string; /** Icons for the dropdown menu. (SVG mark-up) */ icon?: string; /** Alignment of the dropdown menu */ align?: "right" | "left"; } export interface EditObjectDialogEventParams { /** Dialog type */ objectType: EditObjectDialogObjectType; /** Title of the object described within the dialog */ scriptTitle: string; } export interface EntityInfo { /** Entity id (string) */ id: EntityId; /** Name of entity */ name: string; } export interface ErrorFormatterParseResult extends FormatterParseResult { /** Optional message when there's an error while parsing */ error?: string; /** @inheritDoc */ res: false; } /** Exchange Description */ export interface Exchange { /** Value to be passed as the `exchange` argument to `searchSymbols` */ value: string; /** Name of the exchange */ name: string; /** Description of the exchange */ desc: string; } /** * Describes a single execution. Execution is a mark on a chart that displays trade information. */ export interface Execution extends CustomFields { /** Symbol name */ symbol: string; /** Execution price */ price: number; /** Execution Quantity */ qty: number; /** Execution Side */ side: Side; /** Time (unix timestamp in milliseconds) */ time: number; /** Commission amount for executed trade */ commission?: number; /** Net amount for executed trade */ netAmount?: number; } export interface ExportDataOptions { /** * Optional timestamp of the first exported bar. */ from?: number; /** * Optional timestamp of the last exported bar. */ to?: number; /** * If true then each exported data item will include a time value. * * @default true */ includeTime?: boolean; /** * If true then each exported data item will include a user time value. * * @default false */ includeUserTime?: boolean; /** * If true then the exported data will include open, high, low, close values from the main series. * * @default true */ includeSeries?: boolean; /** * If true then the exported data will include formatted value as displayed to the user. * * @default false */ includeDisplayedValues?: boolean; /** * If true then each exported data item will include a value for the specified studies. */ includedStudies: readonly string[] | "all"; /** * Include study data that has a positive offset from the main series data. That is study data that is "to the right of" the last main series data point. */ includeOffsetStudyValues?: boolean; } /** * Export data from the chart */ export interface ExportedData { /** An array of {@link FieldDescriptor} */ schema: FieldDescriptor[]; /** Array of the same length as `schema` that represents the associated field's item */ data: Float64Array[]; /** Array of strings that represents the display value of the associated field element */ displayedData: string[][]; } export interface Favorites { /** * An array of time intervals that are marked as favorite. * * Example: `["D", "2D"]` */ intervals?: ResolutionString[]; /** * An array of chart types that are marked as favorite. * The names of chart types are identical to chart's UI in the English version. * * Example: `["Area", "Candles"]`. */ chartTypes?: string[]; /** * An array of drawing tool identifiers that should be marked as favorite. These will only * be applied if there aren't existing favorites. * * Example: ['LineToolBrush', 'LineToolCallout', 'LineToolCircle'] */ drawingTools?: DrawingToolIdentifier[]; } export interface FormatterParseResult { /** Returns if the formatter support parsing */ res: boolean; } export interface GetNewsResponse { /** Title */ title?: string; /** Retrieved news items */ newsItems: NewsItem[]; } export interface GrayedObject { /** Type for grayed object */ type: "drawing" | "study"; /** Name of grayed object */ name: string; } /** Histogram Preferences */ export interface HHistPreferences { /** * Colors for the histogram up and down bars. * Example: * ```js * colors: ['#1592e6', '#fbc123'] * ``` */ colors: string[]; /** Transparency values for the histogram */ transparencies: number[]; /** Should the histogram be visible */ visible: boolean; /** Percentage width of the chart for which the histogram should occupy */ percentWidth: number; /** Should the values be shown */ showValues: boolean; /** Color for values shown */ valuesColor: string; /** * Direction of the histogram. * Whether the histogram will be shown on the left or right edge of the chart */ direction: HHistDirection; } export interface HeikinAshiStylePreferences { /** Body color for an up candle */ upColor: string; /** Body color for down candle */ downColor: string; /** Whether to draw the candle wick */ drawWick: boolean; /** Whether to draw the candle border */ drawBorder: boolean; /** Whether to draw the candle body */ drawBody: boolean; /** Candle border color */ borderColor: string; /** Up candle border color */ borderUpColor: string; /** Down candle border color */ borderDownColor: string; /** Candle wick color */ wickColor: string; /** Up candle wick color */ wickUpColor: string; /** Down candle wick color */ wickDownColor: string; /** Show real last price */ showRealLastPrice: boolean; /** Color bars based on previous close value */ barColorsOnPrevClose: boolean; } export interface HiLoStylePreferences { /** Color for Hi Lo chart */ color: string; /** Show borders. Default - `false` */ showBorders: boolean; /** Border Color */ borderColor: string; /** Show Labels. Default - `false` */ showLabels: boolean; /** Label color */ labelColor: string; /** Draw body. Default - `true` */ drawBody: boolean; } /** * Information passed to `onHistoryCallback` for getBars. */ export interface HistoryMetadata { /** * Optional value indicating to the library that there is no more data on the server. */ noData?: boolean; /** * Time of the next bar if there is no data in the requested period. * It should be set if the requested period represents a gap in the data. Hence there is available data prior to the requested period. */ nextTime?: number | null; } export interface HollowCandleStylePreferences { /** Body color for an up candle */ upColor: string; /** Body color for a down candle */ downColor: string; /** Whether to draw the candle wick */ drawWick: boolean; /** Whether to draw the candle body border */ drawBorder: boolean; /** Whether to draw the candle body */ drawBody: boolean; /** Candle border color */ borderColor: string; /** Up candle border color */ borderUpColor: string; /** Down candle border color */ borderDownColor: string; /** Candle wick color */ wickColor: string; /** Up candle wick color */ wickUpColor: string; /** Down candle wick color */ wickDownColor: string; } export interface HorizLinePreferences { /** Is visible if set to `true` */ visible: boolean; /** Width of the horizontal line */ width: number; /** Color of the horizontal line */ color: string; /** Line style */ style: LineStyle; /** Show price if set to `true` */ showPrice?: boolean; } /** * Horizontal Line Preferences */ export interface HorizLinePreferences { visible: boolean; width: number; color: string; style: LineStyle; showPrice?: boolean; } export interface IAction extends IMenuItem { /** @inheritDoc */ readonly type: MenuItemType.Action; /** * A method which will be called when an action should be executed (e.g. when a user clicks on the item) */ execute(): void; /** * @returns Returns a state object of the action. */ getState(): Readonly; /** * @returns A subscription for an event when an action is updated. */ onUpdate(): ISubscription; } export interface IBoxedValue extends IBoxedValueReadOnly { /** * Set boxed value * @param {T} value - value to be set */ setValue(value: T): void; } export interface IBoxedValueReadOnly { /** Value */ value(): T; } export interface IBrokerCommon { /** * Chart can have a sub-menu `Trading` in the context menu. This method should return an array of {@link ActionMetaInfo} elements, each of them representing one context menu item. * @param {TradeContext} context - context object passed by a browser * @param {DefaultContextMenuActionsParams} options? - default options for the context menu action parameters */ chartContextMenuActions(context: TradeContext, options?: DefaultContextMenuActionsParams): Promise; /** * This function is required for the Floating Trading Panel. * The ability to trade via the panel depends on the result of this function: `true` or `false`. * You don't need to implement this method if all symbols can be traded. * * If you want to show a custom message with the reason why the symbol cannot be traded then you can return an object `IsTradableResult`. * @param {string} symbol - symbol identifier */ isTradable(symbol: string): Promise; /** * Connection status for the Broker API. * * You don't need to return values other than `1` (`Connected`) typically since the broker is already connected when you create the widget. * You can use it if you want to display a spinner in the bottom panel while the data is being loaded. */ connectionStatus(): ConnectionStatus; /** * Called by Trading Terminal to request orders */ orders(): Promise; /** * This method is called by the Trading Terminal to request orders history. * It is expected that returned orders will have a final status (`rejected`, `filled`, `cancelled`). * * This method is optional. If you don't support orders history, please set `supportOrdersHistory` flag to `false`. */ ordersHistory?(): Promise; /** * Called by Trading Terminal to request positions */ positions?(): Promise; /** * Called by Trading Terminal to request trades */ trades?(): Promise; /** * Called by Trading Terminal to request executions for the specified symbol * @param {string} symbol - symbol identifier */ executions(symbol: string): Promise; /** * Called by the internal Order dialog, DOM panel, and floating trading panel to get symbol information. * @param {string} symbol - symbol identifier */ symbolInfo(symbol: string): Promise; /** * This function should return the information that will be used to build an Account manager. */ accountManagerInfo(): AccountManagerInfo; /** * Provide a custom price formatter for the specified symbol. * @param {string} symbol - symbol identifier * @param {boolean} alignToMinMove - align formatted number to the minimum movement amount of the symbol */ formatter?(symbol: string, alignToMinMove: boolean): Promise; /** * Provide a custom spread formatter for the specified symbol. * @param {string} symbol - symbol identifier */ spreadFormatter?(symbol: string): Promise; /** * Provide a custom quantity formatter for the specified symbol. * @param {string} symbol - symbol identifier */ quantityFormatter?(symbol: string): Promise; /** * Implement this method if you use the standard Order dialog and want to customize it. * * Use the `symbol` parameter to return customization options for a particular symbol. * @param {string} symbol - symbol identifier */ getOrderDialogOptions?(symbol: string): Promise; /** * Implement this method if you want to customize the position dialog. */ getPositionDialogOptions?(): PositionDialogOptions | undefined; } export interface IBrokerConnectionAdapterFactory { /** Creates a Delegate object */ createDelegate(): IDelegate; /** Creates a WatchedValue object */ createWatchedValue(value?: T): IWatchedValue; /** * Creates a price formatter. * @param priceScale - defines the number of decimal places. It is `10^number-of-decimal-places`. If a price is displayed as `1.01`, `pricescale` is `100`; If it is displayed as `1.005`, `pricescale` is `1000`. * @param minMove - the amount of price precision steps for 1 tick. For example, since the tick size for U.S. equities is `0.01`, `minmov` is 1. But the price of the E-mini S&P futures contract moves upward or downward by `0.25` increments, so the `minmov` is `25`. * @param fractional - for common prices is `false` or it can be skipped. * @param minMove2 - for common prices is `0` or it can be skipped. * @param variableMinTick - for common prices is string (for example, `0.01 10 0.02 25 0.05`) or it can be skipped. * * Example: * 1. Typical stock with `0.01` price increment: `minmov = 1, pricescale = 100, minmove2 = 0`. * 2. If `minmov = 1, pricescale = 100, minmove2 = 0, variableMinTick = "0.01 10 0.02 25 0.05"`: * * - for `price = 9`: `minmov = 1, pricescale = 100, minmove2 = 0`. * - for `price = 13`: `minmov = 2, pricescale = 100, minmove2 = 0`. * - for `price = 27`: `minmov = 5, pricescale = 100, minmove2 = 0`. * * For more information on fractional prices, see this [article](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#price-format) */ createPriceFormatter(priceScale?: number, minMove?: number, fractional?: boolean, minMove2?: number, variableMinTick?: string): IPriceFormatter; } /** * Trading Host is an API for interaction between the Broker API and the Chart Trading Subsystem. * Its main purpose is to exchange information between our charts and your trading adapter. */ export interface IBrokerConnectionAdapterHost { /** Broker Connection Adapter Factory object */ factory: IBrokerConnectionAdapterFactory; /** * Generates and returns the default value formatter for the symbol * @param {string} symbol - symbol identifier * @param {boolean} alignToMinMove - whether the formatted number should be aligned to minimum movement for the symbol */ defaultFormatter(symbol: string, alignToMinMove: boolean): Promise; /** * Generates and returns a number formatter with the desired decimal places * @param {number} decimalPlaces? - decimal places */ numericFormatter(decimalPlaces: number): Promise; /** * Generates and returns a quantity formatter with the desired decimal places * @param {number} decimalPlaces? - decimal places */ quantityFormatter(decimalPlaces?: number): Promise; /** * Provides default buy/sell, show properties actions to be returned as a default by {@link IBrokerCommon.chartContextMenuActions}. * @param {TradeContext} context - trade context * @param {DefaultContextMenuActionsParams} params? - optional parameters */ defaultContextMenuActions(context: TradeContext, params?: DefaultContextMenuActionsParams): Promise; /** * Provides default dropdown list of actions. You can use default actions in {@link IBrokerConnectionAdapterHost.setButtonDropdownActions} * @param {Partial} options? - options for the dropdown menu actions */ defaultDropdownMenuActions(options?: Partial): ActionMetaInfo[]; /** Returns whether the buy/sell buttons are visible or not. */ sellBuyButtonsVisibility(): IWatchedValue | null; /** Returns whether DOM Panel is visible or not. */ domPanelVisibility(): IWatchedValue | null; /** Returns whether the order panel is visible or not. */ orderPanelVisibility(): IWatchedValue | null; /** Returns if orders can be sent to the broker without showing the order ticket. */ silentOrdersPlacement(): IWatchedValue; /** * Patch changes into the current broker configuration * @param {Partial} config - partial configuration changes to apply */ patchConfig(config: Partial): void; /** * Set expiration durations * @param {OrderDurationMetaInfo[]} durations - Expiration options for orders */ setDurations(durations: OrderDurationMetaInfo[]): void; /** * Call this method to notify the chart that it needs to update information after an order is added or changed. * @param {Order} order - order which was added or changed */ orderUpdate(order: Order): void; /** * Call this method when an order is not changed, but the fields that you added to the order object to display in the Account Manager have changed. * It should be used only if you want to display custom fields in the Account Manager. * @param {string} id - order id * @param {Partial} orderChanges - changes made to the order object */ orderPartialUpdate(id: string, orderChanges: Partial): void; /** * Call this method when a position is added or changed. * @param {Position} position - position which was added or changed * @param {boolean} isHistoryUpdate? - whether the change is a history update */ positionUpdate(position: Position, isHistoryUpdate?: boolean): void; /** * Call this method when a position is not changed, but the fields that you added to the position object to display in the Account Manager have changed. * It should be used only if you want to display custom fields in the Account Manager. * @param {string} id - id of the position * @param {Partial} positionChanges - changes to the position object */ positionPartialUpdate(id: string, positionChanges: Partial): void; /** * Call this method when a trade is added or changed. * @param {Trade} trade - updated trade * @param {boolean} isHistoryUpdate? - whether the change is a history update */ tradeUpdate(trade: Trade, isHistoryUpdate?: boolean): void; /** * Call this method when a trade has not changed, but fields that you added to the trade object to display in the Account Manager have changed. * @param {string} id - id of the updated trade * @param {Partial} tradeChanges - changes to the trade object */ tradePartialUpdate(id: string, tradeChanges: Partial): void; /** * Call this method when an execution is added. * @param {Execution} execution - execution which was added */ executionUpdate(execution: Execution): void; /** * Call this method when user account has been changed synchronously. The terminal will re-request all displayed information. */ currentAccountUpdate(): void; /** * Trading quote realtime update * @param {string} symbol - symbol identifier * @param {TradingQuotes} data - realtime updated data for the symbol quotes */ realtimeUpdate(symbol: string, data: TradingQuotes): void; /** * Call this method when a broker connection has received a PL update. This method should be used when `supportPLUpdate` flag is set in `configFlags`. * @param {string} positionId - id of the position * @param {number} pl - updated profit / loss value */ plUpdate(positionId: string, pl: number): void; /** * Call this method when a broker connection has a `pipValue` update. * The library subscribes to `pipValue` updates using {@link IBrokerWithoutRealtime.subscribePipValue}. * @param {string} symbol - symbol with updated pip values * @param {PipValues} pipValues - updated pip values */ pipValueUpdate(symbol: string, pipValues: PipValues): void; /** * Call this method when a broker connection has received a trade PL update. * @param {string} tradeId - id of the trade * @param {number} pl - updated profit / loss for the trade */ tradePLUpdate(tradeId: string, pl: number): void; /** * Call this method when a broker connection has received an equity update. This method is required by the standard Order Dialog to calculate risks. * @param {number} equity - updated equity */ equityUpdate(equity: number): void; /** * Call this method when a broker connection has received a margin available update. * This method is required by the standard Order Dialog to display the margin meter. * This method should be used when `supportMargin` flag is set in `configFlags`. * The Trading Terminal subscribes to margin available updates using {@link IBrokerWithoutRealtime.subscribeMarginAvailable}. * @param {number} marginAvailable - updated available margin */ marginAvailableUpdate(marginAvailable: number): void; /** * Call this method when a broker connection has received a balance update. * This method is required by the crypto Order Dialog. * It should be implemented when `supportBalances` flag is set in `configFlags`. * @param {string} symbol - symbol id * @param {CryptoBalance} balance - updated crypto balance */ cryptoBalanceUpdate(symbol: string, balance: CryptoBalance): void; /** * Update the Depth of Market for the specified symbol * @param {string} symbol - symbol identifier * @param {DOMData} equity - Depth of market data */ domeUpdate(symbol: string, equity: DOMData): void; /** * Shows the order dialog * @param {T extends PreOrder} order - order to show in the dialog * @param {OrderTicketFocusControl} focus? - input control to focus on when dialog is opened */ showOrderDialog?(order: T, focus?: OrderTicketFocusControl): Promise; /** * Shows notification message * @param {string} title - notification title * @param {string} text - notification content * @param {NotificationType} notificationType? - type of notification (default: NotificationType.Error) */ showNotification(title: string, text: string, notificationType?: NotificationType): void; /** * Shows the cancel order dialog for specified order * @param {string} orderId - id of order to potentially cancel * @param {()=>Promise} handler - cancel order confirmation handler (called when order should be cancelled) */ showCancelOrderDialog(orderId: string, handler: () => Promise): Promise; /** * Shows the cancel order dialog for multiple orders * @param {string} symbol - symbol for which to cancel orders * @param {Side} side - side of the order * @param {number} qty - quantity of the order * @param {()=>Promise} handler - cancel orders confirmation handler (called when orders should be cancelled) */ showCancelMultipleOrdersDialog(symbol: string, side: Side, qty: number, handler: () => Promise): Promise; /** * Shows the cancel brackets dialog * @param {string} orderId - id of order * @param {()=>Promise} handler - cancel brackets confirmation handler (called when brackets should be cancelled) */ showCancelBracketsDialog(orderId: string, handler: () => Promise): Promise; /** * Shows the cancel brackets dialog for multiple brackets * @param {string} orderId - id of order * @param {()=>Promise} handler - cancel brackets confirmation handler (called when brackets should be cancelled) */ showCancelMultipleBracketsDialog(orderId: string, handler: () => Promise): Promise; /** * Shows reverse position dialog * @param {string} position - position to be reversed * @param {()=>Promise} handler - reverse position confirmation handler (called when the position should be reversed) */ showReversePositionDialog(position: string, handler: () => Promise): Promise; /** * Shows the position brackets dialog * @param {Position|Trade} position - position or trade * @param {Brackets} brackets - brackets for the position or trade * @param {OrderTicketFocusControl} focus - input control to focus on when dialog is opened */ showPositionBracketsDialog(position: Position | Trade, brackets: Brackets, focus: OrderTicketFocusControl): Promise; /** * Bottom Trading Panel has a button with a list of dropdown items. This method can be used to replace existing items. * @param {ActionMetaInfo[]} descriptions - Descriptions for the dropdown items. */ setButtonDropdownActions(descriptions: ActionMetaInfo[]): void; /** * Activate bottom widget */ activateBottomWidget(): Promise; /** * Shows trading properties */ showTradingProperties(): void; /** * Returns symbol `minTick`. * @param {string} symbol - symbol identifier */ getSymbolMinTick(symbol: string): Promise; /** * Displays a message dialog to a user. * @param {string} title - title of the message dialog * @param {string} text - message * @param {boolean} textHasHTML? - whether message text contains HTML */ showMessageDialog(title: string, text: string, textHasHTML?: boolean): void; /** * Displays a confirmation dialog to a user and returns a Promise to the result. * @param {string} title - title of the confirmation dialog * @param {string|string[]} content - content for the dialog * @param {string} mainButtonText? - text for the main button (`true` result) * @param {string} cancelButtonText? - text for the cancel button (`false` result) * @param {boolean} showDisableConfirmationsCheckbox? - show disable confirmations checkbox within the dialog */ showConfirmDialog(title: string, content: string | string[], mainButtonText?: string, cancelButtonText?: string, showDisableConfirmationsCheckbox?: boolean): Promise; /** * Displays a simple confirmation dialog to a user and returns a Promise to the result. * @param {string} title - title of the confirmation dialog * @param {string|string[]} content - content for the dialog * @param {string} mainButtonText? - text for the main button (`true` result) * @param {string} cancelButtonText? - text for the cancel button (`false` result) * @param {boolean} showDisableConfirmationsCheckbox? - show disable confirmations checkbox within the dialog */ showSimpleConfirmDialog(title: string, content: string | string[], mainButtonText?: string, cancelButtonText?: string, showDisableConfirmationsCheckbox?: boolean): Promise; } export interface IBrokerTerminal extends IBrokerWithoutRealtime { /** * Library is requesting that realtime updates should be supplied for this symbol. * @param {string} symbol - symbol identifier */ subscribeRealtime(symbol: string): void; /** * Library is notifying that realtime updates are no longer required for this symbol. * @param {string} symbol - symbol identifier */ unsubscribeRealtime(symbol: string): void; } export interface IBrokerWithoutRealtime extends IBrokerCommon { /** * Library is requesting that realtime DOM (Depth of Market) updates should be supplied for this symbol * @param {string} symbol - symbol identifier */ subscribeDOME?(symbol: string): void; /** * Library is notifying that realtime DOM (Depth of Market) updates are no longer required for this symbol. * @param {string} symbol - symbol identifier */ unsubscribeDOME?(symbol: string): void; /** * Method is called when a user wants to place an order. Order is pre-filled with partial or complete information. This function returns an object with the order id. * @param {PreOrder} order - order information * @param {string} confirmId? - is passed if `supportPlaceOrderPreview` configuration flag is on. * @returns PlaceOrderResult, which should include an `orderId` */ placeOrder(order: PreOrder, confirmId?: string): Promise; /** * Returns estimated commission, fees, margin and other information for the order without it actually being placed. * The method is called if `supportPlaceOrderPreview` configuration flag is on. * @param {PreOrder} order - order information */ previewOrder?(order: PreOrder): Promise; /** * Method is called when a user wants to modify an existing order. * @param {Order} order - order information * @param {string} confirmId? - is passed if `supportPlaceOrderPreview` configuration flag is on. */ modifyOrder(order: Order, confirmId?: string): Promise; /** * This method is called to cancel a single order with the given `id`. * @param {string} orderId - id for the order to cancel */ cancelOrder(orderId: string): Promise; /** * This method is called to cancel multiple orders for a `symbol` and `side`. * * `ordersIds` parameter should contain the list of order ids to be cancelled. * @param {string} symbol - symbol identifier * @param {Side|undefined} side - order side * @param {string[]} ordersIds - ids already collected by `symbol` and `side` */ cancelOrders(symbol: string, side: Side | undefined, ordersIds: string[]): Promise; /** * This method is called if `supportNativeReversePosition` configuration flag is on. It allows to reverse the position by id. * @param {string} positionId - position */ reversePosition?(positionId: string): Promise; /** * This method is called if `supportClosePosition` configuration flag is on. It allows to close the position by id. * @param {string} positionId - position id * @param {number} amount? - The amount is specified if `supportPartialClosePosition` is `true` and the user wants to close only part of the position. */ closePosition?(positionId: string, amount?: number): Promise; /** * This method is called if `supportCloseTrade` configuration flag is on. It allows to close the trade by id. * @param {string} tradeId - trade id * @param {number} amount? - The amount is specified if `supportPartialCloseTrade` is `true` and the user wants to close only part of the trade. */ closeTrade?(tradeId: string, amount?: number): Promise; /** * This method is called if `supportPositionBrackets` configuration flag is on. It shows a dialog that enables `take profit` and `stop loss` editing. * @param {string} positionId - is an ID of an existing position to be modified * @param {Brackets} brackets - new Brackets to be set for the position * @param {CustomInputFieldsValues} customFields? - custom fields to display in the dialog */ editPositionBrackets?(positionId: string, brackets: Brackets, customFields?: CustomInputFieldsValues): Promise; /** * This method is called if `supportTradeBrackets` configuration flag is on. It displays a dialog that enables take profit and stop loss editing. * @param {string} tradeId - ID of existing trade to be modified * @param {Brackets} brackets - new Brackets to be set for the trade */ editTradeBrackets?(tradeId: string, brackets: Brackets): Promise; /** * This method is called to receive leverageInfo from the broker. * @param {LeverageInfoParams} leverageInfoParams - information about the specific symbol to provide leverage info for */ leverageInfo?(leverageInfoParams: LeverageInfoParams): Promise; /** * This method is called to send user's leverage value to the broker. The value should be verified and corrected on the broker's side if required, and sent back in the response. * @param {LeverageSetParams} leverageSetParams - `leverageSetParams` is an object similar to {@link leverageInfoParams}, but contains an additional `leverage: number` field, which holds the leverage value set by the user. */ setLeverage?(leverageSetParams: LeverageSetParams): Promise; /** * This method is called to receive {@link LeveragePreviewResult} object which holds messages about the leverage value set by the user. * @param {LeverageSetParams} leverageSetParams - `leverageSetParams` is an object similar to {@link leverageInfoParams}, but contains an additional `leverage: number` field, which holds the leverage value set by the user. */ previewLeverage?(leverageSetParams: LeverageSetParams): Promise; /** * @deprecated Brokers should always send PL and equity updates */ subscribePL?(positionId: string): void; /** * The method should be implemented if you use the standard Order dialog and support stop loss. Equity is used to calculate Risk in Percent. * * Once this method is called the broker should provide equity (Balance + P/L) updates via {@link IBrokerConnectionAdapterHost.equityUpdate} method. */ subscribeEquity?(): void; /** * The method should be implemented if you use the standard Order dialog and want to show the margin meter. * * Once this method is called the broker should provide margin available updates via {@link IBrokerConnectionAdapterHost.marginAvailableUpdate} method. * @param {string} symbol - symbol identifier */ subscribeMarginAvailable?(symbol: string): void; /** * The method should be implemented if you use a standard Order dialog. * `pipValues` is displayed in the Order info and it is used to calculate the Trade Value and risks. * If this method is not implemented then `pipValue` from the `symbolInfo` is used in the order panel/dialog. * * Once this method is called the broker should provide `pipValue` updates via {@link IBrokerConnectionAdapterHost.pipValueUpdate} method. * @param {string} symbol - symbol identifier */ subscribePipValue?(symbol: string): void; /** * The method should be implemented if you use a standard Order dialog and implement `subscribePipValue`. * * Once this method is called the broker should stop providing `pipValue` updates. * @param {string} symbol - symbol identifier */ unsubscribePipValue?(symbol: string): void; /** * The method should be implemented if you use the standard Order dialog want to show the margin meter. * * Once this method is called the broker should stop providing margin available updates. * @param {string} symbol - symbol identifier */ unsubscribeMarginAvailable?(symbol: string): void; /** * @deprecated */ unsubscribePL?(positionId: string): void; /** * The method should be implemented if you use the standard Order dialog and support stop loss. * * Once this method is called the broker should stop providing equity updates. */ unsubscribeEquity?(): void; } /** * The main chart API. * * This interface can be retrieved by using the following widget ({@link IChartingLibraryWidget}) methods: * - `chart` ({@link IChartingLibraryWidget.chart}) * - `activeChart` ({@link IChartingLibraryWidget.activeChart}) */ export interface IChartWidgetApi { /** * Get a subscription object for new data being loaded for the chart. * * @returns A subscription object for new data loaded for the chart. */ onDataLoaded(): ISubscription<() => void>; /** * Get a subscription object for the chart symbol changing. * * @returns A subscription object for the chart symbol changing. */ onSymbolChanged(): ISubscription<() => void>; /** * Get a subscription object for the chart interval (resolution) changing. * * @returns A subscription object for the chart interval (resolution) changing. */ onIntervalChanged(): ISubscription<(interval: ResolutionString, timeFrameParameters: { /** * timeframe or dates range. It represents if the user clicks on the timeframe panel or changed the dates range. * * Otherwise `timeframe` is `undefined` and you can change it to display a certain range of bars. Valid timeframe is a `TimeFrameValue` object. */ timeframe?: TimeFrameValue; }) => void>; /** * Get a subscription object for the chart's visible range changing. * * @returns A subscription object for the chart's visible range changing. */ onVisibleRangeChanged(): ISubscription<(range: VisibleTimeRange) => void>; /** * Get a subscription object for the chart type changing. * * @returns A subscription object for the chart type changing. */ onChartTypeChanged(): ISubscription<(chartType: SeriesStyle) => void>; /** * Provide a callback function that will be called when chart data is loaded. * If chart data is already loaded when this method is called then the callback is called immediately. * * @param callback A callback function called when chart data is loaded. */ dataReady(callback: () => void): boolean; /** * Get a subscription object for the crosshair moving over the chart. * * @returns A subscription object for the crosshair moving over the chart. */ crossHairMoved(): ISubscription<(params: CrossHairMovedEventParams) => void>; /** * Scroll and/or scale the chart so a time range is visible. * * @param range A range that will be made visible. * @param options Optional object of options for the new visible range. * @returns A promise that is resolved when the range has been set. */ setVisibleRange(range: SetVisibleTimeRange, options?: SetVisibleRangeOptions): Promise; /** * Change the chart's symbol. * * @param symbol A symbol. * @param callback An optional callback function. Called when the data for the new symbol has loaded. */ setSymbol(symbol: string, callback?: () => void): void; /** * Change the chart's interval (resolution). * * @param symbol A resolution. * @param callback An optional callback function. Called when the data for the new resolution has loaded. */ setResolution(resolution: ResolutionString, callback?: () => void): void; /** * Change the chart's type. * * @param symbol A chart type. * @param callback An optional callback function. Called when the chart type has changed and data has loaded. */ setChartType(type: SeriesStyle, callback?: () => void): void; /** * Force the chart to re-request data. * Before calling this function the `onResetCacheNeededCallback` callback from {@link IDatafeedChartApi.subscribeBars} should be called. */ resetData(): void; /** * Execute an action. * * @param actionId An action ID. */ executeActionById(actionId: ChartActionId): void; /** * Get the state of a checkable action. * @param actionId An action ID. * @returns `true` if the action is checked, `false` otherwise. */ getCheckableActionState(actionId: ChartActionId): boolean; /** * Force the chart to re-request all bar marks and timescale marks. */ refreshMarks(): void; /** * Remove all visible marks. */ clearMarks(): void; /** * Get an array of IDs and name for all drawings on the chart. * * @returns An array of drawing information. */ getAllShapes(): EntityInfo[]; /** * Get an array of IDs and names for all studies on the chart. * * @returns An array of study information. */ getAllStudies(): EntityInfo[]; /** * Get the chart's price to bar ratio. * * @returns The ratio or `null` if no ratio is defined. */ getPriceToBarRatio(): number | null; /** * Set the chart's price to bar ratio. * * @param ratio The new price to bar ratio. * @param options Optional undo options. */ setPriceToBarRatio(ratio: number, options?: UndoOptions): void; /** * Get the locked/unlocked state of the chart's price to bar ratio. */ isPriceToBarRatioLocked(): boolean; /** * Lock or unlock the chart's price to bar ratio. * * @param value `true` to lock, `false` to unlock. * @param options Optional undo options. */ setPriceToBarRatioLocked(value: boolean, options?: UndoOptions): void; /** * Get an array of the heigh of all panes. * * @returns An array of heights. */ getAllPanesHeight(): number[]; /** * Set the height for each pane in the order provided. * * @param heights An array of heights. */ setAllPanesHeight(heights: readonly number[]): void; /** * Maximize to its full size currently selected chart. * * Example: * ```javascript * widget.activeChart().maximizeChart(); * ``` */ maximizeChart(): void; /** * Restore to its initial size currently selected chart. * * Example: * ```javascript * widget.activeChart().restoreChart(); * ``` */ restoreChart(): void; /** * Get an object with operations available for the specified set of entities. * * @param sources An array of entity IDs. */ availableZOrderOperations(sources: readonly EntityId[]): AvailableZOrderOperations; /** * Move the group to the bottom of the Z-order. * * @param sources An array of source IDs. */ sendToBack(entities: readonly EntityId[]): void; /** * Move the sources to the top of the Z-order. * * @param sources An array of source IDs. */ bringToFront(sources: readonly EntityId[]): void; /** * Move the sources one level up in the Z-order. * * @param sources An array of source IDs. */ bringForward(sources: readonly EntityId[]): void; /** * Move the sources one level down in the Z-order. * * @param sources An array of source IDs. */ sendBackward(sources: readonly EntityId[]): void; /** * @deprecated Use drawing/study API instead. * @see {@link getStudyById} * @see {@link getShapeById} */ setEntityVisibility(entityId: EntityId, isVisible: boolean): void; /** * @param {string} name - name of an indicator as shown in the `Indicators` widget * @param {boolean} forceOverlay? - forces the Charting Library to place the created study on the main pane * @param {boolean} lock? - whether a user will be able to remove/change/hide the study or not * @param {Record(name: string, forceOverlay?: boolean, lock?: boolean, inputs?: Record, overrides?: TOverrides, options?: CreateStudyOptions): Promise; /** * @deprecated Prefer `createStudy` function that relies on named properties for `inputs`. * @see {@link createStudy} */ createStudy(name: string, forceOverlay?: boolean, lock?: boolean, inputs?: TStudyInputValue[], overrides?: TOverrides, options?: CreateStudyOptions): Promise; /** * Get a study by ID. * * @param entityId The study ID. * @returns An API object for interacting with the study. */ getStudyById(entityId: EntityId): IStudyApi; /** * Get the main series. * * @returns An API object for interacting with the main series. */ getSeries(): ISeriesApi; /** * Create a new single point drawing. * * @param point A point. The location of the new drawing. * @param options An options object for the new drawing. * @returns The ID of the new drawing if it was created successfully, or null otherwise. */ createShape(point: ShapePoint, options: CreateShapeOptions): EntityId | null; /** * Create a new multi point drawing. * * @param points An array of points that define the drawing. * @param options An options object for the new drawing. * @returns The ID of the new drawing if it was created successfully, or null otherwise. */ createMultipointShape(points: ShapePoint[], options: CreateMultipointShapeOptions): EntityId | null; /** * Create a new anchored drawing. Anchored drawings maintain their position when the chart's visible range changes. * * @param position Percent-based x and y position of the new drawing, relative to the top left of the chart. * @param options An options object for the new drawing. */ createAnchoredShape(position: PositionPercents, options: CreateAnchoredShapeOptions): EntityId | null; /** * Get a drawing by ID. * * @param entityId A drawing ID. * @returns An API object for interacting with the drawing. */ getShapeById(entityId: EntityId): ILineDataSourceApi; /** * Remove an entity (e.g. drawing or study) from the chart. * @param entityId The ID of the entity. * @param options Optional undo options. */ removeEntity(entityId: EntityId, options?: UndoOptions): void; /** * Remove all drawings from the chart. */ removeAllShapes(): void; /** * Remove all studies from the chart. */ removeAllStudies(): void; /** * Get an API object for interacting with the selection. */ selection(): ISelectionApi; /** * Show the properties dialog for a study or drawing. * * @param studyId An ID of the study or drawing. */ showPropertiesDialog(studyId: EntityId): void; /** * Save the current study template to a object. * * @param options An object of study template options. * @returns A study template object. */ createStudyTemplate(options: CreateStudyTemplateOptions): object; /** * Apply a study template to the chart. * * @param template A study template object. */ applyStudyTemplate(template: object): void; /** * Create a new trading order on the chart. * * @param options Optional undo options. * @returns An API object for interacting with the order. */ createOrderLine(options?: UndoOptions): IOrderLineAdapter; /** * Creates a new trading position on the chart. * * @param options Optional undo options. * @returns An API object for interacting with the position. */ createPositionLine(options?: UndoOptions): IPositionLineAdapter; /** * Creates a new trade execution on the chart. * * @param options Optional undo options. * @returns An API object for interacting with the execution. */ createExecutionShape(options?: UndoOptions): IExecutionLineAdapter; /** * Get the name of the current symbol. */ symbol(): string; /** * Get an extended information object for the current symbol. */ symbolExt(): SymbolExt | null; /** * Get the current resolution (interval). */ resolution(): ResolutionString; /** * Get the current visible time range. */ getVisibleRange(): VisibleTimeRange; /** * @deprecated Use Price Scale API instead */ getVisiblePriceRange(): VisiblePriceRange; /** * @deprecated Use rightOffset from TimeScale API instead */ scrollPosition(): number; /** * @deprecated Use defaultRightOffset from TimeScale API instead */ defaultScrollPosition(): number; /** * Returns the object with 'format' function that you can use to format the prices. * * ```javascript * widget.activeChart().priceFormatter().format(123); * ``` */ priceFormatter(): INumberFormatter; /** * Returns the main series style type. * * ```javascript * console.log(widget.activeChart().chartType()); * ``` */ chartType(): SeriesStyle; /** * @deprecated Use Timezone API instead * @see {@link getTimezoneApi} */ setTimezone(timezone: "exchange" | Timezone): void; /** * @deprecated Use Timezone API instead * @see {@link getTimezoneApi} */ getTimezone(): "exchange" | Timezone; /** * Get an API object for interacting with the chart timezone. */ getTimezoneApi(): ITimezoneApi; /** * Get an array of API objects for interacting with the chart panes. */ getPanes(): IPaneApi[]; /** * Export the current data from the chart. * * @param options Optional object of options to control the exported data. * @returns A promise that resolves with the exported data. */ exportData(options?: Partial): Promise; /** * Check if the chart can be zoomed out using the {@link zoomOut} method. * * @returns `true` if the chart can be zoomed out. */ canZoomOut(): boolean; /** * Zoom out. The method has the same effect as clicking on the "Zoom out" button. */ zoomOut(): void; /** * Enable or disable zooming of the chart. * * @param enabled `true` to enable zooming, `false` to disable. */ setZoomEnabled(enabled: boolean): void; /** * Enable or disable scrolling of the chart. * * @param enabled `true` to enable scrolling, `false` to disable. */ setScrollEnabled(enabled: boolean): void; /** * Get an API object for interacting with groups of drawings. */ shapesGroupController(): IShapesGroupControllerApi; /** * Get the bar time to the end of the period * @param {number} unixTime - date timestamp */ barTimeToEndOfPeriod(unixTime: number): number; /** * Get the end of period to bar time * @param {number} unixTime - date timestamp */ endOfPeriodToBarTime(unixTime: number): number; /** * Get an API object for interacting with the timescale. */ getTimeScale(): ITimeScaleApi; /** * Check if bar selection mode is active or not. * * @returns `true` if active, `false` otherwise. */ isSelectBarRequested(): boolean; /** * Switch the chart to bar selection mode. * * @returns A promise that resolves to the timestamp of a bar selected by the user. Rejects if the bar selection was already requested or is cancelled. */ requestSelectBar(): Promise; /** * Cancel any active bar selection requests. */ cancelSelectBar(): void; } /** * The main interface for interacting with the library. * * This interface is returned to you by the widget's constructor ({@link ChartingLibraryWidgetConstructor}). * * **Remark**: Please note that it's safe to call any method only **after** `onChartReady` callback function is called. * * Example: * ```javascript * widget.onChartReady(function() { * // It's now safe to call any other methods of the widget * }); * ``` */ export interface IChartingLibraryWidget { /** * A promise that resolves if and when the header is ready to be used. */ headerReady(): Promise; /** * The library will call `callback` when the chart is ready to be used. * * @param callback A function that will be called when the chart is ready to be used. */ onChartReady(callback: EmptyCallback): void; /** * The library will call `callback` when a greyed-out drawing tool or study is clicked. * * @param callback A function that will be called when a greyed-out drawing tool or study is clicked. */ onGrayedObjectClicked(callback: (obj: GrayedObject) => void): void; /** * The library will call `callback` when the `shortCut` keys are input. * * Use a string separated by '+' for shortcuts using an alphabet character (A to Z) with optional modifiers (ctrl, shift, alt). * Use a number for shortcuts using non-alphabet character without modifiers. * If you don't know the key code you need you can use resources like [keycode.info](https://keycode.info), or [MDN](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) to check. * Use an array of literal key codes and modifier strings for shortcuts using non-alphabet characters with optional modifier strings. * * @param shortCut A number, a string, or an array of number and string. * @param callback A function that will be called when the `shortCut` keys are input. * @example * ```javascript * widget.onShortcut("alt+s", function() { * widget.chart().executeActionById("symbolSearch"); * }); * * // F1 * widget.onShortcut(112, function() { * widget.chart().executeActionById("symbolSearch"); * }); * * // ctrl+shift+\ * widget.onShortcut(['ctrl', 'shift', 220], function() { * widget.chart().executeActionById("symbolSearch"); * }); * ``` */ onShortcut(shortCut: string | number | (string | number)[], callback: EmptyCallback): void; /** * Subscribe to library events. * * @param event A event to subscribe to. * @param callback A callback that will be called when the event happens. */ subscribe(event: EventName, callback: SubscribeEventsMap[EventName]): void; /** * Unsubscribe from library events. * * @param event A event to unsubscribe from. * @param callback A callback to unsubscribe. Must be the same reference as a callback passed to {@link subscribe}. */ unsubscribe(event: EventName, callback: SubscribeEventsMap[EventName]): void; /** * Get an API instance that can be used to interact with a chart. * * @param index Zero based index of the chart. * @returns An API instance. */ chart(index?: number): IChartWidgetApi; /** * Get the configured locale of the widget. For example `en`, `zh`, `ru`. * * @returns A code representing the locale of the widget. */ getLanguage(): LanguageCode; /** * Set the symbol and resolution of the active chart. * @param symbol A symbol to load. * @param interval A interval (resolution) to load. * @param callback A callback. Called when the symbol's data has finished loading. */ setSymbol(symbol: string, interval: ResolutionString, callback: EmptyCallback): void; /** * Remove the widget and all its data from the page. The widget cannot be interacted with after it has been removed. */ remove(): void; /** * Close all open context menus, pop-ups or dialogs. */ closePopupsAndDialogs(): void; /** * Select an icon. It's the same as clicking on the corresponding button in the left toolbar. * * @param linetool An icon drawing tool. * @param options An optional object with options. */ selectLineTool(linetool: "icon", options?: IconOptions): void; /** * Select a drawing or a cursor. It's the same as clicking on the corresponding button in the left toolbar. * * @param linetool A drawing or cursor to select (excluding 'icon') */ selectLineTool(linetool: Omit<"icon", SupportedLineTools>): void; /** * Select a drawing, icon, or a cursor. It's the same as clicking on the corresponding button in the left toolbar. * * @param linetool A drawing or cursor to select. * @param options An optional object with options. Currently only used for the 'icon' drawing. */ selectLineTool(linetool: SupportedLineTools, options?: IconOptions): void; /** * Get the currently selected drawing or cursor. * * @returns An identifier for drawing or cursor. */ selectedLineTool(): SupportedLineTools; /** * Saves the chart state to a object. This method is part of the low-level save/load API. * * @param callback A function called with the chart state as the first argument. */ save(callback: (state: object) => void): void; /** * Loads the chart state from a object. This method is part of the low-level save/load API. * * @param state A chart state object to load. * @param extendedData A optional object of information about the saved state. */ load(state: object, extendedData?: SavedStateMetaInfo): void; /** * Get a list of chart descriptions saved to the server for the current user. * * @param callback A function called with an array of saved chart information as the first argument. */ getSavedCharts(callback: (chartRecords: SaveLoadChartRecord[]) => void): void; /** * Load a saved chart from the server. * * @param chartRecord A chart information object (returned by {@link getSavedCharts}). */ loadChartFromServer(chartRecord: SaveLoadChartRecord): void; /** * Save the current chart to the server. * * @param onComplete An optional callback function called when the chart is successfully saved. * @param onFail An optional callback function called when the chart fails to save. * @param options An optional object of options for saving the chart. */ saveChartToServer(onComplete?: EmptyCallback, onFail?: EmptyCallback, options?: SaveChartToServerOptions): void; /** * Remove a saved chart from the server. * * @param chartId A chart ID from a {@link SaveLoadChartRecord} (returned by {@link getSavedCharts}). * @param onCompleteCallback A callback function called when the chart is successfully saved. */ removeChartFromServer(chartId: string, onCompleteCallback: EmptyCallback): void; /** * The widget will call the callback function each time the widget wants to display a context menu. * See also {@link ChartingLibraryWidgetOptions.context_menu}. * * @param callback A function called with the time and price of the location on the chart that triggered the context menu. * The array of objects returned will add or remove items from the context menu. */ onContextMenu(callback: (unixTime: number, price: number) => ContextMenuItem[]): void; /** * Create a button in the top toolbar. This should be called after {@link headerReady} has resolved. * @param options A optional object of options for the button. * @returns A `HTMLElement` you can customise. */ createButton(options?: CreateHTMLButtonOptions): HTMLElement; /** * Create a button in the top toolbar. This should be called after {@link headerReady} has resolved. * If the `title` option is provided then the title text will be shown in a tooltip on hover. * If the `onClick` option is provided then the button will be clickable. * @param options A optional object of options for the button. */ createButton(options?: CreateTradingViewStyledButtonOptions): void; /** * Create a button in the top toolbar. This should be called after {@link headerReady} has resolved. * @param options A optional object of options for the button. * @returns A `HTMLElement` if the `useTradingViewStyle` option if `false`. `undefined` if `useTradingViewStyle` is `true`. */ createButton(options?: CreateButtonOptions): HTMLElement | undefined; /** * add your own dropdown menu to the top toolbar. * @param {DropdownParams} params */ createDropdown(params: DropdownParams): Promise; /** * Show a dialog with custom title and text along with an "OK" buttons. * @param params A object of options for the created dialog. */ showNoticeDialog(params: DialogParams<() => void>): void; /** * Show a dialog with custom title and text along with "OK" and "CANCEL" buttons. * * @param params A object of options for the created dialog. */ showConfirmDialog(params: DialogParams<(confirmed: boolean) => void>): void; /** * Show the "Load Chart Layout" dialog. */ showLoadChartDialog(): void; /** * Show the "Copy Chart Layout" dialog. */ showSaveAsChartDialog(): void; /** * Get the symbol and interval of the active chart. */ symbolInterval(): SymbolIntervalResult; /** * Get the price formatter for the main series. You can use this to format prices as the char */ mainSeriesPriceFormatter(): INumberFormatter; /** * Get an array of supported intervals (resolutions). * * @returns An array of supported intervals. E.g. `['1D', '5D', '1Y']`. */ getIntervals(): string[]; /** * Get an array of the names of all supported studies. These names can be used when calling {@link createStudy}. * * @returns An array of supported study names. E.g. `['Accumulation/Distribution', 'Accumulative Swing Index', 'Advance/Decline', ...]`. */ getStudiesList(): string[]; /** * Get an array of information about the inputs of a study. * * @param studyName The name of a study. */ getStudyInputs(studyName: string): StudyInputInformation[]; /** * Get information about the styles of a study. * * @param studyName The name of a study. */ getStudyStyles(studyName: string): StudyStyleInfo; /** * Add a custom CSS file for the library to load. * * @param url A url to the custom CSS file. Should be absolute or relative to the `static` folder. */ addCustomCSSFile(url: string): void; /** * Apply overrides to the chart without reloading. See also {@link ChartingLibraryWidgetOptions.overrides}. * * @param overrides An object of overrides to apply to the chart. */ applyOverrides>(overrides: TOverrides): void; /** * Apply overrides to study styles and inputs without reloading. See also {@link ChartingLibraryWidgetOptions.studies_overrides}. * * @param overrides An object of overrides to apply to the studies. */ applyStudiesOverrides(overrides: object): void; /** * Trading Terminal only. Get a promise that resolves with an API object for interacting with the widgetbar (right sidebar) watchlist. * * @returns An API object for interacting with the widgetbar (right sidebar) watchlist. */ watchList(): Promise; /** * Trading Terminal only. Get a promise that resolves with an API object for interacting with the widgetbar (right sidebar) news widget. * * @returns An API object for interacting with the widgetbar (right sidebar) widget. */ news(): Promise; /** * Trading Terminal only. Get a promise that resolves with an API object for interacting with the widgetbar (right sidebar). * * @returns An API object for interacting with the widgetbar (right sidebar). */ widgetbar(): Promise; /** * Get an API object for interacting with the active chart. * * @returns An API object for interacting with the chart. */ activeChart(): IChartWidgetApi; /** * Get the number of charts in the current layout. * * @returns A count of the charts in the current layout. */ chartsCount(): number; /** * Get the current chart layout type. * * @returns A string representation of the current layout type. E.g. `'2h'` for two charts split vertically. */ layout(): LayoutType; /** * Set the current chart layout type. * * @params layout A string representation of the new layout type. E.g. `'2h'` for two charts split vertically. */ setLayout(layout: LayoutType): void; /** * Get the name of the current chart layout. The return value will be `undefined` if the current layout has not been saved. * * @returns A string of the name of the current chart layout. */ layoutName(): string; /** * Change the theme of the chart. * * @param themeName A theme name. * @param options An optional object of options for the theme. * @returns A promise that resolves when the theme has been changed. */ changeTheme(themeName: ThemeName, options?: ChangeThemeOptions): Promise; /** * Get the current theme of the chart. * * @returns A theme name. The name of the current theme. */ getTheme(): ThemeName; /** * Create a snapshot of the chart and upload it to the server. * When it is ready callback functions subscribed to the `'onScreenshotReady'` event using {@link subscribe} will be called. * The URL of the snapshot will be passed as an argument to the callback function. */ takeScreenshot(): void; /** * Create a shapshot of the chart and return it as a canvas. * * @param options An optional object that customises the returned snapshot. * @returns A promise containing a `HTMLCanvasElement` of the snapshot. */ takeClientScreenshot(options?: Partial): Promise; /** * Get a watched value that can be used to read/write/subscribe to the state of the "Lock All Drawing Tools" button. * * @returns A watched value of the state of the "Lock All Drawing Tools" button. */ lockAllDrawingTools(): IWatchedValue; /** * Get a watched value that can be used to read/write/subscribe to the state of the "Hide All Drawing Tools" button. * * @returns A watched value of the state of the "Hide All Drawing Tools" button. */ hideAllDrawingTools(): IWatchedValue; /** * Get a watched value that can be used to read/write/subscribe to the state of the magnet. * * @returns A watched value of the state of the magnet. */ magnetEnabled(): IWatchedValue; /** * Get a watched value that can be used to read/write/subscribe to the state of the magnet mode. * * @returns A watched value of the state of the magnet mode. */ magnetMode(): IWatchedValue; /** * Only available in Trading Terminal. Get a watched value that can be used to read/write/subscribe to the state of the symbol sync between charts. * * @returns A watched value of the state of the symbol sync. */ symbolSync(): IWatchedValue; /** * Only available in Trading Terminal. Get a watched value that can be used to read/write/subscribe to the state of the interval sync between charts. * * @returns A watched value of the state of the interval sync. */ intervalSync(): IWatchedValue; /** * Only available in Trading Terminal. Get a watched value that can be used to read/write/subscribe to the state of the crosshair sync between charts. * * @returns A watched value of the state of the crosshair sync. */ crosshairSync(): IWatchedValue; /** * Only available in Trading Terminal. Get a watched value that can be used to read/write/subscribe to the state of the time sync between charts. * * @returns A watched value of the state of the time sync. */ timeSync(): IWatchedValue; /** * Only available in Trading Terminal. Get a watched value that can be used to read/write/subscribe to the state of the date range sync between charts. * * @returns A watched value of the state of the date range sync. */ dateRangeSync(): IWatchedValue; /** * Set the chart into fullscreen mode (if it isn't already). */ startFullscreen(): void; /** * Set the chart into non-fullscreen mode (if it isn't already). */ exitFullscreen(): void; /** * Get the state of the undo/redo stack. */ undoRedoState(): UndoRedoState; /** * Get a watched value that can be used to read/write/subscribe to the state of the navigation buttons. * * @returns A watched value of the state of the navigation buttons. */ navigationButtonsVisibility(): IWatchedValue; /** * Get a watched value that can be used to read/write/subscribe to the state of the pane buttons. * * @returns A watched value of the state of the pane buttons. */ paneButtonsVisibility(): IWatchedValue; /** * Get a watched value that can be used to read/write/subscribe to the state of the date format. * * @returns A watched value of the state of the date format. */ dateFormat(): IWatchedValue; /** * Get a watched value that can be used to read/write/subscribe to the state of the timeHours format. */ timeHoursFormat(): IWatchedValue; /** * Get a watched value that can be used to read/write/subscribe to the state of the currency and unit * visibility setting on the price scale. * * @returns A watched value of the state of the currency and unit visibility option. */ currencyAndUnitVisibility(): IWatchedValue; /** * Enable or disable debug mode. * * @param enabled A boolean flag. `true` to enable debug mode, `false` to disable. */ setDebugMode(enabled: boolean): void; /** * Clears the undo & redo history. * * **Warning:** this should only be used in very specific cases where you have considered * the UX implications. It is generally unexpected for the user that the undo * history has been cleared. * * An example of an acceptable use-case would be reusing a chart when switching * pages / tabs on a Single Page Application, and presenting it to the user as a * new chart. */ clearUndoHistory(): void; /** * This method returns a readonly WatchedValue ({@link IWatchedValueReadonly}) * object that can be used to read/watch the current supported chart types * ({@link SeriesStyle}) for an active chart. * * The chart type is returned as a number. * You can see which number corresponds to which chart type in the * [Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/) * documentation for `mainSeriesProperties.style`. */ supportedChartTypes(): IWatchedValueReadonly; } export interface IContext { /** * Symbol Instrument */ symbol: ISymbolInstrument; /** * Load a new symbol for the custom indicator * @param {string} tickerid - Symbol identifier * @param {string} period - period for the new symbol * @param {string} currencyCode? - Currency code * @param {string} unitId? - Unit id */ new_sym(tickerid: string, period: string, currencyCode?: string, unitId?: string): ISymbolInstrument; /** * Switch context to the other symbol received through {@link IContext.new_sym} * @param {number} i - the index of the symbol (`0` for the main series) */ select_sym(i: number): void; /** * Creates an in-memory temporary storage with depth defined by the first call `new_var(value).get(n)` * @param {number} value? - variable's value */ new_var(value?: number): IPineSeries; /** * Creates an in-memory temporary storage with unlimited depth. * @param {number} value? - variable's value */ new_unlimited_var(value?: number): IPineSeries; /** * Creates a new context */ new_ctx(): IContext; /** * Checks if symbol is the main symbol * @param {ISymbolInstrument|undefined} symbol - symbol to check * @returns `true` if symbol is the main symbol */ is_main_symbol(symbol: ISymbolInstrument | undefined): boolean; } export interface IContextMenuRenderer { /** * Displays the menu at the position. * @param pos Position to show context menu */ show(pos: ContextMenuPosition): void; /** * hides the menu. */ hide(): void; /** * @returns `true` when the menu is currently displayed. */ isShown(): boolean; } export interface IDatafeedChartApi { /** * The Library calls this function to get marks for visible bars range. * The Library assumes that you will call `onDataCallback` only once per `getMarks` call. * * A few marks per bar are allowed (for now, the maximum is 10). The time of each mark must match the time of a bar. For example, if the bar times are `2023-01-01`, `2023-01-08`, and `2023-01-15`, then a mark cannot have the time `2023-01-05`. * * **Remark:** This function will be called only if you confirmed that your back-end is supporting marks ({@link DatafeedConfiguration.supports_marks}). * * @param symbolInfo A SymbolInfo object * @param from Unix timestamp (leftmost visible bar) * @param to Unix timestamp (rightmost visible bar) * @param onDataCallback Callback function containing an array of marks * @param resolution Resolution of the symbol */ getMarks?(symbolInfo: LibrarySymbolInfo, from: number, to: number, onDataCallback: GetMarksCallback, resolution: ResolutionString): void; /** * The Library calls this function to get timescale marks for visible bars range. * The Library assumes that you will call `onDataCallback` only once per `getTimescaleMarks` call. * * **Remark:** This function will be called only if you confirmed that your back-end is supporting marks ({@link DatafeedConfiguration.supports_timescale_marks}). * * @param symbolInfo A SymbolInfo object * @param from Unix timestamp (leftmost visible bar) * @param to Unix timestamp (rightmost visible bar) * @param onDataCallback Callback function containing an array of marks * @param resolution Resolution of the symbol */ getTimescaleMarks?(symbolInfo: LibrarySymbolInfo, from: number, to: number, onDataCallback: GetMarksCallback, resolution: ResolutionString): void; /** * This function is called if configuration flag supports_time is set to true when chart needs to know the server time. * The charting library expects callback to be called once. * The time is provided without milliseconds. Example: `1445324591`. It is used to display Countdown on the price scale. */ getServerTime?(callback: ServerTimeCallback): void; /** * Provides a list of symbols that match the user's search query. * * @param userInput Text entered by user in the symbol search field * @param exchange The requested exchange. Empty value means no filter was specified * @param symbolType Type of symbol. Empty value means no filter was specified * @param onResult Callback function that returns an array of results ({@link SearchSymbolResultItem}) or empty array if no symbols found */ searchSymbols(userInput: string, exchange: string, symbolType: string, onResult: SearchSymbolsCallback): void; /** * The library will call this function when it needs to get SymbolInfo by symbol name. * * @param symbolName Symbol name or `ticker` * @param onResolve Callback function returning a SymbolInfo ({@link LibrarySymbolInfo}) * @param onError Callback function whose only argument is a text error message * @param extension An optional object with additional parameters */ resolveSymbol(symbolName: string, onResolve: ResolveCallback, onError: ErrorCallback, extension?: SymbolResolveExtension): void; /** * This function is called when the chart needs a history fragment defined by dates range. * * @param symbolInfo A SymbolInfo object * @param resolution Resolution of the symbol * @param periodParams An object used to pass specific requirements for getting bars * @param onResult Callback function for historical data * @param onError Callback function whose only argument is a text error message */ getBars(symbolInfo: LibrarySymbolInfo, resolution: ResolutionString, periodParams: PeriodParams, onResult: HistoryCallback, onError: ErrorCallback): void; /** * Charting Library calls this function when it wants to receive real-time updates for a symbol. * The Library assumes that you will call the callback provided by the `onTick` parameter every time you want to update the most recent bar or to add a new one. * * @param symbolInfo A SymbolInfo object * @param resolution Resolution of the symbol * @param onTick Callback function returning a Bar object * @param listenerGuid * @param onResetCacheNeededCallback Function to be executed when bar data has changed */ subscribeBars(symbolInfo: LibrarySymbolInfo, resolution: ResolutionString, onTick: SubscribeBarsCallback, listenerGuid: string, onResetCacheNeededCallback: () => void): void; /** * The library calls this function when it doesn't want to receive updates anymore. * * @param listenerGuid id to unsubscribe from */ unsubscribeBars(listenerGuid: string): void; /** * Trading Terminal calls this function when it wants to receive real-time level 2 (DOM) for a symbol. * * @param symbol A SymbolInfo object * @param callback Function returning an object to update Depth Of Market (DOM) data * @returns A unique identifier that will be used to unsubscribe from the data */ subscribeDepth?(symbol: string, callback: DomeCallback): string; /** * Trading Terminal calls this function when it doesn't want to receive updates for this listener anymore. * * @param subscriberUID A string returned by `subscribeDepth` */ unsubscribeDepth?(subscriberUID: string): void; /** * The library calls this function to get the resolution that will be used to calculate the Volume Profile Visible Range indicator. * * Usually you might want to implement this method to calculate the indicator more accurately. * The implementation really depends on how much data you can transfer to the library and the depth of data in your data feed. * **Remark:** If this function is not provided the library uses currentResolution. * * @param currentResolution Resolution of the symbol * @param from Unix timestamp (leftmost visible bar) * @param to Unix timestamp (rightmost visible bar) * @param symbolInfo A Symbol object * @returns A resolution */ getVolumeProfileResolutionForPeriod?(currentResolution: ResolutionString, from: number, to: number, symbolInfo: LibrarySymbolInfo): ResolutionString; } /** Quotes datafeed API */ export interface IDatafeedQuotesApi { /** * This function is called when the library needs quote data. * The charting library assumes that `onDataCallback` is called once when all the requested data is received. * @param {string[]} symbols - symbol names. * @param {QuotesCallback} onDataCallback - callback to return the requested data. * @param {QuotesErrorCallback} onErrorCallback - callback for responding with an error. */ getQuotes(symbols: string[], onDataCallback: QuotesCallback, onErrorCallback: QuotesErrorCallback): void; /** * Trading Terminal calls this function when it wants to receive real-time quotes for a symbol. * The library assumes that you will call `onRealtimeCallback` every time you want to update the quotes. * @param {string[]} symbols - list of symbols that should be updated rarely (once per minute). These symbols are included in the watchlist but they are not visible at the moment. * @param {string[]} fastSymbols - list of symbols that should be updated frequently (at least once every 10 seconds) * @param {QuotesCallback} onRealtimeCallback - callback to send realtime quote data updates * @param {string} listenerGUID - unique identifier of the listener */ subscribeQuotes(symbols: string[], fastSymbols: string[], onRealtimeCallback: QuotesCallback, listenerGUID: string): void; /** * Trading Terminal calls this function when it doesn't want to receive updates for this listener anymore. * `listenerGUID` will be the same object that the Library passed to `subscribeQuotes` before. * @param {string} listenerGUID - unique identifier of the listener */ unsubscribeQuotes(listenerGUID: string): void; } export interface IDelegate extends ISubscription { /** Fire (Evoke) */ fire: TFunc; } /** * # IDESTRØYÅBLE * ``` * ┌────────────────┐ * │ ┏━━━━━┓ │ * │ ┃ ○ ○ ┃ │ ┏━━━━━┓ ┌╲╌╌╱╌┐ * │ ┃ ○ ○ ┃ x 1 │ ┃ ○ ○ ┃ destroy() ┊ ╲╱ ╵ * │ ┠─────┨ │ ┃ ○ ○ ┃ ╭───╯╲ ╷ ╱╲ ┊ * │ ┗━━━━━┛ │ ┠─────┨ ╰───╮╱ ├╱ ╌╲ ┤ * │ destroy() x 1 │ ┗━━━━━┛ └ ╌╌ ╌┘ * └────────────────┘ * ``` */ export interface IDestroyable { /** Clean up (destroy) any subscriptions, intervals, or other resources that this `IDestroyable` instance has. */ destroy(): void; } /** Dropdown menu API */ export interface IDropdownApi { /** * Apply options to the dropdown menu. * @param {DropdownUpdateParams} options - Partial options for the dropdown menu */ applyOptions(options: DropdownUpdateParams): void; /** * Remove the dropdown menu. */ remove(): void; } /** * An API object used to control execution lines. */ export interface IExecutionLineAdapter { /** * Remove the execution line. This API object cannot be used after this call. */ remove(): void; /** * Get the price of the execution line. */ getPrice(): number; /** * Set the price of the execution line. * * @param value The new price. */ setPrice(value: number): this; /** * Get the time of the execution line. */ getTime(): number; /** * Set the time of the execution line. * * @param value The new time. */ setTime(value: number): this; /** * Get the direction of the execution line. */ getDirection(): Direction; /** * Set the direction of the execution line. * * @param value The new direction. */ setDirection(value: Direction): this; /** * Get the text of the execution line. */ getText(): string; /** * Set the text of the execution line. * * @param value The new text. */ setText(value: string): this; /** * Get the tooltip of the execution line. */ getTooltip(): string; /** * Set the tooltip of the execution line. * * @param value The new tooltip. */ setTooltip(value: string): this; /** * Get the arrow height of the execution line. */ getArrowHeight(): number; /** * Set the arrow height of the execution line. * * @param value The new arrow height. */ setArrowHeight(value: number): this; /** * Get the arrow spacing of the execution line. */ getArrowSpacing(): number; /** * Set the arrow spacing of the execution line. * * @param value The new arrow spacing. */ setArrowSpacing(value: number): this; /** * Get the font of the execution line. */ getFont(): string; /** * Set the font of the execution line. * * @param value The new font. */ setFont(value: string): this; /** * Get the text color of the execution line. */ getTextColor(): string; /** * Set the text color of the execution line. * * @param value The new text color. */ setTextColor(value: string): this; /** * Get the arrow color of the execution line. */ getArrowColor(): string; /** * Set the arrow color of the execution line. * * @param value The new arrow color. */ setArrowColor(value: string): this; } export interface IExternalDatafeed { /** * This call is intended to provide the object filled with the configuration data. * Charting Library assumes that you will call the callback function and pass your datafeed {@link DatafeedConfiguration} as an argument. * * @param {OnReadyCallback} callback - callback to return your datafeed configuration ({@link DatafeedConfiguration}) to the library. */ onReady(callback: OnReadyCallback): void; } export interface IExternalSaveLoadAdapter { /** * Get all saved charts. * @returns Array of chart meta information */ getAllCharts(): Promise; /** * Remove a chart. * @param id - Unique ID of the chart (see {@link getAllCharts}) */ removeChart(id: T): Promise; /** * Save the chart * @param {ChartData} chartData - Chart description data * @returns unique ID of the chart */ saveChart(chartData: ChartData): Promise; /** * Load the chart from the server * @param {number} chartId - Unique ID of the chart to load (see {@link getAllCharts}) * @returns chart content contained in the `content` field when saving the chart ({@link ChartData}) */ getChartContent(chartId: number): Promise; /** * Get all saved study templates * @returns Array of study template meta information */ getAllStudyTemplates(): Promise; /** * Remove a study template * @param {StudyTemplateMetaInfo} studyTemplateInfo */ removeStudyTemplate(studyTemplateInfo: StudyTemplateMetaInfo): Promise; /** * Save a study template * @param {StudyTemplateData} studyTemplateData - Study template data to save */ saveStudyTemplate(studyTemplateData: StudyTemplateData): Promise; /** * load a study template from the server * @param {StudyTemplateMetaInfo} studyTemplateInfo * @returns Study template `content` */ getStudyTemplateContent(studyTemplateInfo: StudyTemplateMetaInfo): Promise; /** * Get names of all saved drawing templates * @param {string} toolName - name of the drawing tool * @returns names of saved drawing templates */ getDrawingTemplates(toolName: string): Promise; /** * Load a drawing template from the server * @param {string} toolName - name of the drawing tool * @param {string} templateName - name of the template * @returns content of the drawing template */ loadDrawingTemplate(toolName: string, templateName: string): Promise; /** * Remove a drawing template * @param {string} toolName - name of the drawing tool * @param {string} templateName - name of the template */ removeDrawingTemplate(toolName: string, templateName: string): Promise; /** * Save a drawing template * @param {string} toolName - name of the drawing tool * @param {string} templateName - name of the template * @param {string} content - content of the drawing template */ saveDrawingTemplate(toolName: string, templateName: string, content: string): Promise; } /** Definition of a formatter */ export interface IFormatter { /** Whatever the input type, formats the data following a certain logic and return that value as a string */ format(value?: T): string; /** Check if the input value satisfies the logic and return either an error or the result of the parsing */ parse?(value: string): ErrorFormatterParseResult | SuccessFormatterParseResult; } /** * Drawing API * * You can retrieve this interface by using the {@link IChartWidgetApi.getShapeById} method. */ export interface ILineDataSourceApi { /** * Is the drawing selectable by the user. * @returns `true` when the drawing can be selected */ isSelectionEnabled(): boolean; /** * Set whether the drawing can be selected by the user or not. * @param {boolean} enable - if `true` then the user can select the drawing (see `disableSelection` option of `createMultipointShape`) */ setSelectionEnabled(enable: boolean): void; /** * Can the drawing be saved in the chart layout * @returns `true` when the drawing can be saved */ isSavingEnabled(): boolean; /** * Enables or disables saving of the drawing in the chart layout (see `disableSave` option of `createMultipointShape`). * @param {boolean} enable - if `true`, the drawing can be saved to the chart */ setSavingEnabled(enable: boolean): void; /** * Is the drawing shown in the Object Tree Panel * @returns `true` when the drawing is visible in the tree. */ isShowInObjectsTreeEnabled(): boolean; /** * Enables or disables the visibility of the drawing in the Object Tree panel * @param {boolean} enabled - if `true` then the drawing will be visible */ setShowInObjectsTreeEnabled(enabled: boolean): void; /** * Is the drawing editable by the user. * @returns `true` when the drawing is editable */ isUserEditEnabled(): boolean; /** * Enables or disables whether the drawing is editable * @param {boolean} enabled - if `true`, then the drawing will be editable */ setUserEditEnabled(enabled: boolean): void; /** * Places the drawing on top of all other chart objects. */ bringToFront(): void; /** * Places the drawing behind all other chart objects. */ sendToBack(): void; /** * Get all the properties of the drawing. * @returns properties of the drawing */ getProperties(): Record; /** * Sets the properties of the drawing. * @param {object} newProperties - Drawing properties to be set on the drawing. It should have the same structure as an object from {@link ILineDataSourceApi.getProperties}. It can only include the properties that you want to override. */ setProperties(newProperties: object): void; /** * Returns the points of the drawing. */ getPoints(): PricedPoint[]; /** * Set the new points of the drawing. All points must be provided: for example if the drawing is defined by 5 points then all 5 must be provided. * * @param points - The new points. * */ setPoints(points: ShapePoint[]): void; /** * Get the position percents of a fixed drawing. */ getAnchoredPosition(): PositionPercents | undefined; /** * Set the position percents for a fixed drawing. * For example `setPoints([{ x: 0.1, y: 0.1 }])` would set a fixed drawing defined by * a single point to be 10% top the left edge of the chart and 10% from the top edge. * * @param positionPercents The new position percents. */ setAnchoredPosition(positionPercents: PositionPercents): void; } export interface IMenuItem { /** Menu item type */ readonly type: MenuItemType; /** * An unique ID of an action item. Could be used to distinguish actions between each other. */ readonly id: string; } export interface INewsApi { /** Refresh News */ refresh(): void; } export interface INonSeriesStudyBarsResult { /** * Non series bars */ bars: IBarArray[]; } export interface INonSeriesStudyResult { /** Type is `non_series_data` */ type: "non_series_data"; /** Always true */ nonseries: true; /** Data */ data: object; } export interface IObservable { /** * Subscribe to changes * @param {(value:T)=>void} callback - callback function to be evoked when observed value changes */ subscribe(callback: (value: T) => void): void; /** * Unsubscribe from changes * @param {(value:T)=>void} callback - callback function to be unsubscribed */ unsubscribe(callback: (value: T) => void): void; } export interface IObservableValue extends IBoxedValue, IObservable { } export interface IObservableValueReadOnly extends IBoxedValueReadOnly, IObservable { } /** * An API object used to control order lines. */ export interface IOrderLineAdapter { /** * Remove the order line. This API object cannot be used after this call. */ remove(): void; /** * Attach a callback to be executed when the order line is modified. * * @param callback Callback to be executed when the order line is modified. */ onModify(callback: () => void): this; /** * Attach a callback to be executed when the order line is modified. * * @param data Data to be passed to the callback. * @param callback Callback to be executed when the order line is modified. */ onModify(data: T, callback: (data: T) => void): this; /** * Attach a callback to be executed when the order line is moved. * * @param callback Callback to be executed when the order line is moved. */ onMove(callback: () => void): this; /** * Attach a callback to be executed when the order line is moved. * * @param data Data to be passed to the callback. * @param callback Callback to be executed when the order line is moved. */ onMove(data: T, callback: (data: T) => void): this; /** * Attach a callback to be executed when the order line is cancelled. * * @param callback Callback to be executed when the order line is cancelled. */ onCancel(callback: () => void): this; /** * Attach a callback to be executed when the order line is cancelled. * * @param data Data to be passed to the callback. * @param callback Callback to be executed when the order line is cancelled. */ onCancel(data: T, callback: (data: T) => void): this; /** * Get the price of the order line. */ getPrice(): number; /** * Set the price of the order line. * * @param value The new price */ setPrice(value: number): this; /** * Get the text of the order line. */ getText(): string; /** * Set the text of the order line. * * @param value The new text */ setText(value: string): this; /** * Get the tooltip of the order line. */ getTooltip(): string; /** * Set the tooltip of the order line. * * @param value The new tooltip */ setTooltip(value: string): this; /** * Get the modify tooltip of the order line. */ getModifyTooltip(): string; /** * Set the modify tooltip of the order line. * * @param value The new modify tooltip */ setModifyTooltip(value: string): this; /** * Get the cancel tooltip of the order line. */ getCancelTooltip(): string; /** * Set the cancel tooltip of the order line. * * @param value The new cancel tooltip */ setCancelTooltip(value: string): this; /** * Get the quantity of the order line. */ getQuantity(): string; /** * Set the quantity of the order line. * * @param value The new quantity. */ setQuantity(value: string): this; /** * Get the editable flag value of the order line. */ getEditable(): boolean; /** * Set the editable of the order line. * * @param value The new editable. */ setEditable(value: boolean): this; /** * Get the cancellable flag value of the order line. */ getCancellable(): boolean; /** * Set the cancellable flag value of the order line. * * @param value The new cancellable flag value. */ setCancellable(value: boolean): this; /** * Get the extend left flag value of the order line. */ getExtendLeft(): boolean; /** * Set the extend left flag value of the order line. * * @param value The new extend left flag value. */ setExtendLeft(value: boolean): this; /** * Get the line length of the order line. */ getLineLength(): number; /** * Set the line length of the order line. * * @param value The new line length. */ setLineLength(value: number): this; /** * Get the line style of the order line. */ getLineStyle(): number; /** * Set the line style of the order line. * * @param value The new line style. */ setLineStyle(value: number): this; /** * Get the line width of the order line. */ getLineWidth(): number; /** * Set the line width of the order line. * * @param value The new line width. */ setLineWidth(value: number): this; /** * Get the body font of the order line. */ getBodyFont(): string; /** * Set the body font of the order line. * * @param value The new body font. */ setBodyFont(value: string): this; /** * Get the quantity font of the order line. */ getQuantityFont(): string; /** * Set the quantity font of the order line. * * @param value The new quantity font. */ setQuantityFont(value: string): this; /** * Get the line color of the order line. */ getLineColor(): string; /** * Set the line color of the order line. * * @param value The new line color. */ setLineColor(value: string): this; /** * Get the body border color of the order line. */ getBodyBorderColor(): string; /** * Set the body border color of the order line. * * @param value The new body border color. */ setBodyBorderColor(value: string): this; /** * Get the body background color of the order line. */ getBodyBackgroundColor(): string; /** * Set the body background color of the order line. * * @param value The new body background color. */ setBodyBackgroundColor(value: string): this; /** * Get the body text color of the order line. */ getBodyTextColor(): string; /** * Set the body text color of the order line. * * @param value The new body text color. */ setBodyTextColor(value: string): this; /** * Get the quantity border color of the order line. */ getQuantityBorderColor(): string; /** * Set the quantity border color of the order line. * * @param value The new quantity border color. */ setQuantityBorderColor(value: string): this; /** * Get the quantity background color of the order line. */ getQuantityBackgroundColor(): string; /** * Set the quantity background color of the order line. * * @param value The new quantity background color. */ setQuantityBackgroundColor(value: string): this; /** * Get the quantity text color of the order line. */ getQuantityTextColor(): string; /** * Set the quantity text color of the order line. * * @param value The new quantity text color. */ setQuantityTextColor(value: string): this; /** * Get the cancel button border color of the order line. */ getCancelButtonBorderColor(): string; /** * Set the cancel button border color of the order line. * * @param value The new cancel button border color. */ setCancelButtonBorderColor(value: string): this; /** * Get the cancel button background color of the order line. */ getCancelButtonBackgroundColor(): string; /** * Set the cancel button background color of the order line. * * @param value The new cancel button background color. */ setCancelButtonBackgroundColor(value: string): this; /** * Get the cancel button icon color of the order line. */ getCancelButtonIconColor(): string; /** * Set the cancel button icon color of the order line. * * @param value The new cancel button icon color. */ setCancelButtonIconColor(value: string): this; } /** * You can retrieve this interface by using the {@link IChartWidgetApi.getPanes} method */ export interface IPaneApi { /** Returns `true` if the price scale contains the main series */ hasMainSeries(): boolean; /** * Returns an array of the PriceScaleApi instances that allows interaction with right price scales. * The array may be empty if there is not any price scale on the left side of the pane */ getLeftPriceScales(): readonly IPriceScaleApi[]; /** * Returns an array of the PriceScaleApi instances that allows interaction with right price scales. * The array may be empty if there is not any price scale on the right side of the pane */ getRightPriceScales(): readonly IPriceScaleApi[]; /** * Returns an instance of the PriceScaleApi that allows you to interact with the price scale of the main source * or `null` if the main source is not attached to any price scale (it is in 'No Scale' mode) */ getMainSourcePriceScale(): IPriceScaleApi | null; /** Returns the pane's height */ getHeight(): number; /** Sets the pane's height */ setHeight(height: number): void; /** Moves the pane to a new position, `paneIndex` should be a number between 0 and all panes count - 1 */ moveTo(paneIndex: number): void; /** Returns the pane's index, it's a number between 0 and all panes count - 1 */ paneIndex(): number; /** Collapse the current pane */ collapse(): void; /** Restore the size of a previously collapsed pane */ restore(): void; } export interface IPineSeries { /** * Get the value at a specific index. * * Note: The indices of a pine series is opposite. * * Example: * - s.get(1) returns second last, * - s.get(2) - third last * - and so on * @param {number} n? - index */ get(n?: number): number; /** * Set the value for the pine series at the current index interation. * @param {number} value - value to be set */ set(value: number): void; /** * Get the index for the bar at the specified timestamp * @param {number} time - timestamp */ indexOf(time: number): number; } /** * An API object used to control position lines. */ export interface IPositionLineAdapter { /** * Remove the position line. This API object cannot be used after this call. */ remove(): void; /** * Attach a callback to be executed when the position line is closed. * * @param callback Callback to be executed when the position line is closed. */ onClose(callback: () => void): this; /** * Attach a callback to be executed when the position line is closed. * * @param data Data to be passed to the callback. * @param callback Callback to be executed when the position line is closed. */ onClose(data: T, callback: (data: T) => void): this; /** * Attach a callback to be executed when the position line is modified. * * @param callback Callback to be executed when the position line is modified. */ onModify(callback: () => void): this; /** * Attach a callback to be executed when the position line is modified. * * @param data Data to be passed to the callback. * @param callback Callback to be executed when the position line is modified. */ onModify(data: T, callback: (data: T) => void): this; /** * Attach a callback to be executed when the position line is reversed. * * @param callback Callback to be executed when the position line is reversed. */ onReverse(callback: () => void): this; /** * Attach a callback to be executed when the position line is reversed. * * @param data Data to be passed to the callback. * @param callback Callback to be executed when the position line is reversed. */ onReverse(data: T, callback: (data: T) => void): this; /** * Get the price of the position line. */ getPrice(): number; /** * Set the price of the position line. * * @param value The new price. */ setPrice(value: number): this; /** * Get the text of the position line. */ getText(): string; /** * Set the text of the position line. * * @param value The new text. */ setText(value: string): this; /** * Get the tooltip of the position line. */ getTooltip(): string; /** * Set the tooltip of the position line. * * @param value The new tooltip. */ setTooltip(value: string): this; /** * Get the protect tooltip of the position line. */ getProtectTooltip(): string; /** * Set the protect tooltip of the position line. * * @param value The new protect tooltip. */ setProtectTooltip(value: string): this; /** * Get the close tooltip of the position line. */ getCloseTooltip(): string; /** * Set the close tooltip of the position line. * * @param value The new close tooltip. */ setCloseTooltip(value: string): this; /** * Get the reverse tooltip of the position line. */ getReverseTooltip(): string; /** * Set the reverse tooltip of the position line. * * @param value The new reverse tooltip. */ setReverseTooltip(value: string): this; /** * Get the quantity of the position line. */ getQuantity(): string; /** * Set the quantity of the position line. * * @param value The new quantity. */ setQuantity(value: string): this; /** * Get the extend left flag value of the position line. */ getExtendLeft(): boolean; /** * Set the extend left flag value of the position line. * @param value The new extend left flag value. */ setExtendLeft(value: boolean): this; /** * Get the line length of the position line. */ getLineLength(): number; /** * Set the line length of the position line. * @param value The new line length. */ setLineLength(value: number): this; /** * Get the line style of the position line. */ getLineStyle(): number; /** * Set the line style of the position line. * @param value The new line style. */ setLineStyle(value: number): this; /** * Get the line width of the position line. */ getLineWidth(): number; /** * Set the line width of the position line. * @param value The new line width. */ setLineWidth(value: number): this; /** * Get the body font of the position line. */ getBodyFont(): string; /** * Set the body font of the position line. * @param value The new body font. */ setBodyFont(value: string): this; /** * Get the quantity font of the position line. */ getQuantityFont(): string; /** * Set the quantity font of the position line. * @param value The new quantity font. */ setQuantityFont(value: string): this; /** * Get the line color of the position line. */ getLineColor(): string; /** * Set the line color of the position line. * @param value The new line color. */ setLineColor(value: string): this; /** * Get the body border color of the position line. */ getBodyBorderColor(): string; /** * Set the body border color of the position line. * @param value The new body border color. */ setBodyBorderColor(value: string): this; /** * Get the body font of the position line. */ getBodyBackgroundColor(): string; /** * Set the body font of the position line. * @param value The new body font. */ setBodyBackgroundColor(value: string): this; /** * Get the body text color of the position line. */ getBodyTextColor(): string; /** * Set the body text color of the position line. * @param value The new body text color. */ setBodyTextColor(value: string): this; /** * Get the quantity border color of the position line. */ getQuantityBorderColor(): string; /** * Set the quantity border color of the position line. * * @param value The new quantity border color. */ setQuantityBorderColor(value: string): this; /** * Get the quantity background color of the position line. */ getQuantityBackgroundColor(): string; /** * Set the quantity background color of the position line. * * @param value The new quantity background color. */ setQuantityBackgroundColor(value: string): this; /** * Get the quantity text color of the position line. */ getQuantityTextColor(): string; /** * Set the quantity text color of the position line. * * @param value The new quantity text color. */ setQuantityTextColor(value: string): this; /** * Get the reverse button border color of the position line. */ getReverseButtonBorderColor(): string; /** * Set the reverse button border color of the position line. * @param value The new reverse button border color. */ setReverseButtonBorderColor(value: string): this; /** * Get the reverse button background color of the position line. */ getReverseButtonBackgroundColor(): string; /** * Set the reverse button background color of the position line. * @param value The new reverse button background color. */ setReverseButtonBackgroundColor(value: string): this; /** * Get the reverse button icon color of the position line. */ getReverseButtonIconColor(): string; /** * Set the reverse button icon color of the position line. * @param value The new reverse button icon color. */ setReverseButtonIconColor(value: string): this; /** * Get the close button border color of the position line. */ getCloseButtonBorderColor(): string; /** * Set the close button border color of the position line. * @param value The new close button border color. */ setCloseButtonBorderColor(value: string): this; /** * Get the close button background color of the position line. */ getCloseButtonBackgroundColor(): string; /** * Set the close button background color of the position line. * @param value The new close button background color. */ setCloseButtonBackgroundColor(value: string): this; /** * Get the close button icon color of the position line. */ getCloseButtonIconColor(): string; /** * Set the close button icon color of the position line. * @param value The new close button icon color. */ setCloseButtonIconColor(value: string): this; } /** * Specific formatter for numbers */ export interface IPriceFormatter extends ISymbolValueFormatter { /** * Price Formatter * @param {number} price - price * @param {boolean} signPositive? - add plus sign to result string. * @param {number} tailSize? - add `tailSize` digits to fractional part of result string * @param {boolean} signNegative? - add minus sign to result string. * @param {boolean} useRtlFormat? - Use Right to left format * @param {boolean} cutFractionalByPrecision? - cuts price by priceScalePrecision, without rounding. * @returns formatted price */ format(price: number, signPositive?: boolean, tailSize?: number, signNegative?: boolean, useRtlFormat?: boolean, cutFractionalByPrecision?: boolean): string; } /** * You can retrieve this interface by evoking the following methods of the {@link IPaneApi}: * - `getLeftPriceScales` * - `getRightPriceScales` * - `getMainSourcePriceScale` */ export interface IPriceScaleApi { /** Returns current mode of the price scale */ getMode(): PriceScaleMode; /** * Changes current mode of the price scale * @param newMode new mode to set for the price scale */ setMode(newMode: PriceScaleMode): void; /** Returns whether the price scale is inverted or not */ isInverted(): boolean; /** * Changes current inverted state of the price scale * @param isInverted set to `true` if the price scale should become inverted */ setInverted(isInverted: boolean): void; /** * Returns `true` when the price scale is locked */ isLocked(): boolean; /** * Set whether the price scale should be locked or not * @param {boolean} isLocked - set to `true` to lock the price scale */ setLocked(isLocked: boolean): void; /** * Returns `true` when the price scale has auto scaling enabled */ isAutoScale(): boolean; /** * Set whether auto scaling should be enabled or not for the price scale * @param {boolean} isAutoScale - set to `true` to enable auto scaling */ setAutoScale(isAutoScale: boolean): void; /** * Returns current visible price range of the price scale. * The result is an object with `from` and `to`, * which are the boundaries of the price scale visible range. */ getVisiblePriceRange(): VisiblePriceRange | null; /** * Sets current visible price range of the price scale, * @param range an object with `from` and `to`, which are the boundaries of the price scale visible range. */ setVisiblePriceRange(range: VisiblePriceRange): void; /** Returns `true` if the price scale contains the main series */ hasMainSeries(): boolean; /** Returns an array of IDs of all studies attached to the price scale */ getStudies(): EntityId[]; } export interface IProjectionStudyResult { /** array of projection bars */ bars: IProjectionBar[]; /** always true */ nonseries?: boolean; /** last price displayed on price scale */ price?: number; /** always projection */ type?: "projection"; /** box size is displayed in the legend */ boxSize?: number; /** reversal amount is displayed in the legend */ reversalAmount?: number; } /** * Allows you to select entities ([drawings](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Drawings) and [indicators](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators/)) on the chart. Consider the following example: * * ```js * var chart = tvWidget.activeChart(); * // Prints all selection changes to the console * chart.selection().onChanged().subscribe(null, s => console.log(chart.selection().allSources())); * // Creates an indicator and saves its ID * var studyId = chart.createStudy("Moving Average", false, false, { length: 10 }); * // Adds the indicator to the selection ([] is printed to the console) * chart.selection().add(studyId); * // Clears the selection ([] is printed to the console) * chart.selection().clear(); * ``` * * #### Multiple Selection * * Multiple selection has the following specifics: * * - Either indicators or drawings can be selected at the same time. * - If you add an indicator to the selection, other entities are removed from it. * - Adding an array of objects to the selection works the same as adding these objects one by one. */ export interface ISelectionApi { /** * Add entity / entities to selection * @param {EntityId[]|EntityId} entities - entities to be added to selection */ add(entities: EntityId[] | EntityId): void; /** * Set entity / entities as the selection * @param {EntityId[]|EntityId} entities - entities to be selected */ set(entities: EntityId[] | EntityId): void; /** * Remove entities from the selection * @param {EntityId[]} entities - entities to be removed from the selection */ remove(entities: EntityId[]): void; /** * Does the selection contain the entity * @param {EntityId} entity - entity to be checked * @returns `true` when entity is in the selection */ contains(entity: EntityId): boolean; /** * Returns all the entities in the selection */ allSources(): EntityId[]; /** * Is the selection empty * @returns `true` when empty */ isEmpty(): boolean; /** * Clear selection */ clear(): void; /** * Subscription for selection changes. */ onChanged(): ISubscription<() => void>; /** * Whether the entity can be added to the selection * @param {EntityId} entity - entity to be checked * @returns `true` when entity can be added to the selection */ canBeAddedToSelection(entity: EntityId): boolean; } export interface ISeparator extends IMenuItem { /** @inheritDoc */ readonly type: MenuItemType.Separator; } /** * Series API * * You can retrieve this interface by using the {@link IChartWidgetApi.getSeries} method */ export interface ISeriesApi { /** Returns `true` if a user is able to remove/change/hide the main series */ isUserEditEnabled(): boolean; /** * Enables or disables removing/changing/hiding the main series by the user */ setUserEditEnabled(enabled: boolean): void; /** Merges the main series up (if possible) */ mergeUp(): void; /** Merges the main series down (if possible) */ mergeDown(): void; /** Unmerges the main series up (if possible) */ unmergeUp(): void; /** Unmerges the main series down (if possible) */ unmergeDown(): void; /** Pins the main series to a new price axis at right */ detachToRight(): void; /** Pins the main series to a new price axis at left */ detachToLeft(): void; /** Makes the main series to be an overlay source */ detachNoScale(): void; /** Changes the price scale of the main series */ changePriceScale(newPriceScale: SeriesPriceScale): void; /** Returns `true` if the main series is visible */ isVisible(): boolean; /** Shows/hides the main series */ setVisible(visible: boolean): void; /** Places main series on top of all other chart objects */ bringToFront(): void; /** Places main series behind all other chart objects */ sendToBack(): void; /** Value that is returned when a study is created via API */ entityId(): EntityId; /** Returns properties for a specific chart style */ chartStyleProperties(chartStyle: T): SeriesPreferencesMap[T]; /** Sets properties for a specific chart style */ setChartStyleProperties(chartStyle: T, newPrefs: Partial): void; } export interface ISettingsAdapter { /** Initial settings */ initialSettings?: InitialSettingsMap; /** Set a value for a setting */ setValue(key: string, value: string): void; /** Remove a value for a setting */ removeValue(key: string): void; } /** * Drawing Groups API. */ export interface IShapesGroupControllerApi { /** * Create a group of drawings from the selection. * * @throws If selection is empty, or selection contains non-drawings, or selection contains drawings from more than one pane. * @return The ID of the created group. */ createGroupFromSelection(): ShapesGroupId; /** * Remove a group of drawings. * * @param groupId A group ID. */ removeGroup(groupId: ShapesGroupId): void; /** * Get an array of all drawing groups. * * @returns An array of group IDs. */ groups(): readonly ShapesGroupId[]; /** * Get an array of IDs for each drawing in a group. * * @param groupId A group ID. * @returns An array of drawing IDs. */ shapesInGroup(groupId: ShapesGroupId): readonly EntityId[]; /** * Remove a drawing from a group. If the drawing is the only drawing in the group then the group is also removed. * * @param groupId A group ID. * @param shapeId A drawing ID. */ excludeShapeFromGroup(groupId: ShapesGroupId, shapeId: EntityId): void; /** * Add a drawing to a group. * * @param groupId A group ID. * @param shapeId A drawing ID. */ addShapeToGroup(groupId: ShapesGroupId, shapeId: EntityId): void; /** * Get an object containing the available Z-order operations for a group. * * @param groupId A group ID. * @returns The available Z-order operations. */ availableZOrderOperations(groupId: ShapesGroupId): AvailableZOrderOperations; /** * Move the group to the top of the Z-order. * * @param groupId A group ID. */ bringToFront(groupId: ShapesGroupId): void; /** * Move the group to the bottom of the Z-order. * * @param groupId A group ID. */ sendToBack(groupId: ShapesGroupId): void; /** * Move the group one level up in the Z-order. * * @param groupId A group ID. */ bringForward(groupId: ShapesGroupId): void; /** * Move the group one level down in the Z-order. * * @param groupId A group ID. */ sendBackward(groupId: ShapesGroupId): void; /** * Move the group immediately below the target in the Z-order. * * @param groupId A group ID. * @param target A target ID. */ insertAfter(groupId: ShapesGroupId, target: ShapesGroupId | EntityId): void; /** * Move the group immediately above the target in the Z-order. * * @param groupId A group ID. * @param target A target ID. */ insertBefore(groupId: ShapesGroupId, target: ShapesGroupId | EntityId): void; /** * Show or hide all drawings in a group. * * @param groupId A group ID. * @param value A boolean flag. `true` to show, `false` to hide. */ setGroupVisibility(groupId: ShapesGroupId, value: boolean): void; /** * Get the visibility state of a group. * * @param groupId A group ID. * @returns The visibility state. */ groupVisibility(groupId: ShapesGroupId): GroupVisibilityState; /** * Lock or unlock a group. * * @param groupId A group ID. * @param value A boolean flag. `true` to lock, `false` to unlock. */ setGroupLock(groupId: ShapesGroupId, value: boolean): void; /** * Get locked state of a group. * * @param groupId A group ID. * @returns The locked state. */ groupLock(groupId: ShapesGroupId): GroupLockState; /** * Get the name of a group. * * @param groupId A group ID. * @returns The name of the group. */ getGroupName(groupId: ShapesGroupId): string; /** * Set the name of a group. Names do not need to be unique. * * @param groupId A group ID. * @param name The new name of the group. */ setGroupName(groupId: ShapesGroupId, name: string): void; /** * Check if some drawings can be grouped. * * @param shapes An array of drawing IDs. * @return `true` if the drawings can be grouped, `false` otherwise. */ canBeGroupped(shapes: readonly EntityId[]): boolean; } /** * API object for interacting with a study. * * You can retrieve this interface by using the {@link IChartWidgetApi.getStudyById} method */ export interface IStudyApi { /** * Get if user editing is enabled for the study. * * @returns `true` if editing is enabled, `false` otherwise. */ isUserEditEnabled(): boolean; /** * Set if user editing is enabled for the study. * * @param enabled `true` if editing should be enabled, `false` otherwise. */ setUserEditEnabled(enabled: boolean): void; /** * Get descriptions of the study inputs. */ getInputsInfo(): StudyInputInformation[]; /** * Get current values of the study inputs. */ getInputValues(): StudyInputValueItem[]; /** * Set the value of one or more study inputs. * * @param values Study input values to set. */ setInputValues(values: StudyInputValueItem[]): void; /** * Get descriptions of study styles. */ getStyleInfo(): StudyStyleInfo; /** * Get current values of the study styles. */ getStyleValues(): StudyStyleValues; /** * Merge the study into the pane above, if possible. */ mergeUp(): void; /** * Merge the study into the pane below, if possible. */ mergeDown(): void; /** * Unmerge the study into the pane above, if possible. */ unmergeUp(): void; /** * Unmerge the study into the pane below, if possible. */ unmergeDown(): void; /** * Change the price scale that the study is attached to. * * @param newPriceScale Price scale identifier, or the ID of another study whose price scale the study should be moved to. */ changePriceScale(newPriceScale: StudyPriceScale | EntityId): void; /** * Get if the study is visible. * * @returns `true` if visible, `false` otherwise. */ isVisible(): boolean; /** * Set the study visibility. * * @param visible `true` if the study should be visible, `false` otherwise. */ setVisible(visible: boolean): void; /** * Move the study visually in front of all other chart objects. */ bringToFront(): void; /** * Move the study visually behind of all other chart objects. */ sendToBack(): void; /** * Override one or more of the study's properties. * See [Studies Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Studies-Overrides) for a list of available overrides. * * @param overrides Property values to override. */ applyOverrides(overrides: TOverrides): void; /** * Copies the study to all charts in the layout. * Only applicable to multi-chart layouts (Trading Terminal). */ applyToEntireLayout(): void; /** * Get a subscription that can be used to subscribe a callback when the study data has loaded. * * @returns A subscription. * * Example: * ```javascript * studyApi.onDataLoaded().subscribe( * null, * () => console.log('Study data is loaded'), * true * ); * ``` */ onDataLoaded(): ISubscription<() => void>; /** * Get a subscription that can be used to subscribe a callback when the study has an error. * * @returns A subscription. * * Example: * ```javascript * studyApi.studyApi.onStudyError().subscribe( * null, * () => console.log('Study error'), * true * ); * ``` */ onStudyError(): ISubscription<() => void>; } /** * A subscription. Used to subscribe callbacks to events. */ export interface ISubscription { /** * Subscribe a callback function to this event. Subscribed callbacks are called when the event fires. * * @param obj Object used as the `this` value bound to the callback function. * @param member Function called when the event is fired. * @param singleshot `true` if the subscription should be automatically removed after the first time it is fired. * * @example * ``` * // Log 'Series data loaded!' to the console the next time the data loaded event fires and then unsubscribe automatically. * seriesApi.onDataLoaded().subscribe(null, () => { console.log('Series data loaded!'); }, true); * ``` * Subscribe to an event within a class. Manually unsubscribe when some condition is true. * ``` * class Example { * constructor(seriesApi) { * this._seriesApi = seriesApi; * this._seriesApi.onDataLoaded().subscribe(this, this._onDataLoaded); * } * * _onDataLoaded() { * // Do something in response to the event. * * if (someUnsubscribeCondition) { * this._seriesApi.onDataLoaded().unsubscribe(this, this._onDataLoaded); * } * } * } * ``` */ subscribe(obj: object | null, member: TFunc, singleshot?: boolean): void; /** * Unsubscribe a previously subscribed callback function. * It is important that the `obj` and `member` arguments are the same as the ones passed when the callback was subscribed. * * @param obj Object passed as the `this` value when the callback was subscribed. * @param member Function subscribed to the event. */ unsubscribe(obj: object | null, member: TFunc): void; /** * Unsubscribe all callbacks that were subscribed with the same `obj` value. * * @param obj `obj` value passed when the callbacks were subscribed. * @example * ``` * // Unsubscribe all three callback functions at once in the `destroy` method. * class Example { * constructor(seriesApi) { * this._seriesApi = seriesApi; * this._seriesApi.onDataLoaded().subscribe(this, this._callback1); * this._seriesApi.onDataLoaded().subscribe(this, this._callback2); * this._seriesApi.onDataLoaded().subscribe(this, this._callback3); * } * * destroy() { * this._seriesapi.onDataLoaded().unsubscribeAll(this); * } * * _callback1() { ... } * _callback2() { ... } * _callback3() { ... } * } * ``` */ unsubscribeAll(obj: object | null): void; } // tslint:disable:tv-variable-name export interface ISymbolInstrument { /** Period Base */ periodBase: string; /** Ticker ID */ tickerid: string; /** Currency Code */ currencyCode?: string; /** Period */ period: string; /** Index */ index: number; /** Time */ time: number; /** Open bar value */ open: number; /** High bar value */ high: number; /** Low bar value */ low: number; /** Close bar value */ close: number; /** Bar Volume value */ volume: number; /** Time of the update */ updatetime: number; /** Session string */ session: string; /** Script */ script: any; // tslint:disable-line:no-any /** Ticker */ ticker: string; /** Resolution */ resolution: string; /** Interval */ interval: number; /** Minimum tick amount */ minTick: number; /** Whether this is the first bar */ isFirstBar: boolean; /** Whether this is the last bar */ isLastBar: boolean; /** Whether this is a new bar */ isNewBar: boolean; /** Whether the bar is closed */ isBarClosed: boolean; /** Symbol information */ info?: LibrarySymbolInfo; } export interface ISymbolValueFormatter { /** Default formatter function used to assign the correct sign (+ or -) to a number */ format(price: number, signPositive?: boolean): string; } /** * API object for interacting with the timescale. * * You can retrieve this interface by using the {@link IChartWidgetApi.getTimeScale} method */ export interface ITimeScaleApi { /** Returns the time associated to a given coordinate (distance in pixels from the leftmost visible bar) */ coordinateToTime(x: number): number | null; /** * Users will be notified every time `barSpacing` value is changed. This typically occurs when zooming in/out on the chart. * This is to detect when the chart has been zoomed in/out */ barSpacingChanged(): ISubscription<(newBarSpacing: number) => void>; /** * Users will be notified every time `rightOffset` value is changed. * This is to detect when the chart has been scrolled left/right. */ rightOffsetChanged(): ISubscription<(rightOffset: number) => void>; /** To set a new right offset */ setRightOffset(offset: number): void; /** To set a new bar spacing */ setBarSpacing(newBarSpacing: number): void; /** Returns the current bar spacing */ barSpacing(): number; /** Returns the current right offset */ rightOffset(): number; /** Returns the current width of the chart in pixels */ width(): number; /** Object that can be used to read/set/watch the default right offset (margin) */ defaultRightOffset(): IWatchedValue; /** Object that can be used to read/set/watch the default right offset (in percent) (margin) */ defaultRightOffsetPercentage(): IWatchedValue; /** * Object that can be used to read/set/watch whether to use `defaultRightOffset` or `defaultRightOffsetPercentage` * option for the right offset (margin). * - `false`: use `defaultRightOffset` * - `true`: use `defaultRightOffsetPercentage` * * Default: `false` */ usePercentageRightOffset(): IWatchedValue; } export interface ITimezoneApi { /** Array of supported TimezoneInfo */ availableTimezones(): readonly TimezoneInfo[]; /** Returns the current TimezoneInfo */ getTimezone(): TimezoneInfo; /** Sets the current timezone */ setTimezone(timezone: TimezoneId | CustomTimezoneId, options?: UndoOptions): void; /** * To be notified when the timezone is changed * * Example: * ```javascript * timezoneApi.onTimezoneChanged().subscribe( * null, * timezone => console.log(`New timezone: ${timezone}`), * true * ); * ``` */ onTimezoneChanged(): ISubscription<(timezone: TimezoneId) => void>; } export interface IUpdatableAction extends IAction { /** * Update the options for the Action * @param {Partial} options - updated options */ update(options: Partial): void; } export interface IWatchListApi { /** * Get a default list of symbols. * @returns default list of symbols */ defaultList(): string[]; /** * Get a list of symbols. * If the `id` parameter is not provided then the current list will be returned. If there is no WatchList then `null` will be returned. * @param {string} id? - Watchlist ID * @returns list of symbols for watchlist */ getList(id?: string): string[] | null; /** * Get all watchlists. If there is no WatchList then `null` will be returned. * @returns object of all watchlists */ getAllLists(): WatchListSymbolListMap | null; /** * Make the watchlist with the specified `id` active. * @param {string} id - watchlist ID */ setActiveList(id: string): void; /** * Get the ID of the current watchlist. If there is no WatchList then `null` will be returned. * @returns id of active watchlist */ getActiveListId(): string | null; /** * **Obsolete. Use `updateList` instead.** * * Set the list of symbols for the watchlist. It will replace the entire list. * @param {string[]} symbols - symbol IDs */ setList(symbols: string[]): void; /** * Edit the list of symbols for a watchlist. * @param {string} listId - ID of the watchlist * @param {string[]} symbols - symbols to be set for the watchlist */ updateList(listId: string, symbols: string[]): void; /** * Rename the watchlist. * @param {string} listId - ID of the watchlist * @param {string} newName - new name to set for the watchlist */ renameList(listId: string, newName: string): void; /** * Create a list of symbols with `listName` name. If the `listName` parameter is not provided or there is no WatchList then `null` will be returned; * @param {string} listName? - name for the watchlist * @param {string[]} symbols? - symbol IDs for the watchlist * @returns WatchListSymbolList */ createList(listName?: string, symbols?: string[]): WatchListSymbolList | null; /** * Save a list of symbols. * @param {WatchListSymbolList} list * @returns If there is no WatchList or an equivalent list already exists then `false` will be returned, otherwise `true` will returned. */ saveList(list: WatchListSymbolList): boolean; /** * Delete a watchlist of symbols * @param {string} listId - watchlist ID */ deleteList(listId: string): void; /** * Subscription for when the symbols of the active watchlist are changed. Use the `subscribe` method of the returned {@link ISubscription} object to subscribe to the notifications. */ onListChanged(): ISubscription; /** * Subscription for when the active watchlist is changed to a different list. Use the `subscribe` method of the returned {@link ISubscription} object to subscribe to the notifications. */ onActiveListChanged(): ISubscription; /** * Subscription for when a new list is added to the watchlist widget. Use the `subscribe` method of the returned {@link ISubscription} object to subscribe to the notifications. */ onListAdded(): ISubscription; /** * Subscription for when a list is removed from the watchlist widget. Use the `subscribe` method of the returned {@link ISubscription} object to subscribe to the notifications. */ onListRemoved(): ISubscription; /** * Subscription for when a list is renamed. Use the `subscribe` method of the returned {@link ISubscription} object to subscribe to the notifications. */ onListRenamed(): ISubscription; } export interface IWatchedValue extends IWatchedValueReadonly, IObservableValue { /** * Set value for the watched value * @param {T} value - value to set * @param {boolean} forceUpdate? - force an update */ setValue(value: T, forceUpdate?: boolean): void; /** @inheritDoc */ subscribe(callback: WatchedValueCallback, options?: WatchedValueSubscribeOptions): void; /** @inheritDoc */ unsubscribe(callback?: WatchedValueCallback | null): void; } export interface IWatchedValueReadonly extends IObservableValueReadOnly { /** * Subscribe to watched value changes * @param {(value:T)=>void} callback - callback to be evoked when change occurs * @param {WatchedValueSubscribeOptions} options? - watch subscriber options */ subscribe(callback: (value: T) => void, options?: WatchedValueSubscribeOptions): void; /** * Unsubscribe to watched value changes * @param {((value:T)=>void)|null} callback? - callback to remove */ unsubscribe(callback?: ((value: T) => void) | null): void; /** * A simplified version of subscription, with promise-like interface, generally for using with boolean-valued watched values * @param {WatchedValueCallback} callback - a function to be called when the value became `true`. `once` and `callWithLast` are implicitly set to true. */ when(callback: WatchedValueCallback): void; } /** * Widget Bar API */ export interface IWidgetbarApi extends IDestroyable { /** * Show page * @param {PageName} pageName - name of page to show */ showPage(pageName: PageName): void; /** * Hide page * @param {PageName} pageName - name of page to hide */ hidePage(pageName: PageName): void; /** * Checks if page is visible * @param {PageName} pageName - page to check if visible * @returns true` when page is visible */ isPageVisible(pageName: PageName): boolean; /** * Open order panel widget */ openOrderPanel(): void; /** * Close order panel widget */ closeOrderPanel(): void; } export interface IconOptions { /** Icon number */ icon: number; } export interface InitialSettingsMap { /** Initial Setting */ [key: string]: string; } export interface InstrumentInfo { /** Quantity field step and boundaries */ qty: QuantityMetainfo; /** Value of 1 pip for the instrument in the account currency */ pipValue: number; /** Size of 1 pip (e.g., 0.0001 for EURUSD) */ pipSize: number; /** Minimal price change (e.g., 0.00001 for EURUSD). Used for price fields. */ minTick: number; /** Lot size */ lotSize?: number; /** Instrument type. `forex` enables negative pips. You can check that in the Order dialog. */ type?: SymbolType; /** Units of quantity or amount. Displayed instead of the Units label in the Quantity/Amount field. */ units?: string; /** Display name for the symbol */ brokerSymbol?: string; /** A description to be displayed in the UI dialogs. */ description: string; /** Number of decimal places of DOM asks/bids volume (optional, 0 by default). */ domVolumePrecision?: number; /** Leverage */ leverage?: string; /** * The margin requirement for the instrument. A 3% margin rate should be represented as 0.03. * @deprecated */ marginRate?: number; /** Minimal price change for limit price field of the Limit and Stop Limit order. If set it will override the `minTick` value. */ limitPriceStep?: number; /** Minimal price change for stop price field of the Stop and Stop Limit order. If set it will override the `minTick` value. */ stopPriceStep?: number; /** Array of strings with valid duration values. You can check that in the Order dialog. */ allowedDurations?: string[]; /** * Dynamic minimum price movement. * It is used if the instrument's minimum price movement changes depending on the price range. * * For example: `0.01 10 0.02 25 0.05`, where `minTick` is `0.01` for a price less than `10`, `minTick` is `0.02` for a price less than `25`, `minTick` is `0.05` for a price more and equal than `25`. */ variableMinTick?: string; /** Instrument currency that is displayed in the Order dialog */ currency?: string; /** The first currency quoted in a currency pair. Used for crypto currencies only. */ baseCurrency?: string; /** The second currency quoted in a currency pair. Used for crypto currencies only. */ quoteCurrency?: string; /** The value represented by a full point of price movement in the contract currency. This value is used to calculate the Total Value (symbol currency) of the order. */ bigPointValue?: number; /** The value represents how much price is multiplied in relation to base monetary unit. */ priceMagnifier?: number; } /** Show a custom message with the reason why the symbol cannot be traded */ export interface IsTradableResult { /** * Is the symbol tradable */ tradable: boolean; /** * Reason is displayed in the Order dialog */ reason?: string; /** Solution available to user to resolve the issue */ solutions?: TradableSolutions; /** shortReason is displayed in the legend */ shortReason?: string; } export interface KagiStylePreferences { /** Up line color */ upColor: string; /** Up down color */ downColor: string; /** Up projection line color */ upColorProjection: string; /** Down projection line color */ downColorProjection: string; } /** * An API object representing leverage info for an order. */ export interface LeverageInfo { /** * The title for any Leverage Dialogs shown by the library. */ title: string; /** * The leverage. */ leverage: number; /** * The minimum leverage value. */ min: number; /** * The maximum leverage value. */ max: number; /** * The mimimum change between leverage values. */ step: number; } /** * An API object representing an order. Used when requesting leverage information from a broker. */ export interface LeverageInfoParams { /** * The order symbol. */ symbol: string; /** * The type of the order. */ orderType: OrderType; /** * The order side. Buy or sell. */ side: Side; /** * Custom data for the broker. */ customFields?: CustomInputFieldsValues; } /** * An API object representing some messages describing the leverage value set by the user. * * Shown in any Leverage Dialogs. */ export interface LeveragePreviewResult { /** * Informative messages about the leverage value. */ infos?: string[]; /** * Warnings about the leverage value. */ warnings?: string[]; /** * Errors about the leverage value. */ errors?: string[]; } /** * An API object representing an order and leverage. Used when requesting that a broker updates a order's leverage. */ export interface LeverageSetParams extends LeverageInfoParams { /** * The requested leverage value. */ leverage: number; } /** * An API object representing a response containing the leverage value for a user. */ export interface LeverageSetResult { /** * The leverage. */ leverage: number; } export interface LibraryPineStudy { /** * Called only once during the lifetime of the study and designed to get additional info for the study. * * Example: * ``` * this.init = function(context, inputCallback) { * var symbol = '#EQUITY'; * var period = PineJS.Std.period(this._context); * context.new_sym(symbol, period); * }; * ``` * @param {IContext} ctx - An object containing symbol info along with some useful methods to load/store symbol * @param {(index:number} inputs - The inputs callback is an array of input values, placed in order of inputs in Metainfo. */ init?(ctx: IContext, inputs: (index: number) => T): void; /** * Called every time the library wants to calculate the study. Also it's called for every bar of every symbol. * Thus, if you request several additional symbols inside your indicator it will increase the count of runs. * @param {IContext} ctx - An object containing symbol info along with some useful methods to load/store symbol * @param {(index:number} inputs - The inputs callback is an array of input values, placed in order of inputs in Metainfo. */ main(ctx: IContext, inputs: (index: number) => T): TPineStudyResult | null; // Indicator defined properties // tslint:disable-next-line:no-any [key: string]: any; } export interface LibraryPineStudyConstructor { /** * Custom Study constructor */ // eslint-disable-next-line @typescript-eslint/prefer-function-type new (): LibraryPineStudy; } export interface LibrarySubsessionInfo { /** * Description of the subsession. * * @example "Regular Trading Hours" */ description: string; /** * Subsession ID. */ id: LibrarySessionId; /** * Session string. See {@link LibrarySymbolInfo.session}. */ session: string; /** * Session corrections string. See {@link LibrarySymbolInfo.corrections}. */ "session-correction"?: string; } export interface LibrarySymbolInfo { /** * Symbol Name * It's the name of the symbol. It is a string that your users will be able to see. * Also, it will be used for data requests if you are not using tickers. */ name: string; /** * The full name of the symbol (contains name and exchange) * Example: `BTCE:BTCUSD` */ full_name: string; /** * Array of base symbols * Example: for `AAPL*MSFT` it is `['NASDAQ:AAPL', 'NASDAQ:MSFT']` */ base_name?: [ string ]; /** * Unique symbol id * It's an unique identifier for this particular symbol in your symbology. * If you specify this property then its value will be used for all data requests for this symbol. ticker will be treated the same as {@link LibrarySymbolInfo.name} if not specified explicitly. */ ticker?: string; /** * The description of the symbol. * Will be displayed in the chart legend for this symbol. */ description: string; /** * Symbol Long description * * Optional long(er) description for the symbol. */ long_description?: string; /** * Type of the instrument. * Possible values: {@link SymbolType} */ type: string; /** * Trading hours for this symbol. See the [Trading Sessions article](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessions) to learn more details. * @example "1700-0200" */ session: string; /** * The session value to display in the UI. If not specified, then `session` is used. */ session_display?: string; /** @deprecated Use session_holidays instead */ holidays?: string; /** * List of holidays for this symbol. These dates are not displayed on the chart. * It's a string in the following format: `YYYYMMDD[,YYYYMMDD]`. * @example "20181105,20181107,20181112" */ session_holidays?: string; /** * List of corrections for this symbol. Corrections are days with specific trading sessions. They can be applied to holidays as well. * * It's a string in the following format: `SESSION:YYYYMMDD[,YYYYMMDD][;SESSION:YYYYMMDD[,YYYYMMDD]]` * Where SESSION has the same format as [Trading Sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessions). * * @example "1900F4-2350F4,1000-1845:20181113;1000-1400:20181114" */ corrections?: string; /** * Traded exchange (current (proxy) exchange). * The name will be displayed in the chart legend for this symbol. * * @example "NYSE" */ exchange: string; /** * short name of the exchange where this symbol is traded (real listed exchange). * The name will be displayed in the chart legend for this symbol. * * @example "NYSE" */ listed_exchange: string; /** * Timezone of the exchange for this symbol. We expect to get the name of the time zone in `olsondb` format. * See [Timezones](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#timezone) for a full list of supported timezones */ timezone: Timezone; /** * Format of displaying labels on the price scale: * * `price` - formats decimal or fractional numbers based on `minmov`, `pricescale`, `minmove2`, `fractional` and `variableMinTick` values. See [Price Formatting](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#price-format) for more details * `volume` - formats decimal numbers in thousands, millions, billions or trillions */ format: SeriesFormat; /** * Code (Tick) * @example 8/16/.../256 (1/8/100 1/16/100 ... 1/256/100) or 1/10/.../10000000 (1 0.1 ... 0.0000001) */ pricescale: number; /** * The number of units that make up one tick. * @example For example, U.S. equities are quotes in decimals, and tick in decimals, and can go up +/- .01. So the tick increment is 1. But the e-mini S&P futures contract, though quoted in decimals, goes up in .25 increments, so the tick increment is 25. (see also Tick Size) */ minmov: number; /** * For common prices this can be skipped. * * Fractional prices are displayed 2 different forms: 1) `xx'yy` (for example, `133'21`) 2) `xx'yy'zz` (for example, `133'21'5`). * * - `xx` is an integer part. * - `minmov/pricescale` is a Fraction. * - `minmove2` is used in form 2. * - `fractional` is `true`. * - `variableMinTick` is skipped. * * Example: * * If `minmov = 1`, `pricescale = 128` and `minmove2 = 4`: * * - `119'16'0` represents `119 + 16/32` * - `119'16'2` represents `119 + 16.25/32` * - `119'16'5` represents `119 + 16.5/32` * - `119'16'7` represents `119 + 16.75/32` * * More examples: * * - `ZBM2014 (T-Bond)` with `1/32`: `minmov = 1`, `pricescale = 32`, `minmove2 = 0` * - `ZCM2014 (Corn)` with `2/8`: `minmov = 2`, `pricescale = 8`, `minmove2 = 0` * - `ZFM2014 (5 year t-note)` with `1/4 of 1/32`: `minmov = 1`, `pricescale = 128`, `minmove2 = 4` */ fractional?: boolean; /** * For common prices this can be skipped. * @example Quarters of 1/32: pricescale=128, minmovement=1, minmovement2=4 */ minmove2?: number; /** * Boolean value showing whether the symbol includes intraday (minutes) historical data. * * If it's `false` then all buttons for intraday resolutions will be disabled for this particular symbol. * If it is set to `true`, all intradays resolutions that are supplied directly by the datafeed must be provided in `intraday_multipliers` array. * * **WARNING** Any daily, weekly or monthly resolutions cannot be inferred from intraday resolutions! * * `false` if DWM only * @default false */ has_intraday?: boolean; /** * An array of resolutions which should be enabled in resolutions picker for this symbol. * * Each item of an array is expected to be a string. Format is described in another article. * * If one changes the symbol and new symbol does not support the selected resolution then resolution will be switched to the first available one in the list. * * **Resolution availability logic (pseudocode):** * ``` * resolutionAvailable = * resolution.isIntraday * ? symbol.has_intraday && symbol.supported_resolutions(resolution) * : symbol.supported_resolutions(resolution); * ``` * * In case of absence of `supported_resolutions` in a symbol info all DWM resolutions will be available. Intraday resolutions will be available if `has_intraday` is `true`. * Supported resolutions affect available timeframes too. The timeframe will not be available if it requires the resolution that is not supported. */ supported_resolutions: ResolutionString[]; /** * Array of resolutions (in minutes) supported directly by the data feed. Each such resolution may be passed to, and should be implemented by, `getBars`. The default of [] means that the data feed supports aggregating by any number of minutes. * * If the data feed only supports certain minute resolutions but not the requested resolution, `getBars` will be called (repeatedly if needed) with a higher resolution as a parameter, in order to build the requested resolution. * * For example, if the data feed only supports minute resolution, set `intraday_multipliers` to `['1']`. * * When the user wants to see 5-minute data, `getBars` will be called with the resolution set to 1 until the library builds all the 5-minute resolution by itself. * @example (for ex.: "1,5,60") - only these resolutions will be requested, all others will be built using them if possible * @default [] */ intraday_multipliers?: string[]; /** * Boolean value showing whether the symbol includes seconds in the historical data. * * If it's `false` then all buttons for resolutions that include seconds will be disabled for this particular symbol. * * If it is set to `true`, all resolutions that are supplied directly by the data feed must be provided in `seconds_multipliers` array. * @default false */ has_seconds?: boolean; /** * Boolean value showing whether the symbol includes ticks in the historical data. * * If it's `false` then all buttons for resolutions that include ticks will be disabled for this particular symbol. * @default false */ has_ticks?: boolean; /** * It is an array containing resolutions that include seconds (excluding postfix) that the data feed provides. * E.g., if the data feed supports resolutions such as `["1S", "5S", "15S"]`, but has 1-second bars for some symbols then you should set `seconds_multipliers` of this symbol to `[1]`. * This will make Charting Library build 5S and 15S resolutions by itself. */ seconds_multipliers?: string[]; /** * The boolean value showing whether data feed has its own daily resolution bars or not. * * If `has_daily` = `false` then Charting Library will build the respective resolutions using 1-minute bars by itself. * If not, then it will request those bars from the data feed only if specified resolution belongs to `daily_multipliers`, otherwise an error will be thrown. * @default true */ has_daily?: boolean; /** * Array (of strings) containing the [resolutions](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#days) (in days - without the suffix) supported by the data feed. {@link ResolutionString} * * For example it could be something like * * ```javascript * daily_multipliers = ['1', '3', '4', '6', '7']; * ``` * @default ['1'] */ daily_multipliers?: string[]; /** * The boolean value showing whether data feed has its own weekly and monthly resolution bars or not. * * If `has_weekly_and_monthly` = `false` then Charting Library will build the respective resolutions using daily bars by itself. * If not, then it will request those bars from the data feed using either the `weekly_multipliers` or `monthly_multipliers` if specified. * If resolution is not within either list an error will be raised. * @default false */ has_weekly_and_monthly?: boolean; /** * Array (of strings) containing the [resolutions](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#weeks) (in weeks - without the suffix) supported by the data feed. {@link ResolutionString} * * For example it could be something like * * ```javascript * weekly_multipliers = ['1', '5', '10']; * ``` * @default ['1'] */ weekly_multipliers?: string[]; /** * Array (of strings) containing the [resolutions](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#months) (in months - without the suffix) supported by the data feed. {@link ResolutionString} * * For example it could be something like * * ```javascript * monthly_multipliers = ['1', '3', '4', '12']; * ``` * @default ['1'] */ monthly_multipliers?: string[]; /** * The boolean value showing whether the library should generate empty bars in the session when there is no data from the data feed for this particular time. * * I.e., if your session is `0900-1600` and your data has gaps between `11:00` and `12:00` and your `has_empty_bars` is `true`, then the Library will fill the gaps with bars for this time. * * Flag `has_empty_bars` = `true` cannot be used if featureset `disable_resolution_rebuild` is enabled. * @default false */ has_empty_bars?: boolean; /** * @deprecated * use visible_plots_set instead */ has_no_volume?: boolean; /** * Represents what values are supported by the symbol. Possible values: * * - `ohlcv` - the symbol supports open, high, low, close and has volume * - `ohlc` - the symbol supports open, high, low, close, but doesn't have volume * - `c` - the symbol supports only close, it's displayed on the chart using line-based styles only * @default 'ohlcv' */ visible_plots_set?: VisiblePlotsSet; /** * Integer showing typical volume value decimal places for a particular symbol. * 0 means volume is always an integer. * 1 means that there might be 1 numeric character after the comma. * @default '0' */ volume_precision?: number; /** * The status code of a series with this symbol. The status is shown in the upper right corner of a chart. */ data_status?: "streaming" | "endofday" | "pulsed" | "delayed_streaming"; /** * Boolean showing whether this symbol is expired futures contract or not. * @default false */ expired?: boolean; /** * Unix timestamp of the expiration date. One must set this value when `expired` = `true`. * Charting Library will request data for this symbol starting from that time point. */ expiration_date?: number; /** Sector for stocks to be displayed in the Symbol Info. */ sector?: string; /** Industry for stocks to be displayed in the Symbol Info. */ industry?: string; /** * The currency in which the instrument is traded or some other currency if currency conversion is enabled. * It is displayed in the Symbol Info dialog and on the price axes. */ currency_code?: string; /** The currency in which the instrument is traded. */ original_currency_code?: string; /** * A unique identifier of a unit in which the instrument is traded or some other identifier if unit conversion is enabled. * It is displayed on the price axes. */ unit_id?: string; /** * A unique identifier of a unit in which the instrument is traded. */ original_unit_id?: string; /** * Allowed unit conversion group names. */ unit_conversion_types?: string[]; /** * Subsession ID. Must match the `id` property of one of the subsessions. */ subsession_id?: string; /** * Subsessions definitions. */ subsessions?: LibrarySubsessionInfo[]; /** * Optional field name describing what the bar values of this symbol represent. * * For example 'Spot Price', 'Ask', 'Bid', etc. * * @example 'Spot Price' */ price_source_id?: string; } export interface LineBreakStylePreferences { /** Up bar color */ upColor: string; /** Down bar color */ downColor: string; /** Up bar border color */ borderUpColor: string; /** Down bar border color */ borderDownColor: string; /** Projection up bar color */ upColorProjection: string; /** Projection down bar color */ downColorProjection: string; /** Projection up bar border color */ borderUpColorProjection: string; /** Projection down bar border color */ borderDownColorProjection: string; } export interface LineStylePreferences { /** Line color */ color: string; /** Line Style {@link LineStyle} */ linestyle: number; /** Line width */ linewidth: number; /** * Line style type * 0 - Points, 1 - Stepped, 2 - Normal */ styleType: number; } /** * Color styling options for the loading screen (spinner) */ export interface LoadingScreenOptions { /** Colour of the spinner on the loading screen */ foregroundColor?: string; /** Background color for the loading screen */ backgroundColor?: string; } export interface MappedObject { [key: string]: TValue | undefined; } export interface Mark { /** ID of the mark */ id: string | number; /** * Time for the mark. * Amount of **milliseconds** since Unix epoch start in **UTC** timezone. */ time: number; /** Color for the mark */ color: MarkConstColors | MarkCustomColor; /** Text content for the mark */ text: string; /** Label for the mark */ label: string; /** Text color for the mark */ labelFontColor: string; /** Minimum size for the mark */ minSize: number; /** Border Width */ borderWidth?: number; /** Border Width when hovering over bar mark */ hoveredBorderWidth?: number; /** * Optional URL for an image to be displayed within the timescale mark. * * The image should ideally be square in dimension. You can use any image type which * the browser supports natively. * * Examples: * - `https://s3-symbol-logo.tradingview.com/crypto/XTVCBTC.svg` * - `/images/myImage.png` * - `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3...` * - `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4...` */ imageUrl?: string; /** * Continue to show text label even when an image has * been loaded for the timescale mark. * * Defaults to `false` if undefined. */ showLabelWhenImageLoaded?: boolean; } export interface MarkCustomColor { /** @deprecated Foreground color */ color?: string; /** Border color */ border: string; /** Background color */ background: string; } /** Separator for a dropdown or context menu */ export interface MenuSeparator extends ActionDescription { /** Is a menu separator */ separator: boolean; } export interface MouseEventParams { /** X (horizontal) coordinate (in pixels) at which the mouse event occurred, relative to the left edge of the applications viewport. */ clientX: number; /** Y (vertical) coordinate (in pixels) at which the mouse event occurred, relative to the left edge of the applications viewport. */ clientY: number; /** X (horizontal) coordinate (in pixels) at which the mouse event occurred, relative to the left edge of the entire document. */ pageX: number; /** Y (vertical) coordinate (in pixels) at which the mouse event occurred, relative to the left edge of the entire document. */ pageY: number; /** X (horizontal) coordinate (in pixels) at which the mouse event occurred, in global screen coordinates. */ screenX: number; /** Y (vertical) coordinate (in pixels) at which the mouse event occurred, in global screen coordinates. */ screenY: number; } export interface NegativeBaseInputFieldValidatorResult extends BaseInputFieldValidatorResult { /** @inheritDoc */ valid: false; /** Reason why base input value is invalid */ errorMessage: string; } export interface NewsItem { /** News item title */ title: string; /** Source of the news item */ source: string; /** Published date */ published: number; /** Link to the news item */ link?: string; /** Short description */ shortDescription?: string; /** Full description */ fullDescription?: string; } /** * Formatting options for numbers */ export interface NumericFormattingParams { /** * String that would represent the decimal part of a number * @example 123.4 or 123,4 or 123'4 */ decimal_sign: string; } export interface OrderDialogOptions extends TradingDialogOptions { /** * Using this flag you can change `Trade Value` to `Total` in the Order Info section of the Order dialog. */ showTotal?: boolean; } export interface OrderDuration { /** * type is OrderDurationMetaInfo.value */ type: string; /** Order duration time */ datetime?: number; } /** * Expiration options for orders */ export interface OrderDurationMetaInfo { /** If it is set to `true`, then the Display date control in the Order Dialog for this duration type will be displayed. */ hasDatePicker?: boolean; /** If it is set to `true`, then the Display time control in the Order Dialog for this duration type will be displayed. */ hasTimePicker?: boolean; /** * Default duration. * Only one duration object in the durations array can have a `true` value for this field. * The default duration will be used when the user places orders in the silent mode and it will be the selected one when the user opens the Order Dialog for the first time. */ default?: boolean; /** Localized title of the duration. The title will be displayed in the Duration control of the Order Dialog. */ name: string; /** Duration identifier */ value: string; /** A list of order types for which this duration type will be displayed in the Duration control of the Order Dialog. Default value is `[OrderType.Limit, OrderType.Stop, OrderType.StopLimit]`. */ supportedOrderTypes?: OrderType[]; } export interface OrderOrPositionMessage { /** Type of message about the order or position */ type: OrderOrPositionMessageType; /** Message content */ text: string; } /** Describes the result of the order preview. */ export interface OrderPreviewResult { /** Order preview section */ sections: OrderPreviewSection[]; /** Confirmation ID. A unique identifier that should be passed to `placeOrder` method */ confirmId?: string; /** Warning messages */ warnings?: string[]; /** Error messages */ errors?: string[]; } /** * Describes a single order preview section. * Order preview can have multiple sections that are divided by separators and may have titles. */ export interface OrderPreviewSection { /** Order preview items. Each item is a row of the section table. */ rows: OrderPreviewSectionRow[]; /** Optional title of the section. */ header?: string; } /** * Describes a single row of a section table of the order preview. */ export interface OrderPreviewSectionRow { /** Description of the item. */ title: string; /** Formatted value of the item. */ value: string; } export interface OrderRule { /** Order ID */ id: string; /** Severity of Order Rule */ severity: "warning" | "error"; } /** * Input value of the order ticket * This info is not sufficient to place an order */ export interface OrderTemplate { /** Symbol identifier */ symbol: string; /** Order Type */ type?: OrderType; /** order / execution side */ side?: Side; /** Order quantity */ qty?: number; /** Type of Stop Order */ stopType?: StopType; /** Order stop price */ stopPrice?: number; /** Order limit price */ limitPrice?: number; /** Order Take Profit (Brackets) */ takeProfit?: number; /** Order Stop loss (Brackets) */ stopLoss?: number; /** Order Trailing stop (Brackets) */ trailingStopPips?: number; /** Duration or expiration of an order */ duration?: OrderDuration; /** Custom input fields */ customFields?: CustomInputFieldsValues; } export interface Overrides { [key: string]: string | number | boolean; } /** * Parameters passed to getBars */ export interface PeriodParams { /** * Unix timestamp (leftmost requested bar) */ from: number; /** * Unix timestamp (rightmost requested bar - not inclusive) */ to: number; /** * The exact amount of bars to load, should be considered a higher priority than `from` if your datafeed supports it */ countBack: number; /** * Used to identify if it's the first call of getBars */ firstDataRequest: boolean; } export interface PineJS { Std: PineJSStd; } export interface PineJSStd { eps(): number; high(context: IContext): number; low(context: IContext): number; open(context: IContext): number; close(context: IContext): number; ohlc4(context: IContext): number; volume(context: IContext): number; time(context: IContext): number; time(context: IContext, period: string, spec: unknown): number; hl2(context: IContext): number; hlc3(context: IContext): number; period(context: IContext): string; tickerid(context: IContext): string; year(context: IContext): number; month(context: IContext): number; weakofyear(context: IContext): number; dayofmonth(context: IContext): number; dayofweek(context: IContext): number; hour(context: IContext): number; minute(context: IContext): number; second(context: IContext): number; greaterOrEqual(n1: number, n2: number, eps?: number): boolean; lessOrEqual(n1: number, n2: number, eps?: number): boolean; equal(n1: number, n2: number, eps?: number): boolean; greater(n1: number, n2: number, eps?: number): boolean; less(n1: number, n2: number, eps?: number): boolean; compare(n1: number, n2: number, eps?: number): -1 | 0 | 1; ge(n1: number, n2: number): boolean; le(n1: number, n2: number): boolean; eq(n1: number, n2: number): boolean; neq(n1: number, n2: number): boolean; gt(n1: number, n2: number): boolean; lt(n1: number, n2: number): boolean; iff(condition: boolean, thenValue: T, elseValue: V): T | V; tr(handleNan: boolean, context: IContext): number; atr(length: number, context: IContext): number; isdwm(context: IContext): boolean; isintraday(context: IContext): boolean; isdaily(context: IContext): boolean; isweekly(context: IContext): boolean; ismonthly(context: IContext): boolean; selectSessionBreaks(context: IContext, times: number[]): number[]; createNewSessionCheck(context: IContext): (time: number) => boolean; error(message: string): never; zigzag(deviation: number, depth: number, context: IContext): number[]; zigzagbars(deviation: number, depth: number, context: IContext): number[]; updatetime(context: IContext): string; percentrank(source: IPineSeries, length: number): number; rising(series: IPineSeries, length: number): boolean; falling(series: IPineSeries, length: number): boolean; rsi(upper: number, lower: number): number; sum(source: IPineSeries, length: number, context: IContext): number; sma(source: IPineSeries, length: number, context: IContext): IPineSeries; rma(source: IPineSeries, length: number, context: IContext): IPineSeries; ema(source: IPineSeries, length: number, context: IContext): IPineSeries; wma(source: IPineSeries, length: number, context: IContext): IPineSeries; vwma(source: IPineSeries, length: number, context: IContext): IPineSeries; swma(source: IPineSeries, length: number, context: IContext): IPineSeries; fixnan(current: IPineSeries, context: IContext): IPineSeries; lowestbars(source: IPineSeries, length: number, context: IContext): number; lowest(source: IPineSeries, length: number, context: IContext): number; highestbars(source: IPineSeries, length: number, context: IContext): number; highest(source: IPineSeries, length: number, context: IContext): number; cum(x: IPineSeries, context: IContext): number; accdist(context: IContext): number; correlation(sourceA: IPineSeries, sourceB: IPineSeries, length: number, context: IContext): number; stoch(source: IPineSeries, high: IPineSeries, low: IPineSeries, length: number, context: IContext): number; tsi(source: IPineSeries, shortLength: number, longLength: number, context: IContext): number; cross(x: IPineSeries, y: IPineSeries, context: IContext): boolean; linreg(source: IPineSeries, length: number, offset: number): IPineSeries; sar(start: IPineSeries, inc: number, max: number, context: IContext): IPineSeries; alma(series: IPineSeries, length: number, offset: number, sigma: number): IPineSeries; change(source: IPineSeries): IPineSeries; roc(source: IPineSeries, length: number): IPineSeries; dev(source: IPineSeries, length: number, context: IContext): IPineSeries; stdev(source: IPineSeries, length: number, context: IContext): IPineSeries; variance(source: IPineSeries, length: number, context: IContext): IPineSeries; add_days_considering_dst(timezone: string, utcTime: Date, daysCount: number): Date; dmi(diLength: number, adxSmoothingLength: number, context: IContext): [ number, number, number, number, number ]; na(n: number): boolean; nz(x: number, y: number): number; and(expr1: boolean, expr2: boolean): boolean; or(expr1: boolean, expr2: boolean): boolean; not(expr1: boolean): boolean; max(...values: T[]): T; min(...values: T[]): T; pow(base: number, exponent: number): number; abs(x: number): number; log(x: number): number; log10(x: number): number; sqrt(x: number): number; sign(x: number): number; exp(x: number): number; sin(x: number): number; cos(x: number): number; tan(x: number): number; asin(x: number): number; acos(x: number): number; atan(x: number): number; floor(x: number): number; ceil(x: number): number; round(x: number): number; avg(...values: T[]): T; n(context: IContext): number; [key: string]: (...params: any[]) => any; } export interface PineStudyResultComposite { /** Type is composite */ type: "composite"; /** Composite data */ data: TPineStudyResultSimple[]; } export interface PipValues { /** value of 1 pip if you buy */ buyPipValue: number; /** value of 1 pip if you sell */ sellPipValue: number; } export interface PlaceOrderResult { /** Order id */ orderId?: string; } export interface PlacedOrder extends PlacedOrderBase, CustomFields { } /** * Info about a placed order */ export interface PlacedOrderBase { /** Order ID */ id: string; /** Symbol name */ symbol: string; /** Order type */ type: OrderType; /** Order side (buy or sell) */ side: Side; /** Order quantity (double) */ qty: number; /** Order status */ status: OrderStatus; /** Stop loss price (double). Available when Brackets are enabled */ stopLoss?: number; /** Trailing stop Pips value (double). Available when Brackets are enabled */ trailingStopPips?: number; /** Stop Loss type. It should be set to 1 (StopType.TrailingStop) for trailing stop orders. */ stopType?: StopType; /** Take profit price (double). Available when Brackets are enabled */ takeProfit?: number; /** Order duration */ duration?: OrderDuration; /** * An object that contains the results of broker specific user inputs (for example a digital signature). * There are two possible kinds of custom fields: an input field with a checkbox and a custom combobox. */ customFields?: CustomInputFieldsValues; /** Filled order quantity (double) */ filledQty?: number; /** Average fulfilled price for the order (double) */ avgPrice?: number; /** Last update time (unix timestamp in milliseconds) */ updateTime?: number; /** Price for the limit order (double) */ limitPrice?: number; /** Price for the stop order (double) */ stopPrice?: number; /** Message describing the state of the order */ message?: OrderOrPositionMessage; } export interface PlusClickParams extends MouseEventParams { /** Symbol identifier */ symbol: string | null; /** Price */ price: number; } export interface PnFStylePreferences { /** Up mark color */ upColor: string; /** Down mark color */ downColor: string; /** Up projection mark color */ upColorProjection: string; /** Down projection mark color */ downColorProjection: string; } export interface PolygonPreferences { /** Transparency of the Polygon. Value between 0 and 100, where `100` -> fully transparent */ transparency: number; /** Color of the Polygon */ color: string; } /** * Polygon Preferences */ export interface PolygonPreferences { transparency: number; color: string; } export interface Position extends PositionBase, CustomFields { } /** * Describes a single position. */ export interface PositionBase { /** Position ID. Usually id should be equal to brokerSymbol */ id: string; /** Symbol name */ symbol: string; /** Position Quantity (positive number) */ qty: number; /** Short position quantity */ shortQty?: number; /** Long position quantity */ longQty?: number; /** Position Side */ side: Side; /** Average price */ avgPrice: number; /** Message describing the state of the position */ message?: OrderOrPositionMessage; } export interface PositionDialogOptions extends TradingDialogOptions { } /** * Anchored (fixed) drawing point position as a percentage from the top left of a chart. * For example `{ x: 0.5, y: 0.5 }` for the centre of the chart. */ export interface PositionPercents { /** * Position as a percentage from the left edge of the chart. */ x: number; /** * Position as a percentage from the top edge of the chart. */ y: number; } export interface PositiveBaseInputFieldValidatorResult extends BaseInputFieldValidatorResult { /** @inheritDoc */ valid: true; } /** * Output value of the order ticket and input value of the broker's place order command * This info is sufficient to place an order */ export interface PreOrder extends OrderTemplate { /** @inheritDoc */ symbol: string; /** @inheritDoc */ type: OrderType; /** @inheritDoc */ side: Side; /** @inheritDoc */ qty: number; /** Current Quotes */ currentQuotes?: AskBid; /** * It is set to `true`, if the order closes a position. */ isClose?: boolean; } /** * Position defined by a price and time. */ export interface PricedPoint extends TimePoint { /** Price */ price: number; } /** * Quantity field step and boundaries */ export interface QuantityMetainfo { /** Minimum quantity */ min: number; /** Maximum quantity */ max: number; /** Quantity step size */ step: number; /** Quantity step size for scrolling */ uiStep?: number; /** Default quantity value */ default?: number; } export interface QuoteDataResponse { /** Status code for symbol. Expected values: `ok` | `error` */ s: "ok" | "error"; /** Symbol name. This value must be **exactly the same** as in the request */ n: string; /** Quote Values */ v: unknown; } /** Quote Data Error Response */ export interface QuoteErrorData extends QuoteDataResponse { /** @inheritDoc */ s: "error"; /** @inheritDoc */ v: object; } /** Quote Data Ok Response */ export interface QuoteOkData extends QuoteDataResponse { /** @inheritDoc */ s: "ok"; /** @inheritDoc */ v: DatafeedQuoteValues; } export interface RawStudyMetaInfo extends RawStudyMetaInfoBase { readonly id: RawStudyMetaInfoId; } export interface RawStudyMetaInfoBase { readonly description: string; readonly shortDescription: string; readonly name?: string; readonly _metainfoVersion?: number; readonly precision?: number | string; readonly format: StudyPlotValueFormat; readonly is_price_study?: boolean; readonly isCustomIndicator?: boolean; readonly linkedToSeries?: boolean; readonly priceScale?: StudyTargetPriceScale; readonly is_hidden_study?: boolean; readonly defaults: Readonly>; readonly bands?: readonly Readonly[]; readonly filledAreas?: readonly Readonly[]; readonly inputs?: StudyInputInfoList; readonly symbolSource?: SymbolSource; readonly palettes?: MappedObject>; readonly plots?: readonly Readonly[]; readonly styles?: MappedObject>; readonly ohlcPlots?: MappedObject>; readonly financialPeriod?: FinancialPeriod; readonly groupingKey?: string; } export interface RenkoStylePreferences { /** Up bar color */ upColor: string; /** Down bar color */ downColor: string; /** Up bar border color */ borderUpColor: string; /** Down bar border color */ borderDownColor: string; /** Projection up bar color */ upColorProjection: string; /** Projection down bar color */ downColorProjection: string; /** Projection up bar border color */ borderUpColorProjection: string; /** Projection down bar border color */ borderDownColorProjection: string; /** Up bar wick color */ wickUpColor: string; /** Down bar wick color */ wickDownColor: string; } export interface RestBrokerConnectionInfo { /** URL endpoint */ url: string; /** Access token for the REST API */ access_token: string; } export interface RssNewsFeedInfo { /** * URL for the RSS feed. * Can contain tags in curly brackets that will be replaced by the terminal: `{SYMBOL}`, `{TYPE}`, `{EXCHANGE}`. */ url: string; /** Name of the feed to be displayed underneath the news */ name: string; } export interface RssNewsFeedParams { /** Default news feed */ default: RssNewsFeedItem; /** Additional news feeds */ [symbolType: string]: RssNewsFeedItem; } /** * Options: Save Chart to Server */ export interface SaveChartToServerOptions { /** Name of chart */ chartName?: string; /** Default chart name */ defaultChartName?: string; } export interface SaveLoadChartRecord { /** Unique id for chart */ id: string; /** Name of chart */ name: string; /** URL of chart image */ image_url: string; /** Modified ISO number for chart */ modified_iso: number; /** Short symbol name */ short_symbol: string; /** Chart interval */ interval: ResolutionString; } export interface SavedStateMetaInfo { /** Unique ID */ uid: number; /** Name of chart */ name: string; /** Chart description */ description: string; } /** * Symbol search result item * * @example * ``` * { * description: 'Apple Inc.', * exchange: 'NasdaqNM', * full_name: 'NasdaqNM:AAPL', * symbol: 'AAPL', * ticker: 'AAPL', * type: 'stock', * } * ``` */ export interface SearchSymbolResultItem { /** Short symbol name */ symbol: string; /** Full symbol name */ full_name: string; /** Description */ description: string; /** Exchange name */ exchange: string; /** Symbol ticker name. Should be an unique id */ ticker?: string; /** * Type of symbol * * 'stock' | 'futures' | 'forex' | 'index' */ type: string; } /** * Description of a series field. * This is used when `includeSeries: true` is defined in `exportData`. */ export interface SeriesFieldDescriptor { /** Type is a `value` */ type: "value"; /** Source type is a `series` */ sourceType: "series"; /** The name of the plot (open, high, low, close) */ plotTitle: string; /** Title of the series */ sourceTitle: string; } /** * Style preferences map for the chart types */ export interface SeriesPreferencesMap { /** Bar Style Preferences */ [ChartStyle.Bar]: BarStylePreferences; /** Candle Style Preferences */ [ChartStyle.Candle]: CandleStylePreferences; /** Line Style Preferences */ [ChartStyle.Line]: LineStylePreferences; /** Area Style Preferences */ [ChartStyle.Area]: AreaStylePreferences; /** Renko Style Preferences */ [ChartStyle.Renko]: RenkoStylePreferences; /** Kagi Style Preferences */ [ChartStyle.Kagi]: KagiStylePreferences; /** Point and Figure Style Preferences */ [ChartStyle.PnF]: PnFStylePreferences; /** Line Break Style Preferences */ [ChartStyle.LineBreak]: LineBreakStylePreferences; /** Heikin Ashi Style Preferences */ [ChartStyle.HeikinAshi]: HeikinAshiStylePreferences; /** Hollow Candle Style Preferences */ [ChartStyle.HollowCandle]: HollowCandleStylePreferences; /** Baseline Style Preferences */ [ChartStyle.Baseline]: BaselineStylePreferences; /** High-Low Style Preferences */ [ChartStyle.HiLo]: HiLoStylePreferences; /** Columns Style Preferences */ [ChartStyle.Column]: ColumnStylePreferences; } /** * Options for setting the visible range. * * Setting `applyDefaultRightMargin` or `percentRightMargin` will result in the `to` value * of the range specified being ignored and the timestamp of the latest bar on the chart * being used instead. */ export interface SetVisibleRangeOptions { /** * Apply the default right offset (margin) when setting the range. */ applyDefaultRightMargin?: boolean; /** * Apply a percentage right offset (margin) when setting the range. */ percentRightMargin?: number; } export interface SingleBrokerMetaInfo { /** * Broker Configuration Flags */ configFlags: BrokerConfigFlags; /** * Optional field. You can use it if you have custom fields in orders or positions that should be taken into account when showing notifications. * * @example * if you have field `additionalType` in orders and you want the chart to show a notification when it is changed, you should set: * ```javascript * customNotificationFields: ['additionalType'] * ``` */ customNotificationFields?: string[]; /** * List of expiration options of orders. It is optional. Do not set it if you don't want the durations to be displayed in the Order Dialog. * * The objects have the following keys: `{ name, value, hasDatePicker?, hasTimePicker?, default?, supportedOrderTypes? }`. */ durations?: OrderDurationMetaInfo[]; /** Dialog options for Positions (order type) */ positionDialogOptions?: PositionDialogOptions; /** * Order Rules */ orderRules?: OrderRule[]; /** * This optional field can be used to replace the standard Order dialogs and the Add Protection dialogs with your own. * Values of the following two fields are functions that are called by the Trading Terminal to show the dialogs. Each function shows a dialog and returns a `Promise` object that should be resolved when the operation is finished or cancelled. * * **NOTE:** The returned `Promise` object should be resolved with either `true` or `false` value. * * @example * ```ts * customUI: { * showOrderDialog?: (order: Order, focus?: OrderTicketFocusControl) => Promise; * showPositionDialog?: (position: Position | Trade, brackets: Brackets, focus?: OrderTicketFocusControl) => Promise; * showCancelOrderDialog?: (order: Order) => Promise; * showClosePositionDialog?: (position: Position) => Promise; * } * ``` */ customUI?: BrokerCustomUI; } export interface SortingParameters { /** `property` of the data object that will be used for sorting */ property: string; /** Ascending sorting order (default `true`) - If it is `false`, then initial sorting will be in descending order */ asc?: boolean; } export interface StandardFormattersDependenciesMapping { [StandardFormatterName.Default]: string[]; [StandardFormatterName.Symbol]: [ brokerSymbolProperty: string, symbolProperty: string ]; [StandardFormatterName.Side]: [ sideProperty: string ]; [StandardFormatterName.PositionSide]: [ sideProperty: string ]; [StandardFormatterName.Text]: string[]; [StandardFormatterName.Type]: [ orderTypeProperty: string, parentIdProperty: string, stopTypeProperty: string ]; [StandardFormatterName.FormatPrice]: [ priceProperty: string ]; [StandardFormatterName.FormatPriceForexSup]: [ priceProperty: string ]; [StandardFormatterName.Status]: [ statusProperty: string ]; [StandardFormatterName.Date]: [ dateProperty: string ]; [StandardFormatterName.LocalDate]: [ dateProperty: string ]; [StandardFormatterName.DateOrDateTime]: [ dateProperty: string ]; [StandardFormatterName.LocalDateOrDateTime]: [ dateProperty: string ]; [StandardFormatterName.Fixed]: [ valueProperty: string ]; [StandardFormatterName.VariablePrecision]: [ valueProperty: string ]; [StandardFormatterName.Pips]: [ pipsProperty: string ]; [StandardFormatterName.IntegerSeparated]: [ valueProperty: string ]; [StandardFormatterName.FormatQuantity]: [ qtyProperty: string ]; [StandardFormatterName.Profit]: [ profitProperty: string ]; [StandardFormatterName.ProfitInInstrumentCurrency]: [ profitProperty: string, currencyProperty: string ]; [StandardFormatterName.Percentage]: [ valueProperty: string ]; [StandardFormatterName.MarginPercent]: [ valueProperty: string ]; [StandardFormatterName.Empty]: [ ]; } /** * Position defined by an OHLC price on a bar at a specified time. */ export interface StickedPoint extends TimePoint { /** Candle stick value to 'stick' on */ channel: "open" | "high" | "low" | "close"; } /** * A description of a study arrows plot. */ export interface StudyArrowsPlotInfo extends StudyPlotBaseInfo { /** @inheritDoc */ readonly type: StudyPlotType.Arrows; } /** * Study arrow plot style preferences. */ export interface StudyArrowsPlotPreferences extends StudyPlotBasePreferences { /** * Up arrow color. */ colorup: string; /** * Down arrow color. */ colordown: string; /** * Minimum arrow height. */ minHeight: number; /** * Maximum arrow height. */ maxHeight: number; } /** * A description of a study band. */ export interface StudyBandInfo { /** * Band ID. Used in {@link StudyFilledAreaInfo.objAId} and {@link StudyFilledAreaInfo.objBId}. * * @see StudyFilledAreaInfo */ readonly id?: string; /** * Band name. */ readonly name: string; /** * Band style inputs visibility flag. Used to hide the band from the style tab of study properties dialogs. */ readonly isHidden?: boolean; /** * Band z-order. */ readonly zorder?: number; } /** * Study band style preferences. */ export interface StudyBandPreferences extends StudyBandStyle, StudyBandInfo { } /** * Study band style preferences. */ export interface StudyBandStyle { /** * Color. * * @example '#ffffff'. */ color: string; /** * Line style. * * @example 2 // Dotted line. */ linestyle: number; /** * Line width. */ linewidth: number; /** * Value at which the band will be drawn. * * @example 75 // Drawn at price = 75. */ value: number; /** * Band visibility flag. */ visible: boolean; } /** * A description of a bar colorer plot. */ export interface StudyBarColorerPlotInfo extends StudyPalettedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.BarColorer; } export interface StudyBarTimeInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.BarTime; readonly defval: number; readonly max: number; readonly min: number; } /** * A description of a background colorer plot. */ export interface StudyBgColorerPlotInfo extends StudyPalettedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.BgColorer; } export interface StudyBooleanInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Bool; readonly defval: boolean; } /** * A description of a border colorer plot. */ export interface StudyCandleBorderColorerPlotInfo extends StudyPalettedPlotInfo, StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.CandleBorderColorer; } /** * A description of a wick colorer plot. */ export interface StudyCandleWickColorerPlotInfo extends StudyPalettedPlotInfo, StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.CandleWickColorer; } /** * A description of a study characters plot. */ export interface StudyCharsPlotInfo extends StudyPlotBaseInfo { /** @inheritDoc */ readonly type: StudyPlotType.Chars; } export interface StudyCharsPlotPreferences extends StudyPlotBasePreferences { /** Character */ char: string; /** Location for the mark */ location: MarkLocation; /** Color */ color: string; /** Text color */ textColor: string; /** Size of the symbol */ size?: PlotSymbolSize; /** Text content */ text?: string; } export interface StudyColorInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Color; readonly defval: string; } /** * A description of a colorer plot. */ export interface StudyColorerPlotInfo extends StudyPalettedPlotInfo, StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.Colorer; } /** * A description of a study data offset plot. */ export interface StudyDataOffsetPlotInfo extends StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.DataOffset; } /** * A description of a study data plot. */ export interface StudyDataPlotInfo extends StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.Data; } export interface StudyDefaults { bands: readonly Required[]; filledAreasStyle: MappedObject; inputs: StudyInputsSimple; palettes: MappedObject; precision: number | string; styles: MappedObject; ohlcPlots: MappedObject; graphics: StudyGraphicsDefaults; } /** * A description of a down colorer plot. */ export interface StudyDownColorerPlotInfo extends StudyPalettedPlotInfo, StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.DownColorer; } /** * Description of a study field. * This is used when `includedStudies: true` is defined in `exportData`. */ export interface StudyFieldDescriptor { /** Type is a `value` */ type: "value"; /** Source type is a `study` */ sourceType: "study"; /** * The ID of the source study. */ sourceId: string; /** * The title of the source study. */ sourceTitle: string; /** * The title of the source plot. */ plotTitle: string; } /** * Study filled area gradient styles. */ export interface StudyFilledAreaGradientColorStyle extends StudyFilledAreaStyleBase { /** Gradient fill type */ fillType: "gradient"; /** * Gradient top color. */ topColor?: string; /** * Gradient bottom color. */ bottomColor?: string; /** * Value at which the top of the gradient is drawn. * * @example 75 // Drawn at price = 75 */ topValue?: number; /** * Value at which the bottom of the gradient is drawn. * * @example 75 // Drawn at price = 75 */ bottomValue?: number; } /** * A description of a study filled area. */ export interface StudyFilledAreaInfo { /** * Study ID. */ readonly id: string; /** * Study band ID. * * @see StudyBandInfo */ readonly objAId: string; /** * Study band ID. * * @see StudyBandInfo */ readonly objBId: string; /** * Title that will appear in the styles tab of the study settings dialog. */ readonly title: string; /** * Filled area type. */ readonly type: FilledAreaType; /** * Should gaps in the area be filled? */ readonly fillgaps?: boolean; /** * Filled area z-order. */ readonly zorder?: number; /** * Filled area's style inputs visibility flag. Used to hide the band from the style tab of study properties dialogs. */ readonly isHidden?: boolean; /** * Color palette ID. */ readonly palette?: string; /** * Value at which the top of the filled area is drawn. * * @example 75 // Drawn at price = 75 */ readonly topValue?: number; /** * Value at which the bottom of the filled area is drawn. * * @example 75 // Drawn at price = 75 */ readonly bottomValue?: number; /** * Color for the top of the filled area. */ readonly topColor?: string; /** * Color for the bottom of the filled area. */ readonly bottomColor?: string; } /** * Study solid color filled area style preferences. */ export interface StudyFilledAreaSolidColorStyle extends StudyFilledAreaStyleBase { /** Solid Fill type */ fillType: undefined; /** * Color. * * @example '#ffffff' */ color: string; } /** * Base study filled area style preferences. */ export interface StudyFilledAreaStyleBase { /** * Filled area's visibility. */ visible: boolean; /** * Filled area's transparency. * * @min 0 * @max 100 */ transparency: number; } export interface StudyGraphicsDefaults { horizlines?: ValueByStyleId; polygons?: ValueByStyleId; hhists?: ValueByStyleId; vertlines?: ValueByStyleId; } export interface StudyInputBaseInfo { readonly id: string; readonly name: string; readonly defval?: StudyInputValue; readonly type: string; readonly confirm?: boolean; readonly isHidden?: boolean; readonly visible?: string; readonly isFake?: boolean; readonly isMTFResolution?: boolean; readonly groupId?: string; readonly internalID?: string; readonly inline?: string; readonly group?: string; readonly tooltip?: string; } /** * A description of a study input. */ export interface StudyInputInformation { /** * The input ID. */ id: StudyInputId; /** * The input name. */ name: string; /** * The input type. */ type: string; /** * The localized input name. */ localizedName: string; } export interface StudyInputOptionsTitles { [option: string]: string; } /** * A description of a study input value. */ export interface StudyInputValueItem { /** * The input ID. */ id: StudyInputId; /** * The input value. */ value: StudyInputValue; } export interface StudyInputsSimple { [inputId: string]: StudyInputValue; } /** * A description of a study line plot. */ export interface StudyLinePlotInfo extends StudyPlotBaseInfo { /** @inheritDoc */ readonly type: StudyPlotType.Line; } /** * Study line plot style preferences. */ export interface StudyLinePlotPreferences extends StudyPlotBasePreferences { /** * Plot style. */ plottype: LineStudyPlotStyle; /** * Line color. */ color: string; /** * Line style. */ linestyle: LineStyle; /** * Line width. */ linewidth: number; /** * Price line visibility flag. */ trackPrice: boolean; /** * Histogram base price. */ histogramBase?: number; joinPoints?: boolean; } export interface StudyNumericInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Integer | StudyInputType.Float | StudyInputType.Price; readonly defval: number; readonly max?: number; readonly min?: number; readonly step?: number; } /** * A description of an OHLC colorer plot. */ export interface StudyOhlcColorerPlotInfo extends StudyPalettedPlotInfo, StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.OhlcColorer; } export interface StudyOhlcPlotBarsStylePreferences extends StudyOhlcPlotBaseStylePreferences { /** OHLC Plot type: Bars */ plottype: OhlcStudyPlotStyle.OhlcBars; } export interface StudyOhlcPlotBaseStylePreferences { /** OHLC plot color */ color: string; /** Bitmask with values from StudyPlotDisplayTarget */ display: StudyPlotDisplayMode; visible?: boolean; } export interface StudyOhlcPlotCandlesStylePreferences extends StudyOhlcPlotBaseStylePreferences { /** OHLC Plot Type: Candles */ plottype: OhlcStudyPlotStyle.OhlcCandles; /** Whether to draw candle wick */ drawWick: boolean; /** Whether to draw candle border */ drawBorder: boolean; /** Candle wick color */ wickColor: string; /** Candle border color */ borderColor: string; } /** * A description of an OHLC plot. */ export interface StudyOhlcPlotInfo extends StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.OhlcOpen | StudyPlotType.OhlcHigh | StudyPlotType.OhlcLow | StudyPlotType.OhlcClose; } export interface StudyOhlcStylesInfo { readonly title: string; readonly isHidden?: boolean; readonly drawBorder?: boolean; readonly showLast?: number; } /** * Parameter object passed to event callback. */ export interface StudyOrDrawingAddedToChartEventParams { /** * Name of the added study or drawing. */ value: string; } /** * Study overrides. * * @example { 'a.overridable.property': 123 } */ export interface StudyOverrides { /** * Override values. */ [key: string]: StudyOverrideValueType; } /** * Study palette color. */ export interface StudyPaletteColor { /** * Palette color. */ color: string; /** * Palette style. */ style: number; /** * Palette width. */ width: number; } /** * Study palette style preferences. */ export interface StudyPaletteColorPreferences extends StudyPaletteColor, StudyPaletteInfo { } /** * A description of a study palette. */ export interface StudyPaletteInfo { /** * Palette name. */ readonly name: string; } /** * Study palette style preferences. */ export interface StudyPalettePreferences { /** * Palette colors. */ colors: Record; } /** * Study palette style. */ export interface StudyPaletteStyle { /** * Palette colors. */ colors: MappedObject | StudyPaletteColor[]; } /** * A description of a study plot with a palette. */ export interface StudyPalettedPlotInfo extends StudyPlotBaseInfo { /** * A color palette ID. */ readonly palette: string; } /** * A description of a study color palettes. */ export interface StudyPalettesInfo { /** * Palette colors. */ readonly colors: MappedObject | StudyPaletteInfo[]; /** * Mapping from values returned by the study to palette color index. */ readonly valToIndex?: MappedObject; /** * Use default color for {@link StudyPlotType.Colorer} plots when the value is `NaN`. */ readonly addDefaultColor?: boolean; } /** * Base type for all study plot descriptions. */ export interface StudyPlotBaseInfo { /** * Plot ID. */ readonly id: string; /** * Plot type. */ readonly type: string; } /** * Base type for all study plot style preferences. */ export interface StudyPlotBasePreferences { /** * Transparency. A number between 1 and 100. * * @example 80 */ transparency: number; /** * Display mode. See {@link StudyPlotDisplayMode}. * * @example StudyPlotDisplayTarget.None // Do not display the plot. */ display: StudyPlotDisplayMode; visible?: boolean; } export interface StudyPlotValueInheritFormat { /** Plot value type */ type: "inherit"; } export interface StudyPlotValuePrecisionFormat { /** Plot value type */ type: "price" | "volume" | "percent"; /** Plot Value Precision */ precision?: number; } export interface StudyPriceInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Price; readonly defval: number; readonly max?: number; readonly min?: number; readonly step?: number; } export interface StudyResolutionInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Resolution; readonly defval: ResolutionString; readonly options?: string[]; readonly optionsTitles?: StudyInputOptionsTitles; readonly isMTFResolution?: boolean; } export interface StudyResultValueWithOffset { /** * Value which will be offset */ value: number; /** * Allows you to override the offset of every plot (note that offset of a certain plot should always be the same) */ offset: number; } /** * A description of a RGBA colorer plot. */ export interface StudyRgbaColorerPlotInfo extends StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.Colorer; } export interface StudySessionInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Session; readonly defval: string; readonly options?: string[]; readonly optionsTitles?: StudyInputOptionsTitles; } /** * A description of a study shapes plot. */ export interface StudyShapesPlotInfo extends StudyPlotBaseInfo { /** @inheritDoc */ readonly type: StudyPlotType.Shapes; } /** * Study shape plot style preferences. */ export interface StudyShapesPlotPreferences extends StudyPlotBasePreferences { /** * Plot type. */ plottype: PlotShapeId; /** * Location relative to the bar. */ location: MarkLocation; /** * Color. */ color: string; /** * Text color. */ textColor: string; /** * Size. */ size?: PlotSymbolSize; /** * Text content. */ text?: string; } export interface StudySourceInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Source; readonly defval: StudyAvailableConstSources | string; readonly options?: (StudyAvailableConstSources | string)[]; readonly optionsTitles?: StudyInputOptionsTitles; } /** * Study style description. */ export interface StudyStyleInfo { /** * Default study description values. */ defaults?: StudyStyleInfoDefaults; /** * Study plot descriptions. */ plots?: readonly Readonly[]; /** * Study plot style descriptions. An object with `plot id` as keys and style info as values */ styles?: StudyStylesInfo; /** * Study band descriptions. */ bands?: readonly Readonly[]; /** * Study filled area descriptions. Filled area is a special object, which allows coloring an area between two plots. */ filledAreas?: readonly Readonly[]; /** * Study color palettes descriptions. */ palettes?: Record | undefined>; } /** * Default study style preferences. */ export interface StudyStyleInfoDefaults { /** * Default study bands style preferences. */ bands?: readonly StudyBandStyle[]; /** * Default study filled areas style preferences. */ filledAreasStyle?: Record; /** * Default study paletes style preferences. */ palettes?: Record; /** * Default study styles. */ styles?: Record; /** * Default study OHLC plot style preferences. */ ohlcPlots?: Record; /** * Default study graphics style preferences. */ graphics?: { /** Horizontal line style preferences */ horizlines?: Record; /** Polygon style preferences */ polygons?: Record; /** Histogram style preferences */ hhists?: Record; /** Vertical line style preferences */ vertlines?: Record; }; } /** * Study style values. */ export interface StudyStyleValues { /** * Plot descriptions. */ plots: StudyPlotInfo[]; /** * OHLC plot styles. */ ohlcPlots: Record; /** * Band styles. */ bands: StudyBandPreferences[]; /** * Palette styles. */ palettes: Record; /** * Plot styles. */ styles: Record; /** * Filled area descriptions. */ filledAreas: StudyFilledAreaInfo[]; /** * Filled area styles. */ filledAreasStyle: Record; /** * Graphics styles. */ graphics: { /** Horizontal line style preferences */ horizlines?: Record; /** Polygon style preferences */ polygons?: Record; /** Histogram style preferences */ hhists?: Record; /** Vertical line style preferences */ vertlines?: Record; }; } /** * Study styles description. */ export interface StudyStylesInfo { /** * Histogram base. A price value which will be considered as a start base point when rendering plot with histogram, columns or area style. */ readonly histogramBase?: number; /** * If `true` then plot points will be joined with line, applicable only to `Circles` and `Cross` type plots. Default is false. */ readonly joinPoints?: boolean; /** * Title used in the study dialog styles tab. */ readonly title?: string; /** * If `true` then the styles tab will be hidden in the study dialog. */ readonly isHidden?: boolean; /** * Minimum possible plot arrow size. Applicable only to arrow plot types. */ readonly minHeight?: number; /** * Maximum possible plot arrow size. Applicable only to arrow plot types. */ readonly maxHeight?: number; /** * Size of characters on the chart. Possible values are: `auto`, `tiny`, `small`, `normal`, `large`,`huge`. Applicable to `chars` and `shapes` plot types. */ readonly size?: PlotSymbolSize; /** * Text to display with the plot. Applicable to `chars` and `shapes` plot types. */ readonly text?: string; /** * If defined, defines the number of bars to plot on chart. */ readonly showLast?: number; /** * Used to control the zorder of the plot. Control if a plot is visually behind or in front of another. */ readonly zorder?: number; readonly location?: MarkLocation; readonly plottype?: OhlcStudyPlotStyle | PlotShapeId | LineStudyPlotStyle; } export interface StudySymbolInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Symbol; readonly defval?: string; readonly optional?: boolean; } /** * A description of a study plot with a target. */ export interface StudyTargetedPlotInfo extends StudyPlotBaseInfo { /** * ID of another target plot. */ readonly target: string; /** * Target field. */ readonly targetField?: "topColor" | "bottomColor" | "topValue" | "bottomValue"; } /** * Study template data. */ export interface StudyTemplateData { /** * Template name. */ name: string; /** * Template content. */ content: string; } /** * Study template metainfo. */ export interface StudyTemplateMetaInfo { /** * Template name. */ name: string; } /** * A description of a text colorer plot. */ export interface StudyTextColorerPlotInfo extends StudyPalettedPlotInfo, StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.TextColorer; } export interface StudyTextInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Text; readonly defval: string; readonly options?: string[]; readonly optionsTitles?: StudyInputOptionsTitles; } export interface StudyTextareaInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Textarea; readonly defval: string; } export interface StudyTimeInputInfo extends StudyInputBaseInfo { readonly type: StudyInputType.Time; readonly defval: number; readonly max: number; readonly min: number; } /** * A description of a up colorer plot. */ export interface StudyUpColorerPlotInfo extends StudyPalettedPlotInfo, StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.UpColorer; } export interface SubscribeEventsMap { /** * Drawing toolbar is shown/hidden * @param {boolean} isHidden - is the drawing toolbar currently hidden */ toggle_sidebar: (isHidden: boolean) => void; /** * Indicators dialog is shown */ indicators_dialog: EmptyCallback; /** * Chart header is shown/hidden * @param {boolean} isHidden - is the chart header currently hidden */ toggle_header: (isHidden: boolean) => void; /** * Chart / Study Properties dialog is shown * @param {EditObjectDialogEventParams} params - meta information about the dialog type and the title of the chart or study */ edit_object_dialog: (params: EditObjectDialogEventParams) => void; /** * New chart is about to be loaded * @param {object} savedData - chart data about to be loaded */ chart_load_requested: (savedData: object) => void; /** * Chart has finished loading */ chart_loaded: EmptyCallback; /** * Mouse button has been pressed * @param {MouseEventParams} params */ mouse_down: (params: MouseEventParams) => void; /** * Mouse button has been released * @param {MouseEventParams} params */ mouse_up: (params: MouseEventParams) => void; /** * A drawing has been added to a chart. * @param {StudyOrDrawingAddedToChartEventParams} params - The arguments contain an object with the `value` field that corresponds with the name of the drawing. */ drawing: (params: StudyOrDrawingAddedToChartEventParams) => void; /** * An indicator has been added to a chart. * @param {StudyOrDrawingAddedToChartEventParams} params - The arguments contain an object with the `value` field that corresponds with the name of the indicator. */ study: (params: StudyOrDrawingAddedToChartEventParams) => void; /** Undo action occurred */ undo: EmptyCallback; /** Redo action occurred */ redo: EmptyCallback; /** * The Undo / Redo state has been changed. * @param {UndoRedoState} state - state of the Undo/Redo stack */ undo_redo_state_changed: (state: UndoRedoState) => void; /** * Reset scales button has been clicked */ reset_scales: EmptyCallback; /** * A compare dialog has been shown */ compare_add: EmptyCallback; /** * A compare instrument has been added */ add_compare: EmptyCallback; /** * A study template has been loaded */ "load_study template": EmptyCallback; /** * Last bar has been updated * @param {Bar} tick - data for last bar */ onTick: (tick: Bar) => void; /** * User has changed the chart. `Chart change` means any user action that can be undone. * The callback function will not be called more than once every 5 seconds. See also `auto_save_delay` within the Widget constructor options ({@link ChartingLibraryWidgetOptions.auto_save_delay}). */ onAutoSaveNeeded: EmptyCallback; /** * A screenshot URL has been returned by the server * @param {string} url - url of the screenshot */ onScreenshotReady: (url: string) => void; /** * User has clicked on a 'mark on a bar'. * @param {Mark['id']} markId - ID of the clicked mark */ onMarkClick: (markId: Mark["id"]) => void; /** * User clicked the "plus" button on the price scale. * @param {PlusClickParams} params - coordinates, price and symbol information */ onPlusClick: (params: PlusClickParams) => void; /** * User clicked a 'timescale mark'. * @param {TimescaleMark['id']} markId - ID of the clicked timescale mark */ onTimescaleMarkClick: (markId: TimescaleMark["id"]) => void; /** Selected drawing tool has changed */ onSelectedLineToolChanged: EmptyCallback; /** * Amount or placement of the charts is about to be changed. * **Note:** this event is only applicable to Trading Terminal. * @param {LayoutType} newLayoutType - whether the layout is single or multi-chart */ layout_about_to_be_changed: (newLayoutType: LayoutType) => void; /** * Amount or placement of the charts is changed. * **Note:** this event is only applicable to Trading Terminal. */ layout_changed: EmptyCallback; /** * Active chart has changed * **Note:** this event is only applicable to Trading Terminal. * @param {number} chartIndex - index of the active chart */ activeChartChanged: (chartIndex: number) => void; /** * An event related to the series has occurred. * @param {SeriesEventType} seriesEventType - series event type */ series_event: (seriesEventType: SeriesEventType) => void; /** * An event related to the study has occurred. * @param {EntityId} entityId - study ID * @param {StudyEventType} studyEventType - study event type */ study_event: (entityId: EntityId, studyEventType: StudyEventType) => void; /** * Drawing was hidden, shown, moved, removed, clicked, or created * @param {EntityId} sourceId - drawing ID * @param {DrawingEventType} drawingEventType - drawing event type */ drawing_event: (sourceId: EntityId, drawingEventType: DrawingEventType) => void; /** * Study properties have changed. * @param {EntityId} id - entity ID */ study_properties_changed: (id: EntityId) => void; /** * Main series properties have changed. * @param {EntityId} id - entity ID */ series_properties_changed: (id: EntityId) => void; /** * Panes' size has changed. */ panes_height_changed: () => void; /** * Panes' order has changed. */ panes_order_changed: () => void; } export interface SuccessFormatterParseResult extends FormatterParseResult { /** @inheritDoc */ res: true; /** Returned value once parsing is done */ value: T; /** Optional value returned by the default formatter */ suggest?: string; } /** * Extended symbol information. */ export interface SymbolExt { /** * Symbol name. E.g. `'AAPL'`. */ symbol: string; /** * Full symbol name. E.g. `'NasdaqNM:AAPL'`. */ full_name: string; /** * Exchange name. E.g. `'NasdaqNM`' */ exchange: string; /** * Symbol description. E.g. `'Apple Inc.'`. */ description: string; /** * Symbol type. E.g. `'stock'`. */ type: string; } export interface SymbolInfoPriceSource { /** Unique ID */ id: string; /** Short name */ name: string; } export interface SymbolInputSymbolSource { type: "symbolInputSymbolSource"; inputId: string; } /** * The time interval for a specific symbol. */ export interface SymbolIntervalResult { /** Symbol name */ symbol: string; /** Time interval */ interval: ResolutionString; } /** Additional information about the Symbol's currency or unit */ export interface SymbolResolveExtension { /** * Indicates the currency for conversions if `currency_codes` configuration field is set, * and `currency_code` is provided in the original symbol information ({@link LibrarySymbolInfo}). * Read more about [currency conversion](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale#currency-conversion). */ currencyCode?: string; /** * Indicates the unit for conversion if `units` configuration * field is set and `unit_id` is provided in the original symbol information ({@link LibrarySymbolInfo}). */ unitId?: string; session?: string; } /** * Symbol override data. Passed to and returned from the symbol search override funciton. */ export interface SymbolSearchCompleteData { /** * The symbol (or ticker). */ symbol: string; /** * The human friendly symbol name to display to users. */ name: string; } export interface TableFormatterInputs { /** Array of values to be formatted. Values are obtained by extracting dependent properties from the data object. */ values: T extends [ ...args: infer A ] ? [ ...A ] : never; /** optional field. It is array of previous values so you can compare and format accordingly. It exists if current column has the `highlightDiff: true` key. */ prevValues?: Partial; /** standard formatter for price. You can use `format(price)` method to prepare price value. */ priceFormatter?: INumberFormatter; } export interface TextWithCheckboxFieldCustomInfo { /** Title for the checkbox */ checkboxTitle: string; /** * Using `asterix` property you can manage input type. * If `asterix` is set to `true` then a password input will be rendered. */ asterix?: boolean; } export interface TextWithCheckboxFieldMetaInfo extends CustomInputFieldMetaInfo { /** @inheritDoc */ inputType: "TextWithCheckBox"; /** @inheritDoc */ value: TextWithCheckboxValue; /** @inheritDoc */ customInfo: TextWithCheckboxFieldCustomInfo; /** @inheritDoc */ validator?: TextInputFieldValidator; } export interface TextWithCheckboxValue { /** Checkbox text */ text: string; /** Whether the checkbox is checked */ checked: boolean; } /** * Used in the schema defined in exportData API to describe the time field. * This is used when `includeTime: true` is defined in `exportData` to add time to exported data. */ export interface TimeFieldDescriptor { /** time field descriptor */ type: "time"; } /** * Definition of visible timeframes that can be selected at the bottom of the chart * @example * ```javascript * { text: "3y", resolution: "1W", description: "3 Years", title: "3yr" } * ``` */ export interface TimeFrameItem { /** Defines the range to be set for the given resolution. It has the `` ( \d+(y|m|d) as Regex ) format. */ text: string; /** Resolution to be set */ resolution: ResolutionString; /** Optional text displayed in the pop-up menu. If not set, `title` wil be used instead. */ description?: string; /** Optional text representing the time frame. If not set a generated string will be set based on `text` property. */ title?: string; } /** Defines a time frame at a specific date */ export interface TimeFramePeriodBack { /** Time frame period is `period-back` */ type: TimeFrameType.PeriodBack; /** A UNIX timestamp */ value: string; } /** Defines a time frame between 2 dates */ export interface TimeFrameTimeRange { /** Time frame period is `time-range` */ type: TimeFrameType.TimeRange; /** * A UNIX timestamp. The start of the range */ from: number; /** * A UNIX timestamp. The end of the range */ to: number; } /** Position defined by time. */ export interface TimePoint { /** A UNIX timestamp */ time: number; } /** * Widget Constructor option (`time_scale`) to add more/less on screen */ export interface TimeScaleOptions { /** Minimum allowed space between bars. Should be greater than 0. */ min_bar_spacing?: number; } export interface TimescaleMark { /** ID of the timescale mark */ id: string | number; /** * Time for the mark. * Amount of **milliseconds** since Unix epoch start in **UTC** timezone. */ time: number; /** Color for the timescale mark */ color: MarkConstColors | string; /** * Color for the timescale mark text label. * If undefined then the value provided for `color` will be used. */ labelFontColor?: MarkConstColors | string; /** Label for the timescale mark */ label: string; /** Tooltip content */ tooltip: string[]; /** Shape of the timescale mark */ shape?: TimeScaleMarkShape; /** * Optional URL for an image to be displayed within the timescale mark. * * The image should ideally be square in dimension. You can use any image type which * the browser supports natively. * * Examples: * - `https://s3-symbol-logo.tradingview.com/crypto/XTVCBTC.svg` * - `/images/myImage.png` * - `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3...` * - `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4...` */ imageUrl?: string; /** * Continue to show text label even when an image has * been loaded for the timescale mark. * * Defaults to `false` if undefined. */ showLabelWhenImageLoaded?: boolean; } /** * Supported timezone identifier are {@link LibrarySymbolInfo.timezones} and {@link LibrarySymbolInfo.exchange}. * `exchange` is a special "timezone" that means the timezone of a currently active symbol. * Thus the actual timezone will be calculated every time a symbol changes. */ export interface TimezoneInfo { /** Timezone identifier {@link TimezoneId} */ id: TimezoneId | CustomTimezoneId; /** Name of the timezone */ title: string; /** Optional number to indicate an offset */ offset?: number; /** * Id of supported default timezone to use for the actual timezone calculations, see {@link TimezoneId} */ alias?: TimezoneId | GmtTimezoneId; } export interface Trade extends TradeBase, CustomFields { } /** * Describes a single trade (individual position). */ export interface TradeBase { /** Trade ID. Usually id should be equal to brokerSymbol */ id: string; /** Trade date (UNIX timestamp in milliseconds) */ date: number; /** Symbol name */ symbol: string; /** Trade Quantity */ qty: number; /** Trade Side */ side: Side; /** Trade price */ price: number; } export interface TradeContext { /** Symbol name */ symbol: string; /** Symbol display name */ displaySymbol: string; /** Price value */ value: number | null; /** Formatted value */ formattedValue: string; /** Previous value */ last: number; } export interface TradingCustomization { /** Overrides for Positions */ position: Overrides; /** Overrides for Orders */ order: Overrides; } export interface TradingDialogOptions { /** Custom fields to be displayed in the dialog (adds additional input fields to the Order dialog). */ customFields?: TradingDialogCustomField[]; } export interface TradingQuotes { /** Trade */ trade?: number; /** Quote size */ size?: number; /** Bid price */ bid?: number; /** Bid quantity */ bid_size?: number; /** Ask price */ ask?: number; /** Ask quantity */ ask_size?: number; /** Price spread */ spread?: number; /** Whether quotes are delayed */ isDelayed?: boolean; /** Whether quotes are halted */ isHalted?: boolean; /** Whether quotes are hard to borrow */ isHardToBorrow?: boolean; /** Whether quotes are can not be shorted */ isNotShortable?: boolean; } export interface TradingTerminalWidgetOptions extends Omit { disabled_features?: TradingTerminalFeatureset[]; enabled_features?: TradingTerminalFeatureset[]; /** configuration flags for the Trading Terminal. */ brokerConfig?: SingleBrokerMetaInfo; /** configuration flags for the Trading Terminal. */ broker_config?: SingleBrokerMetaInfo; /** Connection configuration settings for Rest Broker API */ restConfig?: RestBrokerConnectionInfo; /** * Settings for the widget panel on the right side of the chart. * Watchlist, news, details and data window widgets on the right side of the chart can be enabled using the `widgetbar` field in Widget constructor */ widgetbar?: WidgetBarParams; /** * Use this property to change the RSS feed for news. You can set a different RSS for each symbol type or use a single RSS for all symbols. The object should have the `default` property, other properties are optional. The names of the properties match the symbol types. Each property is an object (or an array of objects) with the following properties: * * 1. `url` - is a URL to be requested. It can contain tags in curly brackets that will be replaced by the terminal: `{SYMBOL}`, `{TYPE}`, `{EXCHANGE}`. * 1. `name` - is a name of the feed to be displayed underneath the news. * * @example * ```javascript * rss_news_feed: { * default: [ { * url: "https://articlefeeds.nasdaq.com/nasdaq/symbols?symbol={SYMBOL}", * name: "NASDAQ" * }, { * url: "http://feeds.finance.yahoo.com/rss/2.0/headline?s={SYMBOL}®ion=US&lang=en-US", * name: "Yahoo Finance" * } ] * }, * ``` * * @example * ```javascript * rss_news_feed: { * "default": { * url: "https://articlefeeds.nasdaq.com/nasdaq/symbols?symbol={SYMBOL}", * name: "NASDAQ" * } * } * ``` * * @example * ```javascript * rss_news_feed: { * "default": { * url: "https://articlefeeds.nasdaq.com/nasdaq/symbols?symbol={SYMBOL}", * name: "NASDAQ" * }, * "stock": { * url: "http://feeds.finance.yahoo.com/rss/2.0/headline?s={SYMBOL}®ion=US&lang=en-US", * name: "Yahoo Finance" * } * } * ``` */ rss_news_feed?: RssNewsFeedParams; /** * Use this property to set your own news getter function. Both the `symbol` and `callback` will be passed to the function. * * The callback function should be called with an object. The object should have two properties: `title` which is a optional string, and `newsItems` which is an array of news objects that have the following structure: * * * `title` (required) - the title of news item. * * `published` (required) - the time of news item in ms (UTC). * * `source` (optional) - source of the news item title. * * `shortDescription` (optional) - Short description of a news item that will be displayed under the title. * * `link` (optional) - URL to the news story. * * `fullDescription` (optional) - full description (body) of a news item. * * **NOTE:** Only `title` and `published` are the main properties used to compare what has already been published and what's new. * * **NOTE 2:** When a user clicks on a news item a new tab with the `link` URL will be opened. If `link` is not specified then a pop-up dialog with `fullDescription` will be shown. * * **NOTE 3:** If both `news_provider` and `rss_news_feed` are available then the `rss_news_feed` will be ignored. * * See [News API examples](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news/News-Api-Examples) for usage examples. */ news_provider?: GetNewsFunction; /** Override customizations for trading */ trading_customization?: TradingCustomization; /** Alias for {@link broker_factory} */ brokerFactory?(host: IBrokerConnectionAdapterHost): IBrokerWithoutRealtime | IBrokerTerminal; /** * Use this field to pass the function that returns a new object which implements Broker API. This is a function that accepts the Trading Host ({@link IBrokerConnectionAdapterHost}). * * @example * ```javascript * broker_factory: function(host) { ... } * ``` * @param host - Trading Host */ broker_factory?(host: IBrokerConnectionAdapterHost): IBrokerWithoutRealtime | IBrokerTerminal; } /** * Additional translation options */ export interface TranslateOptions { /** Plural of the phrase */ plural?: string; /** Count of the phrase */ count?: number; /** Context of the phrase */ context?: string; /** Replacements object */ replace?: Record; } /** * Undo options. */ export interface UndoOptions { /** * A boolean flag. Controls if undo should be disabled. */ disableUndo?: boolean; } /** State of the Undo/Redo stack. This object has the same structure as the result of {@link IChartingLibraryWidget.undoRedoState} method */ export interface UndoRedoState { /** Undo is enabled */ readonly enableUndo: boolean; /** Undo text */ readonly undoText: string | undefined; /** Redo is enabled */ readonly enableRedo: boolean; /** Redo text */ readonly redoText: string | undefined; /** Original text for undo action - without being translated */ readonly originalUndoText: string | undefined; /** Original text for redo action - without being translated */ readonly originalRedoText: string | undefined; } export interface Unit { /** Unique ID */ id: string; /** Short name */ name: string; /** Description */ description: string; } /** * Used in the schema defined in exportData API to describe the user time field. * This is used when `includeUserTime: true` is defined in `exportData` to add user time (aka time that is displayed to the user on the chart) to exported data. */ export interface UserTimeFieldDescriptor { /** user time field descriptor */ type: "userTime"; } export interface ValueByStyleId { [styleId: string]: TValue | undefined; } export interface VertLinePreferences { /** Is visible if set to `true` */ visible: boolean; /** Width of the vertical line */ width: number; /** Color of the horizontal line */ color: string; /** Line style */ style: LineStyle; } export interface VertLinePreferences { visible: boolean; width: number; color: string; style: LineStyle; } /** * Boundaries of the price scale visible range in main series area */ export interface VisiblePriceRange { /** * A UNIX timestamp. The start of the range. */ from: number; /** * A UNIX timestamp. The end of the range. */ to: number; } /** * A time range. */ export interface VisibleTimeRange { /** * A UNIX timestamp. The start of the range. */ from: number; /** * A UNIX timestamp. The end of the range. */ to: number; } export interface WatchListSymbolList extends WatchListSymbolListData { /** Symbol ID */ id: string; } export interface WatchListSymbolListData { /** Symbol IDs in watchlist */ symbols: string[]; /** Title for the watchlist */ title: string; } export interface WatchListSymbolListMap { /** Symbol watchlist */ [listId: string]: WatchListSymbolList; } export interface WatchedValueSubscribeOptions { /** Subscribe for only one update, and remove subscription afterwards. (the callback will be executed only once) */ once?: boolean; /** if it is set to true then the callback will be executed with the previous value (if available) */ callWithLast?: boolean; } export interface WidgetBarParams { /** * Enables details widget in the widget panel on the right. * @default false */ details?: boolean; /** * Enables watchlist widget in the widget panel on the right. * @default false */ watchlist?: boolean; /** * Enables news widget in the widget panel on the right. * @default false */ news?: boolean; /** * Enables data window widget in the widget panel on the right. * @default false */ datawindow?: boolean; /** Watchlist settings */ watchlist_settings?: { /** * Sets the list of default symbols for watchlist. * @default [] */ default_symbols: string[]; /** * Enables read-only mode for the watchlist * @default false */ readonly?: boolean; }; } export type AccountId = Nominal; export type AccountManagerColumn = { [K in StandardFormatterName | FormatterName]: AccountManagerColumnBase; }[StandardFormatterName | FormatterName]; /** * Describes a single action to put it into a dropdown or a context menu. */ export type ActionMetaInfo = ActionDescriptionWithCallback | MenuSeparator; /** * The Ask and Bid quotes. */ export type AskBid = Required>; export type AvailableSaveloadVersions = "1.0" | "1.1"; export type CellAlignment = "left" | "right"; /** * A chart action ID. */ export type ChartActionId = "chartProperties" | "compareOrAdd" | "scalesProperties" | "paneObjectTree" | "insertIndicator" | "symbolSearch" | "changeInterval" | "timeScaleReset" | "chartReset" | "seriesHide" | "studyHide" | "lineToggleLock" | "lineHide" | "scaleSeriesOnly" | "drawingToolbarAction" | "stayInDrawingModeAction" | "hideAllMarks" | "showCountdown" | "showSeriesLastValue" | "showSymbolLabelsAction" | "showStudyLastValue" | "showStudyPlotNamesAction" | "undo" | "redo" | "paneRemoveAllStudiesDrawingTools" | "showSymbolInfoDialog"; /** This is the list of all featuresets that work on Charting Library */ export type ChartingLibraryFeatureset = /** Allows storing all properties (including favorites) to the localstorage @default true */ "use_localstorage_for_settings" | /** Disabling this feature hides "Favorite this item" icon for Drawings and Intervals @default true */ "items_favoriting" | /** Can be disabled to forbid storing chart properties to the localstorage while allowing to save other properties. The other properties are favorites in the Charting Library and Watchlist symbols and some panels states in the Trading Terminal @default true @default true */ "save_chart_properties_to_local_storage" | /** Add the volume indicator upon initialisation of the chart @default true */ "create_volume_indicator_by_default" | /** Prevent the volume indicator from being recreated when an instrument or a resolution is switched @default true */ "create_volume_indicator_by_default_once" | /** Places Volume indicator on the same pane with the main series @default true */ "volume_force_overlay" | /** Determines the behavior of Zoom feature: bar under the mouse cursor stays in the same place if this feature is disabled @default true */ "right_bar_stays_on_scroll" | /** Keeps the dialogs within the chart @default true */ "constraint_dialogs_movement" | /** Enables logs @default false */ "charting_library_debug_mode" | /** This enables Drawings Toolbar in the fullscreen mode @default false */ "side_toolbar_in_fullscreen_mode" | /** Enables header widget DOM element in the fullscreen mode @default false */ "header_in_fullscreen_mode" | /** Shows bar time exactly as provided by the data feed with no adjustments @default false */ "disable_resolution_rebuild" | /** Allows chart scrolling @default true */ "chart_scroll" | /** Allows chart zooming @default true */ "chart_zoom" | /** If enabled, the chart handles horizontal pointer movements on touch screens. In this case the webpage is not scrolled. If disabled, the webpage is scrolled instead. Keep in mind that if the user starts scrolling the chart vertically or horizontally, scrolling is continued in any direction until the user releases the finger @default true */ "horz_touch_drag_scroll" | /** If enabled, the chart handles vertical pointer movements on touch screens. In this case the webpage is not scrolled. If disabled, the webpage is scrolled instead. Keep in mind that if the user starts scrolling the chart vertically or horizontally, scrolling is continued in any direction until the user releases the finger @default true */ "vert_touch_drag_scroll" | /** If enabled, chart scrolling with horizontal mouse wheel is enabled @default true */ "mouse_wheel_scroll" | /** If enabled, chart scrolling with left mouse button pressed is allowed @default true */ "pressed_mouse_move_scroll" | /** If enabled, series scaling with a mouse wheel is enabled @default true */ "mouse_wheel_scale" | /** If enabled, series scaling with pinch/zoom gestures (this option is supported on touch devices) is enabled @default true */ "pinch_scale" | /** If enabled, axis scaling with left mouse button pressed is allowed @default true */ "axis_pressed_mouse_move_scale" | /** Allows zooming in to show up to one bar in the viewport @default false */ "low_density_bars" | /** Disabling this feature allows a user to enter case-sensitive symbols @default true */ "uppercase_instrument_names" | /** Disables minimum chart width limitation @default false */ "no_min_chart_width" | /** Prevents scrolling to the left of the first historical bar @default false */ "fix_left_edge" | /** Prevents changing visible time area on chart resizing @default false */ "lock_visible_time_range_on_resize" | /** If disabled, adding a new bar zooms out the chart preserving the first visible point. Otherwise the chart is scrolled one point to the left when a new bar comes @default true */ "shift_visible_range_on_new_bar" | /** If enabled, there is a possibility to add custom resolutions @default false */ "custom_resolutions" | /** Toggles the timeline marks to display the bar's end time @default false */ "end_of_period_timescale_marks" | /** If disabled, partially visible price labels on price axis will be hidden @default true */ "cropped_tick_marks" | /** Applies symbol display mode (ticker/description) to overlay/compare studies in the status line @default false */ "study_overlay_compare_legend_option" | /** Applies symbol display mode (ticker/description) to indicator inputs in the status line @default false */ "study_symbol_ticker_description" | /** Displays Symbol Name Label when comparing Symbols @default true */ "auto_enable_symbol_labels" | /** Enables insert indicator dialog shortcut (/) @default true */ "insert_indicator_dialog_shortcut" | /** Display at most two characters in bar marks. The default behavior is to only display one character @default false */ "two_character_bar_marks_labels" | /** By default many chart layouts can be saved with the same name. If this feature is enabled then the library will prompt to confirm overwriting chart layouts with the same name when saving, renaming, or cloning ("Save as") @default false */ "confirm_overwrite_if_chart_layout_with_name_exists" | /** By default the chart will request a small (fixed) number of bars for the initial data request when the chart is first created. If this feature is enabled then the library will rather calculate the request size based on the amount of bars which will be visible on the chart @default false */ "determine_first_data_request_size_using_visible_range" | /** Places the logo on the main series pane instead of the bottom pane @default false */ "move_logo_to_main_pane" | /** Enables a button in the header to load/save `Indicator template` @default false */ "study_templates" | /** Enables copying of drawings and studies @default true */ "datasource_copypaste" | /** Enables the support of resolutions that start from 1 second @default false */ "seconds_resolution" | /** Enables the support of tick resolution @default false */ "tick_resolution" | /** Enables a feature to allow an additional series to extend the time scale @default false */ "secondary_series_extend_time_scale" | /** Removes the header from the chart @default true */ "header_widget" | /** Hides the symbol search button from the header @default true */ "header_symbol_search" | /** Symbol search by pressing any key @default true */ "symbol_search_hot_key" | /** Hides the resolution button from the header @default true */ "header_resolutions" | /** Displays a `Change interval` dialog to specify another resolution @default true */ "show_interval_dialog_on_key_press" | /** Hides the chart type button from the header @default true */ "header_chart_type" | /** Relates to Chart Properties button @default true */ "header_settings" | /** Hides the indicators button from the header @default true */ "header_indicators" | /** Hides the compare button from the header @default true */ "header_compare" | /** Hides the undo/redo button from the header @default true */ "header_undo_redo" | /** Hides the screenshot button from the header @default true */ "header_screenshot" | /** Hides the fullscreen button from the header @default true */ "header_fullscreen_button" | /** Adds a 2px padding to the chart @default true */ "border_around_the_chart" | /** Hides save/load buttons (the feature is not part of `header_widget` featureset) @default true */ "header_saveload" | /** Hides the left toolbar aka drawings toolbar @default true */ "left_toolbar" | /** Relates to the navigation buttons at the bottom of the chart @default true */ "control_bar" | /** Hide the timeframe toolbar at the bottom of the chart @default true */ "timeframes_toolbar" | /** Disabling this feature hides the legend widget @default true */ "legend_widget" | /** Display legend on all diagrams regardless of crosshair synchronization @default false */ "display_legend_on_all_charts" | /** Display object tree button in the legend at a small width @default true */ "object_tree_legend_mode" | /** Removes all buttons from the legend except the ellipsis menu @default true */ "edit_buttons_in_legend" | /** Removes the eye button that hides/shows a chart @default true */ "show_hide_button_in_legend" | /** Removes the cog icon for accessing chart/indicator's settings @default true */ "format_button_in_legend" | /** Removes the delete button @default true */ "delete_button_in_legend" | /** Doesn't display any context menu when right clicking anywhere in the UI @default true */ "context_menus" | /** Doesn't display the context menu when right clicking on the chart @default true */ "pane_context_menu" | /** Doesn't display the context menu when right clicking on either price scale or timescale @default true */ "scales_context_menu" | /** Doesn't display the context menu when right clicking on the legend @default true */ "legend_context_menu" | /** Displays the settings button in the bottom right corner of the chart @default true */ "main_series_scale_menu" | /** Hides the market status from the legend @default true */ "display_market_status" | /** Sets the border style to 0px & padding to 1px @default true */ "remove_library_container_border" | /** Disables all property pages @default true */ "property_pages" | /** Turning this feature off disables Properties @default true */ "show_chart_property_page" | /** Allows overrides for the price scale @default true */ "chart_property_page_scales" | /** This feature is for the Trading Terminal only @default true */ "chart_property_page_trading" | /** Shows the right margin editor in the setting dialog @default true */ "chart_property_page_right_margin_editor" | /** Displays a countdown label on a price scale @default true */ "countdown" | /** Hides true/false study arguments @default false */ "dont_show_boolean_study_arguments" | /** Hides last n/a study output data @default false */ "hide_last_na_study_output" | /** Enables the symbol info dialog @default true */ "symbol_info" | /** Disables timezone context menu @default true */ "timezone_menu" | /** Includes orders/positions/executions in the screenshot @default false */ "snapshot_trading_drawings" | /** Disables selection markers for series and indicators @default true */ "source_selection_markers" | /** Allows you to jump to a particular bar using 'Go to' dialog @default true */ "go_to_date" | /** Allows you to hide 'charts by TradingView' text on small-screen devices @default true */ "adaptive_logo" | /** Shows DOM panel when a user opens the Chart for the first time @default false */ "show_dom_first_time" | /** Hides left toolbar when a user opens the Chart for the first time @default false */ "hide_left_toolbar_by_default" | /** Adds High-low option to chart style controls @default true */ "chart_style_hilo" | /** Enables last price line and price axis label on High-low chart style @default false */ "chart_style_hilo_last_price" | /** Displays the currency in which the instrument is traded on the price axes @default false */ "pricescale_currency" | /** Displays the unit in which the instrument is traded on the price axes @default false */ "pricescale_unit" | /** Displays Date Format selector in Chart Settings @default true */ "scales_date_format" | /** Displays popup hints about possible mouse/shortcuts/UI actions @default true */ "popup_hints" | /** Enables the save shortcut @default true */ "save_shortcut" | /** Opens right widget toolbar on first launch @default true */ "show_right_widgets_panel_by_default" | /** Shows the object tree button in the left or right panel depending on the product and configuration @default true */ "show_object_tree" | /** Shows the spread operators in the Symbol Search dialog @default false */ "show_spread_operators" | /** Hide exponentiation spread operator (^) in the Symbol Search dialog @default false */ "hide_exponentiation_spread_operator" | /** Hide reciprocal spread operator (1/x) in the Symbol Search dialog @default false */ "hide_reciprocal_spread_operator" | /** Shows the spread operators in the Compare Search dialog - needs to be used in conjunction to show_spread_operators @default false */ "compare_symbol_search_spread_operators" | /** Shows the spread operators for Studies - needs to be used in conjunction to show_spread_operators @default false */ "studies_symbol_search_spread_operators" | /** Hide the interval (D, 2D, W, M, etc.) in the chart legend and the data window @default false */ "hide_resolution_in_legend" | /** Hide unresolved symbols in the chart legend and the data window @default false */ "hide_unresolved_symbols_in_legend" | /** On touch device show the zoom and move buttons at the bottom of the chart @default false */ "show_zoom_and_move_buttons_on_touch" | /** Hide the optional symbol input value from the indicator's legend if 'Main chart symbol' option is selected @default true */ "hide_main_series_symbol_from_indicator_legend" | /** Hide the global last price label on price scale if last bar is outside of visible range @default false */ "hide_price_scale_global_last_bar_value" | /** Hide the visibility settings of the label and the average close price line @default false */ "show_average_close_price_line_and_label" | /** Hide image shown to illustrate symbol is invalid @default false */ "hide_image_invalid_symbol" | /** Show/Hide the exchange label from the displayed label @default false */ "hide_object_tree_and_price_scale_exchange_label" | /** Displays Time Format selector in Chart Settings @default true */ "scales_time_hours_format" | /** Show a literal "n/a" for not available values instead of "∅" @default false */ "use_na_string_for_not_available_values" | /** Enable pre and post market session support @default false */ "pre_post_market_sessions" | /** Show the option to specify the default right margin in percentage within chart settings dialog @default false */ "show_percent_option_for_right_margin" | /** * Alternative loading mode for the library, which can be used to support * older browsers and a few non-standard browsers. * @default false */ "iframe_loading_compatibility_mode" | /** Use the last (rightmost) visible bar value in the legend @default false */ "use_last_visible_bar_value_in_legend" | /** Enable long symbol descriptions to be shown in the main series and compare studies legends, if provided in the symbol info data. */ "symbol_info_long_description" | /** Enable symbol price source to be shown in the main series and compare studies legends, if provided in the symbol info data. */ "symbol_info_price_source"; /** These are defining the types for a background */ export type ColorTypes = "solid" | "gradient"; /** * Context menu items processor signature * @param {readonlyIActionVariant[]} items - an array of items the library wants to display * @param {ActionsFactory} actionsFactory - factory you could use to create a new items for the context menu. */ export type ContextMenuItemsProcessor = (items: readonly IActionVariant[], actionsFactory: ActionsFactory) => Promise; /** * @param {readonlyIActionVariant[]} items - an array of items the library wants to display * @param {CreateContextMenuParams} params - an object representing where the user right-clicked on (only if there is an existing menu) * @param {()=>void} onDestroy - function that you should call once a created menu is hidden/destroyed */ export type ContextMenuRendererFactory = (items: readonly IActionVariant[], params: CreateContextMenuParams, onDestroy: () => void) => Promise; export type CreateButtonOptions = CreateHTMLButtonOptions | CreateTradingViewStyledButtonOptions; export type CustomStudyFormatter = Omit; /** * Factory function that can be implemented to create custom study formatters. */ export type CustomStudyFormatterFactory = (format: CustomStudyFormatterFormat, symbolInfo: LibrarySymbolInfo | null) => CustomStudyFormatter | null; /** * A function that takes an {@link TableFormatterInputs} object and returns a `string` or an `HTMLElement`. */ export type CustomTableFormatElementFunction = (inputs: TableFormatterInputs) => undefined | string | HTMLElement; /** * Identifier for a custom timezone (string). */ export type CustomTimezoneId = Nominal<"CustomTimezoneId", string>; export type CustomTimezones = "Africa/Cairo" | "Africa/Johannesburg" | "Africa/Lagos" | "Africa/Nairobi" | "Africa/Tunis" | "America/Argentina/Buenos_Aires" | "America/Bogota" | "America/Caracas" | "America/Chicago" | "America/El_Salvador" | "America/Juneau" | "America/Lima" | "America/Los_Angeles" | "America/Mexico_City" | "America/New_York" | "America/Phoenix" | "America/Santiago" | "America/Sao_Paulo" | "America/Toronto" | "America/Vancouver" | "Asia/Almaty" | "Asia/Ashkhabad" | "Asia/Bahrain" | "Asia/Bangkok" | "Asia/Chongqing" | "Asia/Colombo" | "Asia/Dubai" | "Asia/Ho_Chi_Minh" | "Asia/Hong_Kong" | "Asia/Jakarta" | "Asia/Jerusalem" | "Asia/Karachi" | "Asia/Kathmandu" | "Asia/Kolkata" | "Asia/Kuwait" | "Asia/Manila" | "Asia/Muscat" | "Asia/Nicosia" | "Asia/Qatar" | "Asia/Riyadh" | "Asia/Seoul" | "Asia/Shanghai" | "Asia/Singapore" | "Asia/Taipei" | "Asia/Tehran" | "Asia/Tokyo" | "Asia/Yangon" | "Atlantic/Reykjavik" | "Australia/Adelaide" | "Australia/Brisbane" | "Australia/Perth" | "Australia/Sydney" | "Europe/Amsterdam" | "Europe/Athens" | "Europe/Belgrade" | "Europe/Berlin" | "Europe/Bratislava" | "Europe/Brussels" | "Europe/Bucharest" | "Europe/Budapest" | "Europe/Copenhagen" | "Europe/Dublin" | "Europe/Helsinki" | "Europe/Istanbul" | "Europe/Lisbon" | "Europe/London" | "Europe/Luxembourg" | "Europe/Madrid" | "Europe/Malta" | "Europe/Moscow" | "Europe/Oslo" | "Europe/Paris" | "Europe/Riga" | "Europe/Rome" | "Europe/Stockholm" | "Europe/Tallinn" | "Europe/Vilnius" | "Europe/Warsaw" | "Europe/Zurich" | "Pacific/Auckland" | "Pacific/Chatham" | "Pacific/Fakaofo" | "Pacific/Honolulu" | "Pacific/Norfolk" | "US/Mountain"; /** * Custom translation function * @param {string} key - key for string to be translated * @param {TranslateOptions} options? - additional translation options */ export type CustomTranslateFunction = (key: string, options?: TranslateOptions) => string | null; export type DateFormat = keyof typeof dateFormatFunctions; export type DeepWriteable = { -readonly [P in keyof T]: DeepWriteable; }; /** * The direction of an execution line. Either buy or sell. */ export type Direction = "buy" | "sell"; export type DomeCallback = (data: DOMData) => void; /** * A event related to a drawing. * * - Note that the `properties_changed` event can be emitted before `create` event, and that the * event isn't debounced (for example dragging a slider for a property will result in this event * firing for each movement on the slider), you may want to debounce this within your code. * - The `move` event is emitted when a drawing is moved as a whole, whilst the `points_changed` * event is emitted when a single point of the drawing is moved. `points_changed` will always fire * when `move` fires but not vice-versa. */ export type DrawingEventType = "click" | "move" | "remove" | "hide" | "show" | "create" | "properties_changed" | "points_changed"; export type DrawingToolIdentifier = "arrow" | "cursor" | "dot" | "eraser" | "LineTool5PointsPattern" | "LineToolABCD" | "LineToolArc" | "LineToolArrow" | "LineToolArrowMarkDown" | "LineToolArrowMarker" | "LineToolArrowMarkLeft" | "LineToolArrowMarkRight" | "LineToolArrowMarkUp" | "LineToolBarsPattern" | "LineToolBezierCubic" | "LineToolBezierQuadro" | "LineToolBrush" | "LineToolCallout" | "LineToolCircle" | "LineToolCircleLines" | "LineToolComment" | "LineToolCrossLine" | "LineToolCypherPattern" | "LineToolDateAndPriceRange" | "LineToolDateRange" | "LineToolDisjointAngle" | "LineToolElliottCorrection" | "LineToolElliottDoubleCombo" | "LineToolElliottImpulse" | "LineToolElliottTriangle" | "LineToolElliottTripleCombo" | "LineToolEllipse" | "LineToolExtended" | "LineToolFibChannel" | "LineToolFibCircles" | "LineToolFibRetracement" | "LineToolFibSpeedResistanceArcs" | "LineToolFibSpeedResistanceFan" | "LineToolFibSpiral" | "LineToolFibTimeZone" | "LineToolFibWedge" | "LineToolFixedRangeVolumeProfile" | "LineToolFlagMark" | "LineToolFlatBottom" | "LineToolGannComplex" | "LineToolGannFan" | "LineToolGannFixed" | "LineToolGannSquare" | "LineToolGhostFeed" | "LineToolHeadAndShoulders" | "LineToolHighlighter" | "LineToolHorzLine" | "LineToolHorzRay" | "LineToolInfoLine" | "LineToolInsidePitchfork" | "LineToolNote" | "LineToolNoteAbsolute" | "LineToolParallelChannel" | "LineToolPath" | "LineToolPitchfan" | "LineToolPitchfork" | "LineToolPolyline" | "LineToolPrediction" | "LineToolPriceLabel" | "LineToolPriceNote" | "LineToolPriceRange" | "LineToolProjection" | "LineToolRay" | "LineToolRectangle" | "LineToolRegressionTrend" | "LineToolRiskRewardLong" | "LineToolRiskRewardShort" | "LineToolRotatedRectangle" | "LineToolSchiffPitchfork" | "LineToolSchiffPitchfork2" | "LineToolSignpost" | "LineToolSineLine" | "LineToolText" | "LineToolTextAbsolute" | "LineToolThreeDrivers" | "LineToolTimeCycles" | "LineToolTrendAngle" | "LineToolTrendBasedFibExtension" | "LineToolTrendBasedFibTime" | "LineToolTrendLine" | "LineToolTriangle" | "LineToolTrianglePattern" | "LineToolVertLine"; /** Dropdown options which can be adjusted on an existing menu. */ export type DropdownUpdateParams = Partial>; export type EditObjectDialogObjectType = "mainSeries" | "drawing" | "study" | "other"; export type EmptyCallback = () => void; export type EntityId = Nominal; export type ErrorCallback = (reason: string) => void; /** * Description of each field of exported data from the chart */ export type FieldDescriptor = TimeFieldDescriptor | UserTimeFieldDescriptor | SeriesFieldDescriptor | StudyFieldDescriptor; export type FinancialPeriod = "FY" | "FQ" | "FH" | "TTM"; export type FormatterName = Nominal; export type GetMarksCallback = (marks: T[]) => void; export type GetNewsFunction = (symbol: string, callback: (response: GetNewsResponse) => void) => void; /** * GMT timezone ID. * * In order to conform with the POSIX style, those zone names * beginning with "Etc/GMT" have their sign reversed from the * standard ISO 8601 convention. In the "Etc" area, zones west * of GMT have a positive sign and those east have a negative * sign in their name (e.g "Etc/GMT-14" is 14 hours ahead of GMT). */ export type GmtTimezoneId = `Etc/GMT${"+" | "-"}${number}${`:${number}` | ""}`; export type GroupLockState = "Locked" | "Unlocked" | "Partial"; export type GroupVisibilityState = "Visible" | "Invisible" | "Partial"; /** * Mode can be of the following: * * * `fullsize`: always full-size buttons on the top toolbar * * `adaptive`: adaptive/auto mode (fullsize if the window width allows and icons on small windows). * * `compact`: icons only buttons on the top toolbar (favorites won't be shown) */ export type HeaderWidgetButtonsMode = "fullsize" | "compact" | "adaptive"; export type HistoryCallback = (bars: Bar[], meta?: HistoryMetadata) => void; /** Item variants within a context menu */ export type IActionVariant = IAction | ISeparator; export type IBarArray = [ number, number, number, number, number, number ]; export type IBasicDataFeed = IDatafeedChartApi & IExternalDatafeed; /** Specific formatter for number */ export type INumberFormatter = IFormatter; export type IPineStudyResult = IPineStudyResultTypes; export type IPineStudyResultSimple = StudyPrimitiveResult | ISeriesStudyResult | INonSeriesStudyBarsResult | IProjectionStudyResult | INonSeriesStudyResult; export type IPineStudyResultTypes = TPineStudyResultSimple | PineStudyResultComposite; export type IProjectionBar = [ number, number, number, number, number, number ] | [ number, number, number, number, number, number, number ]; export type ISeriesStudyResult = [ /* time */ number, number, number, number, number, number, /* updatetime */ number | undefined, /* isBarClosed */ boolean | undefined ]; /** * Input field validator * @param {any} value - value to be validated */ export type InputFieldValidator = (value: any) => InputFieldValidatorResult; export type InputFieldValidatorResult = PositiveBaseInputFieldValidatorResult | NegativeBaseInputFieldValidatorResult; export type LanguageCode = "ar" | "zh" | "cs" | "da_DK" | "ca_ES" | "nl_NL" | "en" | "et_EE" | "fr" | "de" | "el" | "he_IL" | "hu_HU" | "id_ID" | "it" | "ja" | "ko" | "fa" | "pl" | "pt" | "ro" | "ru" | "sk_SK" | "es" | "sv" | "th" | "tr" | "vi" | "no" | "ms_MY" | "zh_TW"; export type LayoutType = SingleChartLayoutType | MultipleChartsLayoutType; export type LegendMode = "horizontal" | "vertical"; export type LibrarySessionId = "regular" | "extended" | "premarket" | "postmarket"; export type MarkConstColors = "red" | "green" | "blue" | "yellow"; export type MultipleChartsLayoutType = "2h" | "2v" | "2-1" | "3s" | "3h" | "3v" | "4" | "6" | "8" | "1-2" | "3r" | "4h" | "4v" | "4s" | "5h" | "6h" | "7h" | "8h" | "1-3" | "2-2" | "2-3" | "1-4" | "5s" | "6c" | "8c"; export type OnActionExecuteHandler = (action: IAction) => void; export type OnActionUpdateHandler = (action: IAction) => void; export type OnReadyCallback = (configuration: DatafeedConfiguration) => void; export type Order = PlacedOrder | BracketOrder; export type OrderTableColumn = AccountManagerColumn & { /** * An optional numeric array of order statuses that is applied to order columns only. If it is available then the column will be displayed in the specified tabs of the status filter only. * * Here is the list of possible order statuses: * * 0 - All * 1 - Canceled * 2 - Filled * 3 - Inactive * 5 - Rejected, * 6 - Working */ supportedStatusFilters?: OrderStatusFilter[]; }; export type PageName = "watchlist_details_news" | "data_window" | "object_tree"; /** * Plot shape ID. */ export type PlotShapeId = "shape_arrow_down" | "shape_arrow_up" | "shape_circle" | "shape_cross" | "shape_xcross" | "shape_diamond" | "shape_flag" | "shape_square" | "shape_label_down" | "shape_label_up" | "shape_triangle_down" | "shape_triangle_up"; export type PriceSource = "open" | "high" | "low" | "close"; export type QuoteData = QuoteOkData | QuoteErrorData; /** * Callback to provide Quote data. * @param {QuoteData[]} data - Quote Data */ export type QuotesCallback = (data: QuoteData[]) => void; /** * Error callback for quote data request. * @param {QuoteData[]} reason - message describing the reason for the error */ export type QuotesErrorCallback = (reason: string) => void; export type RawStudyMetaInfoId = Nominal; export type RawStudyMetaInformation = Omit & { readonly plots?: readonly Readonly[]; readonly defaults?: Readonly>; }; /** * Resolution or time interval is a time period of one bar. Charting Library supports tick, intraday (seconds, minutes, hours), and DWM (daily, weekly, monthly) resolutions. The table below describes how to specify different types of resolutions: * * Resolution | Format | Example * ---------|----------|--------- * Ticks | `xT` | `1T` — one tick * Seconds | `xS` | `1S` — one second * Minutes | `x` | `1` — one minute * Hours | `x` minutes | `60` — one hour * Days | `xD` | `1D` — one day * Weeks | `xW` | `1W` — one week * Months | `xM` | `1M` — one month * Years | `xM` months | `12M` — one year * * Refer to [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution) for more information. */ export type ResolutionString = Nominal; export type ResolveCallback = (symbolInfo: LibrarySymbolInfo) => void; /** RSS news feed. */ export type RssNewsFeedItem = RssNewsFeedInfo | RssNewsFeedInfo[]; export type SearchSymbolsCallback = (items: SearchSymbolResultItem[]) => void; /** An event related to the series. Currently the only possible value for this argument is `price_scale_changed` */ export type SeriesEventType = "price_scale_changed"; export type SeriesFormat = "price" | "volume"; export type SeriesFormatterFactory = (symbolInfo: LibrarySymbolInfo | null, minTick: string) => ISymbolValueFormatter | null; /** * Where to attach the price scale. * Options are either to the `left`, `right`, next to an already existing price axis using a reference or `no scale` if there are no other scales on the main pane. */ export type SeriesPriceScale = "new-left" | "new-right" | "no-scale" | EntityId; export type SeriesStatusViewSymbolTextSource = "ticker" | "description" | "ticker-and-description" | "long-description"; export type ServerTimeCallback = (serverTime: number) => void; /** * A time range to set. The end `to` value is optional. * * When the optional `to` value is omitted then the value will * fallback to the timestamp of the latest bar on the chart. */ export type SetVisibleTimeRange = Omit & Partial>; /** Drawing point */ export type ShapePoint = StickedPoint | PricedPoint | TimePoint; export type ShapesGroupId = Nominal; export type SingleChartLayoutType = "s"; export type StudyAvailableConstSources = "open" | "high" | "low" | "close" | "hl2" | "hlc3" | "ohlc4" | "hlcc4"; /** An event related to a study. */ export type StudyEventType = "remove" | "price_scale_changed" | "paste_study"; export type StudyFilledAreaStyle = StudyFilledAreaSolidColorStyle | StudyFilledAreaGradientColorStyle; export type StudyInputId = Nominal; export type StudyInputInfo = StudyBooleanInputInfo | StudyTextInputInfo | StudySymbolInputInfo | StudyResolutionInputInfo | StudySessionInputInfo | StudySourceInputInfo | StudyNumericInputInfo | StudyPriceInputInfo | StudyColorInputInfo | StudyTimeInputInfo | StudyBarTimeInputInfo | StudyTextareaInputInfo; export type StudyInputInfoList = readonly Readonly[]; /** * The value of a study input. */ export type StudyInputValue = string | number | boolean; export type StudyMetaInfo = DeepWriteable & { id: string; }; export type StudyOhlcPlotPreferences = StudyOhlcPlotBarsStylePreferences | StudyOhlcPlotCandlesStylePreferences; export type StudyOverrideValueType = string | number | boolean; export type StudyPlotDisplayMode = Nominal | StudyPlotDisplayTarget; export type StudyPlotInfo = StudyPlotInformation; /** * A description of a study plot. */ export type StudyPlotInformation = StudyArrowsPlotInfo | StudyCharsPlotInfo | StudyColorerPlotInfo | StudyRgbaColorerPlotInfo | StudyDataPlotInfo | StudyDataOffsetPlotInfo | StudyLinePlotInfo | StudyOhlcPlotInfo | StudyShapesPlotInfo | StudyBarColorerPlotInfo | StudyBgColorerPlotInfo | StudyTextColorerPlotInfo | StudyOhlcColorerPlotInfo | StudyCandleWickColorerPlotInfo | StudyCandleBorderColorerPlotInfo | StudyUpColorerPlotInfo | StudyDownColorerPlotInfo; /** * Study plot style preferences. */ export type StudyPlotPreferences = StudyLinePlotPreferences | StudyShapesPlotPreferences | StudyCharsPlotPreferences | StudyArrowsPlotPreferences; export type StudyPlotValueFormat = StudyPlotValueInheritFormat | StudyPlotValuePrecisionFormat; /** * Price scale to display a study on. * * Possible values are: * * `new-left` - attach the study to a new left price scale * * `new-right` - attach the study to a new right price scale * * `no-scale` - do not attach the study to any price scale. The study will be added in 'No Scale' mode * * `as-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) */ export type StudyPriceScale = "new-left" | "new-right" | "no-scale" | "as-series"; export type StudyPrimitiveResult = (number | StudyResultValueWithOffset)[]; export type SubscribeBarsCallback = (bar: Bar) => void; export type SupportedLineTools = "text" | "anchored_text" | "note" | "anchored_note" | "signpost" | "double_curve" | "arc" | "icon" | "emoji" | "arrow_up" | "arrow_down" | "arrow_left" | "arrow_right" | "price_label" | "price_note" | "arrow_marker" | "flag" | "vertical_line" | "horizontal_line" | "cross_line" | "horizontal_ray" | "trend_line" | "info_line" | "trend_angle" | "arrow" | "ray" | "extended" | "parallel_channel" | "disjoint_angle" | "flat_bottom" | "pitchfork" | "schiff_pitchfork_modified" | "schiff_pitchfork" | "balloon" | "comment" | "inside_pitchfork" | "pitchfan" | "gannbox" | "gannbox_square" | "gannbox_fixed" | "gannbox_fan" | "fib_retracement" | "fib_trend_ext" | "fib_speed_resist_fan" | "fib_timezone" | "fib_trend_time" | "fib_circles" | "fib_spiral" | "fib_speed_resist_arcs" | "fib_channel" | "xabcd_pattern" | "cypher_pattern" | "abcd_pattern" | "callout" | "triangle_pattern" | "3divers_pattern" | "head_and_shoulders" | "fib_wedge" | "elliott_impulse_wave" | "elliott_triangle_wave" | "elliott_triple_combo" | "elliott_correction" | "elliott_double_combo" | "cyclic_lines" | "time_cycles" | "sine_line" | "long_position" | "short_position" | "forecast" | "date_range" | "price_range" | "date_and_price_range" | "bars_pattern" | "ghost_feed" | "projection" | "rectangle" | "rotated_rectangle" | "circle" | "ellipse" | "triangle" | "polyline" | "path" | "curve" | "cursor" | "dot" | "arrow_cursor" | "eraser" | "measure" | "zoom" | "brush" | "highlighter" | "regression_trend" | "fixed_range_volume_profile"; /** * function to override the symbol input from symbol search dialogs * @param {SymbolSearchCompleteData} symbol - input from the symbol search */ export type SymbolSearchCompleteOverrideFunction = (symbol: string, searchResultItem?: SearchSymbolResultItem) => Promise; export type SymbolSource = SymbolInputSymbolSource; export type SymbolType = "stock" | "index" | "forex" | "futures" | "bitcoin" | "crypto" | "undefined" | "expression" | "spread" | "cfd" | "economic" | "equity" | "dr" | "bond" | "right" | "warrant" | "fund" | "structured"; /** * A function that takes an {@link TableFormatterInputs} object and returns a `string`. */ export type TableFormatTextFunction = (inputs: TableFormatterInputs) => string; export type TableFormatterInputValue = any; export type TableFormatterInputValues = TableFormatterInputValue[]; export type TextInputFieldValidator = (value: string) => InputFieldValidatorResult; export type ThemeName = "Light" | "Dark"; export type TickMarkType = /** * The start of the year (e.g. it's the first tick mark in a year). */ "Year" /** * The start of the month (e.g. it's the first tick mark in a month). */ | "Month" /** * A day of the month. */ | "DayOfMonth" /** * A time without seconds. */ | "Time" /** * A time with seconds. */ | "TimeWithSeconds"; /** * Type of timeframe defined in the UI. * Can either be a single one {@link TimeFramePeriodBack} or a range {@link TimeFrameTimeRange} * * Examples: * 1. a timeframe object, `{type, value}`: * * `type`: `period-back`. * * `value`: valid timeframe is a number with letter D for days and M for months. * 2. a range object, `{type, from, to}` * * `type`: `time-range`. * * `from`, `to`: UNIX timestamps, UTC. */ export type TimeFrameValue = TimeFramePeriodBack | TimeFrameTimeRange; export type TimeScaleMarkShape = "circle" | "earningUp" | "earningDown" | "earning"; export type TimeframeOption = string | { /** From date timestamp */ from: number; /** To date timestamp */ to: number; }; export type Timezone = "Etc/UTC" | CustomTimezones; export type TimezoneId = CustomTimezones | "Etc/UTC" | "exchange"; /** * `TradableSolutions` has one of the following keys: * - `changeAccount` - id of a sub-account suitable for trading the symbol * - `changeSymbol` - the symbol suitable for trading with current sub-account */ export type TradableSolutions = ChangeAccountSolution | ChangeSymbolSolution; export type TradingDialogCustomField = CheckboxFieldMetaInfo | TextWithCheckboxFieldMetaInfo | CustomComboBoxMetaInfo; /** This is the list of all featuresets that work on Trading Terminal (which is an extension of Charting Library) */ export type TradingTerminalFeatureset = ChartingLibraryFeatureset | /** Enables the "plus" button on the price scale for quick trading @default true */ "chart_crosshair_menu" | /** Enables context menu actions (Clone, Sync) related to Multiple Chart Layout @default true */ "support_multicharts" | /** Shows the Select Layout button in the header @default true */ "header_layouttoggle" | /** Enables "Add symbol to Watchlist" item in the menu @default true */ "add_to_watchlist" | /** Keeps the Account Manager opened by default @default true */ "open_account_manager" | /** Shows trading notifications on the chart @default true */ "trading_notifications" | /** Enables creating of multiple watchlists @default true */ "multiple_watchlists" | /** Enables the Notifications Log tab in the bottom panel @default true */ "show_trading_notifications_history" | /** If a bracket order is modified, the terminal passes its parent order to `modifyOrder`. The featureset disables this behavior @default false */ "always_pass_called_order_to_modify" | /** Enables Drawing Templates on Drawing toolbar @default true */ "drawing_templates" | /** Shows the Account Manager Widget @default true */ "trading_account_manager" | /** Shows the right buttons toolbar @default true */ "right_toolbar" | /** Shows the Order Panel @default true */ "order_panel" | /** Shows the Order info section in the Order dialog @default true */ "order_info" | /** Shows the Buy/Sell Buttons in Legend @default true */ "buy_sell_buttons" | /** Shows the Broker Button in Legend @default true */ "broker_button" | /** Order Panel is visible when the chart opens @default false */ "show_order_panel_on_start" | /** Shows close Order Panel button @default true */ "order_panel_close_button" | /** Shows the Undock button in the Order Panel Settings @default true */ "order_panel_undock" | /** Hide the close button for position @default false */ "chart_hide_close_position_button" | /** Hide the close button for order @default false */ "chart_hide_close_order_button" | /** Enables watchlist export and import @default true */ "watchlist_import_export" | /** Enables DOM widget visibility @default false */ "dom_widget" | /** Keeps Object Tree widget in the right toolbar @default false */ "keep_object_tree_widget_in_right_toolbar" | /** Show only the last price and change values in the main series legend @default false */ "show_last_price_and_change_only_in_series_legend" | /** Show a context menu on clicking the crosshair menu even when there's only 1 item to show @default false */ "show_context_menu_in_crosshair_if_only_one_item" | /** Enable context menu support in the watchlist. */ "watchlist_context_menu "; export type VisiblePlotsSet = "ohlcv" | "ohlc" | "c"; export type WatchListSymbolListAddedCallback = (listId: string, symbols: string[]) => void; export type WatchListSymbolListChangedCallback = (listId: string) => void; export type WatchListSymbolListRemovedCallback = (listId: string) => void; export type WatchListSymbolListRenamedCallback = (listId: string, oldName: string, newName: string) => void; export type WatchedValueCallback = (value: T) => void; export as namespace TradingView; export {}; /* eslint-disable jsdoc/require-jsdoc */ declare type DeepPartial = { [P in keyof T]?: T[P] extends (infer U)[] ? DeepPartial[] : T[P] extends readonly (infer X)[] ? readonly DeepPartial[] : DeepPartial; };