# Charting Library Context and Prompt ## Part 1: Documentation Content Below you will find the necessary documentation to answer questions about the TradingView Charting Library. It includes the TypeScript definition files (`.d.ts`) for complete type information and the markdown version of the official documentation for explanations and examples. File: broker-api.d.ts ====================== /** * Broker JS API for TradingView Trading Platform * @packageDocumentation * @module Broker */ // Generated by dts-bundle-generator v9.5.1 export declare const enum DisconnectType { LogOut = 0, FailedRestoring = 1, Offline = 2, APIError = 3, TwoFactorRequired = 4, CancelAuthorization = 5, TimeOutForAuthorization = 6, OauthError = 7, BrokenConnection = 8, Reconnect = 9, FailedSignIn = 10 } export declare const enum BottomWidgetBarMode { Minimized = "minimized", Normal = "normal", Maximized = "maximized" } /** * Enumeration of the built-in formatters for the Account Manager columns. * Refer to the [Value formatters](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters) section for more information. */ export declare const enum StandardFormatterName { Date = "date", DateOrDateTime = "dateOrDateTime", Default = "default", Fixed = "fixed", FixedInCurrency = "fixedInCurrency", VariablePrecision = "variablePrecision", FormatQuantity = "formatQuantity", FormatPrice = "formatPrice", FormatPriceForexSup = "formatPriceForexSup", FormatPriceInCurrency = "formatPriceInCurrency", IntegerSeparated = "integerSeparated", LocalDate = "localDate", LocalDateOrDateTime = "localDateOrDateTime", Percentage = "percentage", Pips = "pips", Profit = "profit", ProfitInInstrumentCurrency = "profitInInstrumentCurrency", ProfitInPercent = "profitInPercent", Side = "side", PositionSide = "positionSide", Status = "status", Symbol = "symbol", Text = "text", Type = "type", MarginPercent = "marginPercent", Empty = "empty" } export declare enum CommonAccountManagerColumnId { /** You should use this column id if you want to fix the column in the positions and orders tables. */ Symbol = "symbol" } export declare enum ConnectionStatus { Connected = 1, Connecting = 2, Disconnected = 3, Error = 4 } export declare enum ConnectionType { Demo = 1, Real = 0 } export declare enum NotificationType { Error = 0, Success = 1 } export declare enum OrderOrPositionMessageType { Information = "information", Warning = "warning", Error = "error" } export declare enum OrderStatus { Canceled = 1, Filled = 2, Inactive = 3, Placing = 4, Rejected = 5, Working = 6 } export declare enum OrderStatusFilter { All = 0, Canceled = 1, Filled = 2, Inactive = 3, Rejected = 5, Working = 6 } export declare enum OrderTicketFocusControl { LimitPrice = 1, StopPrice = 2, TakeProfit = 3, StopLoss = 4, Quantity = 5 } export declare enum OrderType { Limit = 1, Market = 2, Stop = 3, StopLimit = 4 } export declare enum ParentType { Order = 1, Position = 2, IndividualPosition = 3 } export declare enum PriceType { Limit = 1, Stop = 2 } export declare enum Side { Buy = 1, Sell = -1 } export declare enum StopType { StopLoss = 0, TrailingStop = 1, GuaranteedStop = 2 } /** * 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; }; /** Column properties for the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager) pages. */ 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; /** Unique column identifier. */ id: string; /** * Defines a formatter to be applied for data formatting, which can either belong to the `StandardFormatterName` or `FormatterName` type. * If no specific formatter is set, the value is displayed as is. * * Default formatter names are enumerated in {@link StandardFormatterName}. * Refer to the [Built-in formatters](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters#built-in-formatters) section to see the full list of formatters. * * You can also create custom formatters using the {@link AccountManagerInfo.customFormatters} property. */ formatter?: TFormatterName; /** * The `dataFields` array contains fields from an order/position data object. * `dataFields` is used to generate the values displayed in a column. * The displayed value in the column updates only when the corresponding values in the data object change. * * If no {@link formatter} is specified, the displayed values will be space-separated in the column. * When a `formatter` is defined, it processes only the specified values. * If an empty array is assigned to `dataFields`, the `formatter` will receive the entire data object. * * **Example** * * - For a column with `dataFields` set as `['avgPrice', 'qty']`, the displayed value updates only when the `avgPrice` or `qty` values in the data object change. * - For a column with an empty `dataFields` array, the displayed value updates if any values in the data object change. */ dataFields: TFormatterName extends StandardFormatterName ? StandardFormattersDependenciesMapping[TFormatterName] : string[]; /** * Data object key that is used for data sorting. * * If `sortProp` is not provided, the first element of the `dataFields` array will be used. * If the `dataFields` array is empty, the 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`](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters#formatPrice) * and [`StandardFormatterName.FormatPriceForexSup`](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters#formatPriceForexSup) formatters to highlight the changes of the field. * If `highlightDiff is `true`, the custom formatters will also get previous values. */ highlightDiff?: boolean; /** Setting `notHideable` to `true` prevents the column from being hidden. */ notHideable?: boolean; /** Setting `hideByDefault` to `true` hides 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; /** Setting `showZeroValues` to `true` hides any zero values. The default value is `true`. */ showZeroValues?: boolean; } /** * The information object that is used to build the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager). */ export interface AccountManagerInfo { /** Name of the broker */ accountTitle: string; /** * Custom fields that are always displayed at the top-right corner of the Account Manager. * Refer to the [Account Summary row](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#account-summary-row) section for more information. */ summary: AccountManagerSummaryField[]; /** * An optional array for defining [custom formatters](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters#custom-formatters). * Each formatter description is an object with the following fields: * * - `name` ({@link FormatterName}): Unique formatter name. * * - `formatText` ({@link TableFormatTextFunction}): * Function that is used for formatting a cell value to a string. * The `formatText` field is required because it is used to generate exported data. * You can return an empty string if you do not need this function. * * - `formatElement` ({@link CustomTableFormatElementFunction} | `undefined`): * Optional function that is used for formatting a cell value to a string or an HTML element. * * If the `formatElement` function is provided, it only handles the formatting of displayed values. * Otherwise the `formatText` function is used. * For optimal performance, it is recommended to only use `formatText` if you intend to display only string values. * * **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[]; /** An array of data objects that create columns for the [Orders](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#orders-and-positions) 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; /** * An array of data objects that create columns for the [History](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#history) page where all orders from previous sessions are shown. * Note that this page is only shown * if you set the {@link BrokerConfigFlags.supportOrdersHistory} to `true` * and implement the [`ordersHistory`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#ordershistory) method. */ historyColumns?: AccountManagerColumn[]; /** Optional sorting of the table on the [History](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#history) page. */ historyColumnsSorting?: SortingParameters; /** * An array of data objects that create columns for the [Positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#orders-and-positions) page. * 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 an {@link IndividualPosition} * or add your own fields to an individualPosition object and display them. */ individualPositionColumns?: AccountManagerColumn[]; /** Adds [custom pages](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#custom-pages) to the Account Manager. Each page 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; /** * A function for creating a custom [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) for positions and orders in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager). * @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[]; /** Controls whether the number of items is displayed on a custom page. Set to `true` to display the count, or `false` to hide it. */ displayCounterInTab?: boolean; } /** 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; /** An optional parameter with text explaining the contents of this field. */ informerMessage?: string; } /** * 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>; /** This delegate is used to watch the data deletions and update the table. * Pass the id of the row that needs to be deleted to the `fire` method of the delegate. */ deleteDelegate?: ISubscription<(id: string) => 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 AccountMetainfo { /** * Account ID */ id: AccountId; /** * Account Name */ name: string; /** * Account Type */ type?: "live" | "demo"; /** * Currency */ currency?: string; /** * Currency Sign (Prefix) */ currencySign?: string; } 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 BaseInputFieldValidatorResult { /** Is the base input value valid */ valid: boolean; } /** * An object that contains information about a bracket order. */ export interface BracketOrder extends BracketOrderBase, CustomFields { } export interface BracketOrderBase extends PlacedOrderBase { /** If an order is a bracket, it should contain an ID of a parent order/position. */ parentId: string; /** Type of the bracket's parent. */ parentType: ParentType; } export interface Brackets { /** Stop loss */ stopLoss?: number; /** Guaranteed Stop */ guaranteedStop?: number; /** Take Profit */ takeProfit?: number; /** Trailing Stop Pips */ trailingStopPips?: number; } export interface BrokerConfigFlags { /** * Changes _Amount_ to _Quantity_ in Order Ticket. * @default false */ showQuantityInsteadOfAmount?: boolean; /** * Enables order brackets: take-profit and stop-loss. * @default false */ supportOrderBrackets?: boolean; /** * Enables stop loss orders. If this flag is set to `true`, the library displays stop loss orders and a user can place a stop loss order using the Order Ticket. * If you set this flag to `false`, the {@link BrokerConfigFlags.supportTrailingStop} and/or {@link BrokerConfigFlags.supportGuaranteedStop} flag should be set to `true`. * If the `supportStopLoss`, `supportTrailingStop`, and `supportGuaranteedStop` flags are set to `false`, the default value will be used. * @default true */ supportStopLoss?: boolean; /** * Enables trailing stop orders. * If you set this flag to `true`, the library displays trailing stop orders and a user can place a trailing stop order using the Order Ticket. * @default false */ supportTrailingStop?: boolean; /** * Enables guaranteed stop loss orders. * If you set this flag to `true`, the library displays guaranteed stop orders and a user can place a guaranteed stop order using the Order Ticket. * @default false */ supportGuaranteedStop?: boolean; /** * Enables [positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions). * This flag requires the [`positions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#positions) method to be implemented. * If you set `supportPositions` to `false`, the _Positions_ tab in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager) will be hidden. * @default true */ supportPositions?: boolean; /** * Enables position brackets: take-profit and stop-loss orders. * If you set `supportPositionBrackets` to `true`, the library displays an _Edit_ button for positions and _Edit position..._ in the position's context menu. * This flag requires the {@link IBrokerTerminal.editPositionBrackets} method to be implemented. * @default false */ supportPositionBrackets?: boolean; /** * Enables brackets for individual positions: take-profit and stop-loss orders. * If you set this flag to `true`, the library displays an _Edit_ button for individual positions and _Edit position..._ in the individual position's context menu. * This flag requires the {@link IBrokerTerminal.editIndividualPositionBrackets} method to be implemented. * @default false */ supportIndividualPositionBrackets?: boolean; /** * Enables [position netting](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#position-netting). * This flag requires the [`positions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#positions) and [`individualPositions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#individualpositions) method to be implemented. * * If you set this flag to `true`, the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager) will have two tabs: _Individual Positions_ and _Net Positions_. * * @default false */ supportPositionNetting?: boolean; /** * Enables [position closing](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#close-positions). * - If `supportClosePosition` is set to `false`, positions are closed using [market orders](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders#order-types) of the opposite side. The library calls the {@link IBrokerTerminal.placeOrder} method, passing the `isClose` property set to `true` in the `PreOrder` object. * - If `supportClosePosition` is set to `true`, the library calls the {@link IBrokerTerminal.closePosition} method. * @default false */ supportClosePosition?: boolean; /** * Enables individual [position closing](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#close-positions). * This flag requires the {@link IBrokerTerminal.closeIndividualPosition} method to be implemented. * @default false */ supportCloseIndividualPosition?: boolean; /** * Enables order price editing. * If you set this flag to `false`, the price control in the _Order Ticket_ will be disabled when users modify orders. * @default true */ supportModifyOrderPrice?: boolean; /** * Enables order quantity editing. * If you set this flag to `false`, the quantity control in the _Order Ticket_ will be disabled when users modify orders. * @default true */ supportEditAmount?: boolean; /** * Enables order brackets editing. * If you set this flag to `false`, the bracket's control in the Order Ticket will be disabled, * and the _Modify_ button will be hidden from the chart and in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager). * @default true */ supportModifyBrackets?: boolean; /** * Enables Level 2 data for the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) widget. * This flag requires the [`subscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribedepth) and [`unsubscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#unsubscribedepth) methods to be implemented. * @default false */ supportLevel2Data?: boolean; /** * Enables [multiple positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#multiposition) for one instrument at the same time. * * Note that if the flag is set to `true`: * - The [default reversal](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#default-reversal) in the library does not work. You need to implement the [native reversal](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#native-reversal) on your backend side. * - The _Flatten_ button in the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) widget will be disabled. * @default false */ supportMultiposition?: boolean; /** * Allows using your own [profit and loss](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss) (P&L) values for positions. * By default, `supportPLUpdate` is set to `true`. * This means you should calculate the P&L value for a position and [provide values](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss#provide-pl-values) to the library. * * If `supportPLUpdate` is set to `false`, the library automatically calculates P&L values as the difference between the current trade and the average position price. * However, we recommend using your own P&L calculations for positions. * This helps avoid any discrepancies between the P&L values of the account and positions due to potential delays. * @default true */ supportPLUpdate?: boolean; /** * Enables [position reversing](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#reverse-positions). * If `supportReversePosition` is set to `false`, the _Reverse Position_ button will be hidden from the UI. * @default false */ supportReversePosition?: boolean; /** * Enables [native](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#native-reversal) position reversing. You should implement the {@link IBrokerTerminal.reversePosition} method to process reversing on your backend side. * Note that the {@link supportReversePosition} flag should be set to `true` to enable the reverse option in the UI. * * If `supportNativeReversePosition` is set to `false`, the library handles reversing using the built-in mechanism. For more information, refer to the [Default reversal](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#default-reversal) section. * @default false */ supportNativeReversePosition?: boolean; /** * Enables market orders type in the Order Ticket. * @default true */ supportMarketOrders?: boolean; /** * Enables limit orders type in the Order Ticket. * @default true */ supportLimitOrders?: boolean; /** * Enables stop orders type in the Order Ticket. * @default true */ supportStopOrders?: boolean; /** * Enables stop-limit orders type in the Order Ticket. * @default false */ supportStopLimitOrders?: boolean; /** * Enables demo live switcher. * @default true */ supportDemoLiveSwitcher?: boolean; /** * Enables brackets for market orders. * @default true */ supportMarketBrackets?: boolean; /** * Enables symbol searching. * @default false */ supportSymbolSearch?: boolean; /** * Allows modifying existing [order duration](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-time-in-force-menu). * @default false */ supportModifyDuration?: boolean; /** * Allows modifying trailing stop orders. * @default true */ supportModifyTrailingStop?: boolean; /** * Allows margin. * If `supportMargin` is set to `true`, you should call {@link IBrokerConnectionAdapterHost.marginAvailableUpdate} when the Trading Platform subscribes to margin available updates using {@link IBrokerTerminal.subscribeMarginAvailable}. * @default false */ supportMargin?: boolean; /** * Allows providing the estimated commission, fees, margin, and other order information before placing the order without actually placing it. * This information will be displayed in the _Order confirmation_ dialog. * * This flag requires the {@link IBrokerTerminal.previewOrder} method to be implemented and `confirmId` parameter to be passed in the {@link IBrokerTerminal.placeOrder} method. * Refer to [Enable order preview](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#add-custom-fields) for more information. * @default false */ supportPlaceOrderPreview?: boolean; /** * Allows providing the estimated commission, fees, margin, and other order information before modifying the order without actually modifying it. * This information will be displayed in the _Order confirmation_ dialog. * * This flag requires the {@link IBrokerTerminal.previewOrder} method to be implemented and `confirmId` parameter to be passed in the {@link IBrokerTerminal.modifyOrder} method. * Refer to [Enable order preview](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#add-custom-fields) for more information. * @default false */ supportModifyOrderPreview?: boolean; /** * Enables trading with leverage. * If the flag is set to `true`, you should calculate the leverage using the {@link IBrokerTerminal.leverageInfo} method. * @default false */ supportLeverage?: boolean; /** * Displays a leverage button in the UI. * Note that you should also enable the {@link BrokerConfigFlags.supportLeverage} flag. * If `supportLeverageButton` is set to `true`, the leverage input field appears in the Order Ticket. * Clicking the input field activates a dedicated Leverage Dialog. * @default true */ supportLeverageButton?: boolean; /** * Enables orders history. * If `supportOrdersHistory` is set to `true`, the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager) will have an additional tab: _Orders History_. * This flag requires the [`ordersHistory`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#ordershistory) method to be implemented. * The method should return a list of orders with the `filled`, `cancelled`, and `rejected` statuses from previous trade sessions. * @default false */ supportOrdersHistory?: boolean; /** * Enables adding brackets to the existing order. * @default true */ supportAddBracketsToExistingOrder?: boolean; /** * Allows getting crypto balances for an account. * Balances are displayed as the first table of the _Account Summary_ tab. * Use the flag for crypto currencies only. * This flag requires the {@link IBrokerConnectionAdapterHost.cryptoBalanceUpdate} method to be implemented. * @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 for a position. * @default false */ supportOnlyPairPositionBrackets?: boolean; /** * `Stop Loss` and `Take Profit` are added or removed only together for an order. * @default false */ supportOnlyPairOrderBrackets?: boolean; /** * Enables cryptocurrency trading (exchanging). * This flag switches the Order Ticket to Crypto Exchange mode, * which provides additional controls for entering the quantity in either the base or quote currency. * @default false */ supportCryptoExchangeOrderTicket?: boolean; /** * Enables displaying Profit & Loss values in instrument currency. * @default false */ positionPLInInstrumentCurrency?: boolean; /** * Enables the display of Risk in Currency control value in instrument currency for brackets. * @default false */ showRiskInInstrumentCurrency?: boolean; /** * Enables [partial position closing](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#partial-closing). * This flag requires the {@link IBrokerTerminal.closePosition} method to be implemented. * @default false */ supportPartialClosePosition?: boolean; /** * Enables [partial individual position closing](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#partial-closing). * This flag requires the {@link IBrokerTerminal.closeIndividualPosition} method to be implemented. * @default false */ supportPartialCloseIndividualPosition?: boolean; /** * Modifies the confirmation dialog text for closing a bracket order. * When set to `true`, the text explicitly states that cancelling a bracket order will also cancel its associated pair. * When set to `false`, the text will include the ID of the singular bracket order being cancelled. * * Note that the library does not cancel orders itself. * You should implement the {@link IBrokerTerminal.cancelOrder} or {@link IBrokerTerminal.cancelOrders } method. * @default false */ supportCancellingBothBracketsOnly?: boolean; /** * Enables crypto brackets. * @default false */ supportCryptoBrackets?: boolean; /** * Enables the _Notifications log_ tab in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/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 Ticket. * @default false */ supportStopOrdersInBothDirections?: boolean; /** * Whether stop-limit orders should behave like Limit-if-Touched in both directions. * Enabling this flag prevents the check of stop price direction from the stop limit Order Ticket. */ supportStopLimitOrdersInBothDirections?: boolean; /** * Whether the integration supports limit price validation in the order ticket to eliminate the possibility to place * an order on the wrong side of the market that will most likely trigger and get filled immediately. */ supportStrictCheckingLimitOrderPrice?: boolean; /** * If set to `true`, executions are displayed on the chart. * This flag requires the [`executions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#executions) method to be implemented. * @default true */ supportExecutions?: boolean; /** * Allows modifying order type. * @default false */ supportModifyOrderType?: boolean; /** * Enables closing of individual positions in FIFO order. * @default false */ requiresFIFOCloseIndividualPositions?: boolean; /** * Allows brokers to add their own parameters that will be displayed in Order info. * @default false */ supportCustomOrderInfo?: boolean; /** * Allows brokers to send position closing information that will be displayed in Close Position Dialog * @default false */ supportPreviewClosePosition?: boolean; } export interface BrokerCustomUI { /** * Shows Order Ticket 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|IndividualPosition} 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 | IndividualPosition, 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|IndividualPosition} position - position to be closed */ showClosePositionDialog?: (position: Position | IndividualPosition) => Promise; /** * Shows the Reverse Position Dialog. * @param {Position} position - position to be reversed */ showReversePositionDialog?: (position: Position) => Promise; } 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 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 ClosePositionPreviewResult { id?: string; rows: ClosePositionPreviewRow[]; disclaimer?: string | MarkupText; } export interface ClosePositionPreviewRowData { title: string; value?: string; currency?: string; } export interface ClosePositionPreviewSeparator { type: "separator"; } 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 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 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; } 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; /** Allow usage of priceFormatter */ isPriceFormatterNeeded?: boolean; } /** * 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 DefaultContextMenuActionsParams { } export interface DefaultDropdownActionsParams { /** Show trading properties */ tradingProperties?: boolean; /** Restore confirmations */ restoreConfirmations?: boolean; } export interface DisconnectionInfo { message?: string; heading?: string; additionalInfo?: string; disconnectType?: DisconnectType; } export interface ErrorFormatterParseResult extends FormatterParseResult { /** Optional message when there's an error while parsing */ error?: string; /** @inheritDoc */ res: false; } /** * Describes a single execution. * Execution is when a buy or sell order is completed for a financial instrument. */ 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; } /** * Format options */ export interface FormatterFormatOptions { /** * Ignore locale number format settings like decimal/thousands separators */ ignoreLocaleNumberFormat?: boolean; } /** * Format options */ export interface FormatterParseOptions { /** * Ignore locale number format settings like decimal/thousands separators */ ignoreLocaleNumberFormat?: boolean; } export interface FormatterParseResult { /** Returns if the formatter support parsing */ res: boolean; } export interface HyperlinkInfo { text: string; url: string; } 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 IBrokerAccountInfo { /** * The library calls `accountsMetainfo` to get a list of accounts for a particular user. * The method should return an array that contains an ID and name for each account. * * Note that if `accountsMetainfo` returns an array containing more than one element, you should implement the {@link setCurrentAccount} method. * Refer to [Multiple accounts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/multiple-accounts) for more information. */ accountsMetainfo(): Promise; /** * The library calls `currentAccount` to get the current account's ID. */ currentAccount(): AccountId; /** * The library calls `setCurrentAccount` when users switch accounts using the drop-down menu in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager). * This method provides your backend server with the ID of the selected account. * * Note that `setCurrentAccount` is required if {@link accountsMetainfo} returns an array containing more than one element. * Refer to [Multiple accounts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/multiple-accounts) for more information. * @param {AccountId} id - The ID of the selected account. */ setCurrentAccount?(id: AccountId): void; } export interface IBrokerCommon { /** * The library calls `chartContextMenuActions` when users open the [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) on the chart. * This method also renders the *Trade* button 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 - A context object passed by the library. * @param {DefaultContextMenuActionsParams} [options] - Default options for the context menu action parameters. * @returns A promise that resolves to an array of {@link ActionMetaInfo}, which may be empty. In that case, the *Trade* button will * be removed from the context menu. */ chartContextMenuActions(context: TradeContext, options?: DefaultContextMenuActionsParams): Promise; /** * The library calls `isTradable` to check if a symbol can be traded. * If the method returns `false`, users will see the *Non-tradable symbol* message in the UI when creating orders. * You can also display a custom message with the reason why the symbol cannot be traded and the possible solution to resolve the issue. * To do this, return an `IsTradableResult` object. * @param {string} symbol - The symbol identifier. */ isTradable(symbol: string): Promise; /** * Defines a connection status for the Broker API. * If any other value than `1` ("Connected") is returned, the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager) will display an endless spinner instead of users' trading data. * If you want to handle other scenarios, for example when the status is disconnected, you need to manage this scenario within your implementation and use the {@link IBrokerConnectionAdapterHost.connectionStatusUpdate} method. * * If the method is not implemented or returns a value other than `1`, * the following error will appear in the console: *Method connectionStatus is not properly implemented*. */ connectionStatus(): ConnectionStatus; /** * The library calls `orders` to request data on the user's active orders. This data is displayed on the _Orders and Positions_ pages of the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#orders-and-positions). */ orders(): Promise; /** * The library calls `ordersHistory` to request orders history. * It is expected that returned orders will have a final status (`rejected`, `filled`, `cancelled`). * * This method is only required when you set the {@link BrokerConfigFlags.supportOrdersHistory} flag to `true`. * This flag adds the *History* page, where order history is displayed, to the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager). * Refer to the [History](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#history) section for more information. */ ordersHistory?(): Promise; /** * Called by Trading Platform to request [positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions). * Required if the {@link BrokerConfigFlags.supportPositions} flag is set to `true`. */ positions?(): Promise; /** * Called by Trading Platform to request [individual positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions). * Required if the {@link BrokerConfigFlags.supportPositionNetting} flag is set to `true`. */ individualPositions?(): Promise; /** * The library calls `executions` to request executions for the specified symbol. * If you want executions to be displayed on the chart, set the {@link BrokerConfigFlags.supportExecutions} to `true`. * @param {string} symbol - The symbol identifier. */ executions(symbol: string): Promise; /** * The library calls `symbolInfo` to request symbol information for the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) and [Depth of Market widget](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market). * @param {string} symbol - The symbol identifier. */ symbolInfo(symbol: string): Promise; /** * The library calls `accountManagerInfo` to get information required for building the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/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 want to [add custom fields](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#add-custom-fields) to the standard Order Ticket. * * 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. * * Use the `symbol` parameter to return customization options for a particular symbol. * @param {string} symbol - symbol identifier */ getPositionDialogOptions?(symbol: string): Promise; /** * Implement this method if you want to have custom options available for different symbols. * @param {string} symbol - symbol identifier */ getSymbolSpecificTradingOptions?(symbol: string): Promise; } 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. For more information on fractional prices, refer to [Fractional format](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#fractional-format). * @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. For more information, refer to [Variable tick size](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#variable-tick-size). */ createPriceFormatter(priceScale?: number, minMove?: number, fractional?: boolean, minMove2?: number, variableMinTick?: string): IPriceFormatter; } /** * The Trading Host is an API for interaction between the Broker API and the library code related to trading. * Its main purpose is to receive information from your backend server where trading logic is implemented and provide updates to the library. * Refer to the [Core trading concepts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts) article for more information. */ export interface IBrokerConnectionAdapterHost { /** Broker Connection Adapter Factory object */ factory: IBrokerConnectionAdapterFactory; /** * Triggers a connection status update throughout the broker by reinvoking {@link IBrokerCommon.connectionStatus}. * @param {ConnectionStatus} status - new connection status to propagate internally to the host * @param {DisconnectionInfo} [info] - additional information to provide when entering a disconnected status */ connectionStatusUpdate(status: ConnectionStatus, info?: DisconnectionInfo): void; /** * 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 to clear the current cache for orders and notify the chart that it needs to request orders again. * Use this method only in cases such as ID mismatches. * For more details, see [Order and position IDs mismatch](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#order-and-position-ids-mismatch). */ ordersFullUpdate(): 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 to clear the current cache for positions and notify the chart that it needs to request positions again. * Use this method only in cases such as ID mismatches. * For more details, see [Order and position IDs mismatch](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#order-and-position-ids-mismatch). */ positionsFullUpdate(): 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 an individual position is added or changed. * @param {IndividualPosition} individualPosition - updated individual position * @param {boolean} [isHistoryUpdate] - whether the change is a history update */ individualPositionUpdate(individualPosition: IndividualPosition, isHistoryUpdate?: boolean): void; /** * Call this method to clear the current cache for individual positions and notify the chart that it needs to request individual positions again. * Use this method only in cases such as ID mismatches. * For more details, see [Order and position IDs mismatch](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#order-and-position-ids-mismatch). */ individualPositionsFullUpdate(): void; /** * Call this method when an individual position has not changed, but fields that you added to the individual position object to display in the Account Manager have changed. * @param {string} id - ID of the updated individual position * @param {Partial} changes - changes to the individual position object */ individualPositionPartialUpdate(id: string, changes: 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 [profit and loss](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss) update. * Use this method when the {@link BrokerConfigFlags.supportPLUpdate} flag is set to `true` in {@link SingleBrokerMetaInfo.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 IBrokerTerminal.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 an individual position [profit and loss](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss) update. * @param {string} individualPositionId - ID of the individual position * @param {number} pl - updated profit / loss for the individual position */ individualPositionPLUpdate(individualPositionId: string, pl: number): void; /** * Call this method when a broker connection has received an equity update. This method is required by the standard Order Ticket 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 Ticket to display the margin meter. * This method should be used when {@link BrokerConfigFlags.supportMargin} is set to `true` in {@link SingleBrokerMetaInfo.configFlags}. * The Trading Platform subscribes to margin available updates using {@link IBrokerTerminal.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 Ticket. * It should be implemented when the {@link BrokerConfigFlags.supportBalances} flag is set to `true` in {@link SingleBrokerMetaInfo.configFlags}. * @param {string} symbol - symbol ID * @param {CryptoBalance} balance - updated crypto balance */ cryptoBalanceUpdate(symbol: string, balance: CryptoBalance): void; /** * Update the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) data for a specified symbol. * @param {string} symbol - symbol identifier * @param {DOMData} equity - Depth of Market data */ domUpdate(symbol: string, equity: DOMData): void; /** * Sets the quantity for a given symbol. * Use this method only when you need to [override the user-specified quantity](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#symbol-quantity-is-overridden) with a new value. * * To specify the default quantity, use the {@link InstrumentInfo.qty} field instead. * @param {string} symbol - symbol * @param {number} quantity - quantity to update */ setQty(symbol: string, quantity: number): void; /** * Returns the quantity for a given symbol. * @param {string} symbol - symbol * @return {Promise} - quantity for the given symbol */ getQty(symbol: string): Promise; /** * Adds a callback to be executed whenever there's a change of quantity for a given symbol. * * Make sure to unsubscribe from these changes using the corresponding {@link unsubscribeSuggestedQtyChange} method. * * @param {string} symbol - symbol to which the callback will be linked to * @param {SuggestedQtyChangedListener} listener - callback */ subscribeSuggestedQtyChange(symbol: string, listener: SuggestedQtyChangedListener): void; /** * Remove a previously added callback from the list. * @param {string} symbol - symbol to remove the callback from * @param {SuggestedQtyChangedListener} listener - callback to be removed */ unsubscribeSuggestedQtyChange(symbol: string, listener: SuggestedQtyChangedListener): void; /** * Shows the Order Ticket * @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 Ticket 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 Ticket 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|IndividualPosition} position - position or individual position * @param {Brackets} brackets - brackets for the position or individual position * @param {OrderTicketFocusControl} focus - input control to focus on when dialog is opened */ showPositionBracketsDialog(position: Position | IndividualPosition, brackets: Brackets, focus: OrderTicketFocusControl): Promise; /** * @deprecated This method will be removed from the library in the next major version. Please use {@link setAccountManagerVisibilityMode} instead. * Activate bottom widget */ activateBottomWidget(): Promise; /** * Method to retrieve the current visibility mode of the Account Manager. */ getAccountManagerVisibilityMode(): IWatchedValueReadonly; /** * Method to set a new visibility mode for the Account Manager. */ setAccountManagerVisibilityMode(mode: BottomWidgetBarMode): void; /** * 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; /** * Retrieves the current value for a specified [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) setting in the ellipsis menu. * * @template K A key of the OrderTicketSettings type. * @param {K} settingName - The name of the Order Ticket setting. * @returns {Promise} A promise that resolves with the value of the specified setting. */ getOrderTicketSetting(settingName: K): Promise; /** * Updates the value of a specified [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) setting in the ellipsis menu. * * @template K A key of OrderTicketSettings type. * @param {K} settingName - The name of the Order Ticket setting to be updated. * @param {OrderTicketSettings[K]} value - The new value to be assigned to the setting. * @returns {Promise} A promise that resolves when the setting is successfully updated. */ setOrderTicketSetting(settingName: K, value: OrderTicketSettings[K]): Promise; } /** * The Broker API is a key component that enables trading. * Its main purpose is to connect TradingView charts with your trading logic. * Refer to the [Core trading concepts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts) article for more information. */ export interface IBrokerTerminal extends IBrokerCommon, IBrokerAccountInfo { /** * The library calls `placeOrder` to request placing an order pre-filled with partial or complete information. * You should handle this request on your backend side. For more information, refer to [Order creation](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts#1-order-creation). * * To display an order preview before placing it, set {@link BrokerConfigFlags.supportPlaceOrderPreview} to `true`. * Refer to [Enable order preview](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-order-preview) for more information. * @param {PreOrder} order - Order information. * @param {string} [confirmId] - The ID of the confirmed order. This parameter is passed if [`supportPlaceOrderPreview`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportplaceorderpreview) is `true`. * @returns {PlaceOrderResult} An object with the order ID. */ placeOrder(order: PreOrder, confirmId?: string): Promise; /** * The library calls `previewOrder` to show an order preview when a user clicks _Buy order_ or _Modify order_ in the Order Ticket. * To [enable order preview](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-order-preview), set the {@link BrokerConfigFlags.supportPlaceOrderPreview} or {@link BrokerConfigFlags.supportModifyOrderPreview} configuration flag to `true`. * * This method returns estimated commission, fees, margin, and other information for the order without it actually being placed. * @param {PreOrder} order - Order information. */ previewOrder?(order: PreOrder): Promise; /** * The library calls `modifyOrder` to request modifying an existing order. * You should handle this request on your backend side and provide the library with a new order state. To do this, call the {@link IBrokerConnectionAdapterHost.orderUpdate} method right afterwards. * Otherwise, the library will return a [timeout issue](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue). * * Note that [market orders](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders#order-types) cannot be modified. * * To enable an order preview before modification, set the {@link BrokerConfigFlags.supportModifyOrderPreview} configuration flag to `true`. * Refer to [Enable order preview](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-order-preview) for more information. * @param {Order} order - Order information. * @param {string} [confirmId] - The ID of the confirmed order. This parameter is passed if [`supportModifyOrderPreview`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportmodifyorderpreview) is `true`. */ modifyOrder(order: Order, confirmId?: string): Promise; /** * The library calls `cancelOrder` to request canceling an order. * You should handle this request on your backend side and provide the library with a new order state. To do this, call the {@link IBrokerConnectionAdapterHost.orderUpdate} method right afterwards. * @param {string} orderId - The ID of the order to cancel. */ cancelOrder(orderId: string): Promise; /** * The library calls `cancelOrders` to request canceling multiple orders for a symbol. * You should handle this request on your backend side and provide the library with a new order states. To do this, call the {@link IBrokerConnectionAdapterHost.orderUpdate} method right afterwards. * * `cancelOrders` is only called when users click the *CXL all* button in the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) widget. * @param {string} symbol - The symbol identifier. * @param {Side|undefined} side - An order side. * @param {string[]} ordersIds - IDs of the orders to cancel. The orders are selected based on the specified `symbol` and `side`. */ cancelOrders?(symbol: string, side: Side | undefined, ordersIds: string[]): Promise; /** * This method is called if the {@link BrokerConfigFlags.supportNativeReversePosition} configuration flag is on. * It allows reversing the position by ID. * * Note that the library expects you to call the {@link IBrokerConnectionAdapterHost.positionUpdate} method right afterwards. * Otherwise, the library will return a [timeout issue](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue). * @param {string} positionId - position */ reversePosition?(positionId: string): Promise; /** * The library calls `closePosition` to request [closing a position](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#close-positions) by ID. * You should handle this request on your backend side and provide the library with a new position state. To do this, call the {@link IBrokerConnectionAdapterHost.positionUpdate} method right afterwards. * Otherwise, the library will return a [timeout issue](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue). * * `closePosition` is only called if the {@link BrokerConfigFlags.supportClosePosition} or {@link BrokerConfigFlags.supportPartialClosePosition} configuration flag is `true`. * @param {string} positionId - The position ID. * @param {number} [amount] - The amount is specified if [`supportPartialClosePosition`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpartialcloseposition) is `true` and the user wants to close only [part of the position](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#partial-closing). * @param {string} [confirmId] - The ID of the confirmed close position preview. This parameter is passed if [`supportPreviewClosePosition`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpreviewcloseposition) is `true`. */ closePosition?(positionId: string, amount?: number, confirmId?: string): Promise; /** * The library calls `closeIndividualPosition` if the {@link BrokerConfigFlags.supportCloseIndividualPosition} or {@link BrokerConfigFlags.supportPartialCloseIndividualPosition} configuration flag is `true`. * `closeIndividualPosition` allows [closing an individual position](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#close-positions) by ID. * * Note that the library expects you to call the {@link IBrokerConnectionAdapterHost.positionUpdate} method right afterwards. * Otherwise, the library will return a [timeout issue](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue). * @param {string} individualPositionId - The individual position ID. * @param {number} [amount] - The amount is specified if `supportPartialCloseIndividualPosition` is `true` and the user wants to close only [part of the individual position](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#partial-closing). * @param {string} [confirmId] - The ID of the confirmed close position preview. This parameter is passed if [`supportPreviewClosePosition`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpreviewcloseposition) is `true`. */ closeIndividualPosition?(individualPositionId: string, amount?: number, confirmId?: string): Promise; /** * The library calls `editPositionBrackets` if the {@link BrokerConfigFlags.supportPositionBrackets} configuration flag is `true`. * It shows a dialog that enables take-profit and stop-loss editing. * * Note that the library expects you to call the {@link IBrokerConnectionAdapterHost.positionUpdate} method right afterwards. * @param {string} positionId - The ID of the 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 the {@link BrokerConfigFlags.supportIndividualPositionBrackets} configuration flag is on. * It displays a dialog that enables take-profit and stop-loss editing. * * Note that the library expects you to call the {@link IBrokerConnectionAdapterHost.positionUpdate} method right afterwards. * @param {string} individualPositionId - ID of existing individual position to be modified * @param {Brackets} brackets - new Brackets to be set for the individual position */ editIndividualPositionBrackets?(individualPositionId: 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 information 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; /** * The method should be implemented if you use the standard Order Ticket 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 Ticket 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; /** * Use this method to enable dynamic updates of the pip value defined in {@link InstrumentInfo.pipValue}. * The pip value is displayed in the *Order info* section of the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) and is used to calculate the trade value and risks. * Once `subscribePipValue` is called, your Broker API implementation should provide pip value updates through the {@link IBrokerConnectionAdapterHost.pipValueUpdate} method. * * If `subscribePipValue` is not implemented, the static value from {@link InstrumentInfo.pipValue} is displayed in the UI. * @param {string} symbol - symbol identifier */ subscribePipValue?(symbol: string): void; /** * The method should be implemented if you use a standard Order Ticket 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 Ticket 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; /** * The method should be implemented if you use the standard Order Ticket and support stop loss. * * Once this method is called the broker should stop providing equity updates. */ unsubscribeEquity?(): void; } export interface IDelegate extends ISubscription { /** Fire (Evoke) */ fire: TFunc; } /** 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, options?: FormatterFormatOptions): string; /** Check if the input value satisfies the logic and return either an error or the result of the parsing */ parse?(value: string, options?: FormatterParseOptions): ErrorFormatterParseResult | SuccessFormatterParseResult; } /** Specific formatter for number */ export interface INumberFormatter extends IFormatter { /** Formatter for a number */ format(value?: number, options?: NumberFormatterFormatOptions): string; /** * Formatter for a price change * @param currentPrice - current price * @param prevPrice - previous price * @param options - format options */ formatChange?(currentPrice: number, prevPrice: number, options?: NumberFormatterFormatOptions): string; } export interface IObservable { /** * Subscribe to changes * @param {(value:T)=>void} callback - callback function to be evoked when observed value changes */ subscribe(callback: ObservableCallback): void; /** * Unsubscribe from changes * @param {(value:T)=>void} callback - callback function to be unsubscribed */ unsubscribe(callback: ObservableCallback): void; } export interface IObservableValue extends IBoxedValue, IObservable { } export interface IObservableValueReadOnly extends IBoxedValueReadOnly, IObservable { } /** * Specific formatter for numbers */ export interface IPriceFormatter extends ISymbolValueFormatter { /** Price formatter */ format(price: number, options?: PriceFormatterFormatOptions): string; /** Price change formatter */ formatChange?(price: number, prevPrice: number, options?: PriceFormatterFormatOptions): string; } /** * 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; } export interface ISymbolValueFormatter extends INumberFormatter { /** Default formatter function used to assign the correct sign (+ or -) to a number */ format(price: number, options?: SymbolValueFormatterFormatOptions): string; /** * Formatter for a price change * @param currentPrice - current price * @param prevPrice - previous price * @param options - format options */ formatChange?(currentPrice: number, prevPrice: number, options?: SymbolValueFormatterFormatOptions): string; } 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; } export interface IndividualPosition extends IndividualPositionBase, CustomFields { } /** * Describes an individual position. */ export interface IndividualPositionBase { /** Individual position ID. Usually id should be equal to brokerSymbol */ id: string; /** Individual position open date (UNIX timestamp in milliseconds) */ date: number; /** Symbol name */ symbol: string; /** Individual position Quantity */ qty: number; /** Individual position Side */ side: Side; /** Individual position price */ price: number; /** Determines whether individual position can be closed */ canBeClosed?: boolean; } export interface InstrumentInfo { /** The default quantity parameters for a symbol. */ qty: QuantityMetainfo; /** * The value of one pip for the instrument, expressed in the account currency. * This value is displayed in the *Order info* section of the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket). * * If set to `0`, the *Order info* section will not be displayed, and there will be no way to show it programmatically. * To ensure the section and the value appears in the UI, set this property to a non-zero value. * * If you implement [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal), use {@link IBrokerTerminal.subscribePipValue} to enable dynamic value updates. */ 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 Order Ticket. */ 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; /** Leverage */ leverage?: string; /** * The margin requirement for the instrument. A 3% margin rate should be represented as 0.03. */ 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 Order Ticket. */ 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 Order Ticket */ 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; /** Supported order types for the instrument */ allowedOrderTypes?: OrderType[]; } /** 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 Order Ticket */ reason?: string; /** Reason heading */ reasonHeading?: string; /** Solution available to user to resolve the issue */ solutions?: TradableSolutions; /** shortReason is displayed in the legend */ shortReason?: 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; } /** Separator for a dropdown or context menu */ export interface MenuSeparator extends ActionDescription { /** Is a menu separator */ separator: boolean; } export interface NegativeBaseInputFieldValidatorResult extends BaseInputFieldValidatorResult { /** @inheritDoc */ valid: false; /** Reason why base input value is invalid */ errorMessage: string; } /** * Number format options */ export interface NumberFormatterFormatOptions extends FormatterFormatOptions { /** * Disable exponential form */ noExponentialForm?: boolean; } /** * Interface for an URL which will be opened */ export interface OpenUrlSolution { /** * Link to be opened */ openUrl: { /** URL to be opened */ url: string; /** text for solution button */ text: string; }; } export interface OrderDialogOptions extends TradingDialogOptions { /** * Using this flag, you can change `Trade Value` to `Total` in the *Order Info* section of the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket). */ showTotal?: boolean; } export interface OrderDuration { /** * type is OrderDurationMetaInfo.value */ type: string; /** Order duration time */ datetime?: number; } /** * Order duration options that determine how long the order remains active. * Refer to [Enable Time in force menu](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-time-in-force-menu) for more information. */ export interface OrderDurationMetaInfo { /** If it is set to `true`, then the Display date control in Order Ticket for this duration type will be displayed. */ hasDatePicker?: boolean; /** If it is set to `true`, then the Display time control in Order Ticket 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 Order Ticket for the first time. */ default?: boolean; /** Localized title of the duration. The title will be displayed in the Duration control of Order Ticket. */ name: string; /** Duration identifier */ value: string; /** A list of order types for which this duration type will be displayed in the Duration control of Order Ticket. 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?: OrderPreviewMessage[]; /** Error messages */ errors?: OrderPreviewMessage[]; } /** * 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 information is not sufficient to place an order. */ export interface OrderTemplate extends OrderTemplateBase { } export interface OrderTemplateBase { /** Symbol identifier */ symbol: string; /** Order Type */ type?: OrderType; /** order / execution side */ side?: Side; /** Order quantity */ qty?: number; /** Type of Stop Order */ stopType?: StopType; /** Current Quotes */ currentQuotes?: AskBid; /** Order stop price */ stopPrice?: number; /** Order limit price */ limitPrice?: number; /** Order Take Profit (Brackets) */ takeProfit?: number; /** Order Stop loss (Brackets) */ stopLoss?: number; /** Order Guaranteed Stop loss (Brackets) */ guaranteedStop?: number; /** Order Trailing stop (Brackets) */ trailingStopPips?: number; /** Duration or expiration of an order */ duration?: OrderDuration; /** Custom input fields */ customFields?: CustomInputFieldsValues; } /** * Settings for the ellipsis menu of the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket). You can read and adjust these settings using the * {@link IBrokerConnectionAdapterHost.getOrderTicketSetting} and * {@link IBrokerConnectionAdapterHost.setOrderTicketSetting} methods. */ export interface OrderTicketSettings { /** If true, the "Show Order Price in Ticks" setting is displayed. */ showRelativePriceControl: boolean; /** If true, the "Show order confirmations" setting is displayed. */ showOrderPreview: boolean; } export interface PipValues { /** The value of one pip for buy orders, expressed in account currency. */ buyPipValue: number; /** The value of one pip for sell orders, expressed in account currency. */ sellPipValue: number; } export interface PlaceOrderResult { /** Order id - this is mainly used for debugging purpose */ orderId?: string; } export interface PlacedOrder extends PlacedOrderBase, CustomFields { } /** * An object that contains information 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; /** Guaranteed stop loss price (double). Available when Brackets are enabled and supportGuaranteedStop flag is set to true */ guaranteedStop?: 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 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; /** * The weighted average price of all positions for a symbol. * The library uses this value to draw a position line on the chart and to calculate [profit and loss values](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss). */ avgPrice: number; /** Last update time (unix timestamp in milliseconds) */ updateTime?: number; /** Message describing the state of the position */ message?: OrderOrPositionMessage; } export interface PositionDialogOptions extends TradingDialogOptions { } 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 information is sufficient to place an order. */ export interface PreOrder extends OrderTemplateBase { /** @inheritDoc */ symbol: string; /** @inheritDoc */ type: OrderType; /** @inheritDoc */ side: Side; /** @inheritDoc */ qty: number; /** * It is set to `true`, if the order closes a position. */ isClose?: boolean; } export interface PriceFormatterFormatOptions extends SymbolValueFormatterFormatOptions { /** Add `tailSize` digits to fractional part of result string */ tailSize?: number; /** Add minus sign to result string */ signNegative?: boolean; /** Use Right to left format */ useRtlFormat?: boolean; /** Cuts price by priceScalePrecision, without rounding */ cutFractionalByPrecision?: boolean; /** Remove all trailing zeroes in decimal part */ removeAllEndingZeros?: boolean; } /** * 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 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 order duration options that determine how long the order remains active. * Specifying `durations` enables a drop-down menu in the Order Ticket for supported orders. * Refer to [Enable Time in force menu](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-time-in-force-menu) for more information. * * The objects have the following keys: `{ name, value, hasDatePicker?, hasTimePicker?, default?, supportedOrderTypes? }`. */ durations?: OrderDurationMetaInfo[]; /** * Order Rules */ orderRules?: OrderRule[]; /** * This optional field can be used to replace the standard Order Ticket and the Add Protection dialogs with your own. * Values of the following two fields are functions that are called by the Trading Platform 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 | IndividualPosition, brackets: Brackets, focus?: OrderTicketFocusControl) => Promise; * showCancelOrderDialog?: (order: Order) => Promise; * showClosePositionDialog?: (position: Position | IndividualPosition) => 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; } /** * The interface that describes the mapping of values in the {@link AccountManagerColumnBase.formatter} and {@link AccountManagerColumnBase.dataFields} properties of the Account Manager columns. * Refer to the [Value formatters](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters) section for more information. */ /* eslint-disable jsdoc/require-jsdoc */ export interface StandardFormattersDependenciesMapping { [StandardFormatterName.Default]: string[]; [StandardFormatterName.Symbol]: SymbolFormatterProperties[keyof SymbolFormatterProperties]; [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.FormatPriceInCurrency]: [ priceProperty: string, currencyProperty: 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.FixedInCurrency]: [ valueProperty: string, currencyProperty: 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.ProfitInPercent]: [ plPercent: string ]; [StandardFormatterName.Percentage]: [ valueProperty: string ]; [StandardFormatterName.MarginPercent]: [ valueProperty: string ]; [StandardFormatterName.Empty]: [ ]; } /* eslint-enable jsdoc/require-jsdoc */ 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; } export interface SymbolFormatterProperties { base: [ brokerSymbolProperty: string, symbolProperty: string ]; withMessage: [ brokerSymbolProperty: string, symbolProperty: string, messageProperty: string ]; } export interface SymbolSpecificTradingOptions { /** Array of strings with valid duration values. You can check that in Order Ticket. */ allowedDurations?: string[]; /** Supported order types for the instrument. */ allowedOrderTypes?: OrderType[]; /** * Whether order brackets are supported for the symbol. * Defaults to the value in the config. */ supportOrderBrackets?: boolean; /** * Whether brackets could be set in ticks/pips. * @default true */ supportBracketsInPips?: boolean; /** * Using this flag you can disable adding brackets to the existing order. */ supportAddBracketsToExistingOrder?: boolean; /** * Using this flag you can disable existing order's brackets modification. If you set it to `false`, * additional fields will be disabled in Order Ticket on the chart, */ supportModifyBrackets?: boolean; /** * Whether position brackets are supported for the symbol. * Defaults to the value in the config. */ supportPositionBrackets?: boolean; /** * Whether trade brackets are supported for the symbol. * Defaults to the value in the config. */ supportIndividualPositionBrackets?: boolean; /** * Whether position reversing is supported for the symbol. * Defaults to the value in the config. */ supportReversePosition?: boolean; /** * A symbol-specific message that can be used to warn users. */ warningMessage?: string; /** * Whether the integration supports the modification of existing position brackets. */ supportModifyPositionBrackets?: boolean; /** * Whether the integration supports the modification of existing order brackets. */ supportModifyOrderBrackets?: boolean; /** * Whether the risk controls and order info should be shown. */ supportRiskControlsAndInfo?: boolean; } export interface SymbolValueFormatterFormatOptions extends NumberFormatterFormatOptions { /** Add plus sign to result string */ signPositive?: boolean; } 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; } export interface TextFieldMetaInfo extends CustomInputFieldMetaInfo { /** @inheritDoc */ inputType: "TextField"; /** @inheritDoc */ value: string; /** @inheritDoc */ validator?: TextInputFieldValidator; /** @inheritDoc */ maskWithAsterisk?: boolean; } 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; } export interface TradableSolutionsTypes { changeAccountSolution: ChangeAccountSolution; changeSymbolSolution: ChangeSymbolSolution; openUrlSolution: OpenUrlSolution; } 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 TradingDialogOptions { /** Custom fields that are displayed in the Order Ticket. * Refer to the [Add custom fields](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#add-custom-fields) section for more information. * * **Example** * ```javascript * customFields: [ * { * inputType: 'TextWithCheckBox', * id: '2410', * title: 'Digital Signature', * placeHolder: 'Enter your personal digital signature', * value: { * text: '', * checked: false, * }, * customInfo: { * asterix: true, * checkboxTitle: 'Save', * }, * } * ] * ``` * */ 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 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 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 CellAlignment = "left" | "right"; export type ClosePositionPreviewRow = ClosePositionPreviewRowData | ClosePositionPreviewSeparator; export type CustomFieldPossibleTypes = "TextWithCheckBox" | "ComboBox" | "Checkbox" | "TextField"; /** * A function that takes an {@link TableFormatterInputs} object and returns a `string` or an `HTMLElement`. */ export type CustomTableFormatElementFunction = (inputs: TableFormatterInputs) => undefined | string | HTMLElement; export type FormatterName = Nominal; /** * 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" | "ca_ES" | "en" | "fr" | "de" | "he_IL" | "id_ID" | "it" | "ja" | "ko" | "pl" | "pt" | "ru" | "es" | "sv" | "th" | "tr" | "vi" | "ms_MY" | "zh_TW"; export type LeverageParams = LeverageInfoParams | LeverageSetParams; export type MarkupText = (string | HyperlinkInfo)[]; export type ObservableCallback = (value: T) => void; export type Order = PlacedOrder | BracketOrder; export type OrderPreviewMessage = string | MarkupText; 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 SuggestedQtyChangedListener = (newQty: number) => void; export type SymbolType = "stock" | "index" | "forex" | "futures" | "bitcoin" | "crypto" | "undefined" | "expression" | "spread" | "cfd" | "economic" | "equity" | "dr" | "bond" | "right" | "warrant" | "fund" | "structured" | "commodity" | "fundamental" | "spot" | "swap" | "option" | "ndf"; /** * 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; /** * `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 * - `openUrl` - the object with URL to be opened and text for solution button */ export type TradableSolutions = TradableSolutionsTypes[keyof TradableSolutionsTypes]; export type TradingDialogCustomField = CheckboxFieldMetaInfo | TextWithCheckboxFieldMetaInfo | CustomComboBoxMetaInfo | TextFieldMetaInfo; export type WatchedValueCallback = (value: T) => void; export as namespace TradingView; export {}; File: charting_library.d.ts ============================ /** * TradingView Advanced Charts * @packageDocumentation * @module Charting Library */ // Generated by dts-bundle-generator v9.5.1 declare const LINESTYLE_DASHED = 2; declare const LINESTYLE_DOTTED = 1; declare const LINESTYLE_SOLID = 0; /* eslint-disable jsdoc/require-jsdoc */ declare const dateFormatFunctions: { readonly "qq 'yy": (date: Date, local: boolean) => string; readonly "qq yyyy": (date: Date, local: boolean) => string; readonly "dd MMM 'yy": (date: Date, local: boolean) => string; readonly "MMM 'yy": (date: Date, local: boolean) => string; readonly "MMM dd, yyyy": (date: Date, local: boolean) => string; readonly "MMM 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 */ export declare const enum ColorType { Solid = "solid", Gradient = "gradient" } export declare const enum DisconnectType { LogOut = 0, FailedRestoring = 1, Offline = 2, APIError = 3, TwoFactorRequired = 4, CancelAuthorization = 5, TimeOutForAuthorization = 6, OauthError = 7, BrokenConnection = 8, Reconnect = 9, FailedSignIn = 10 } export declare const enum PlotSymbolSize { Auto = "auto", Tiny = "tiny", Small = "small", Normal = "normal", Large = "large", Huge = "huge" } export declare const enum StopType { StopLoss = 0, TrailingStop = 1, GuaranteedStop = 2 } export declare const enum BottomWidgetBarMode { Minimized = "minimized", Normal = "normal", Maximized = "maximized" } export declare const enum PaneSize { Tiny = "tiny", Small = "small", Medium = "medium", Large = "large" } export declare const enum PropertyKeyType { DefaultsKey = 1, StateKey = 2, TemplateKey = 4 } export declare const enum SearchInitiationPoint { SymbolSearch = "symbolSearch", Watchlist = "watchlist", Compare = "compare", IndicatorInputs = "indicatorInputs" } export declare const widget: ChartingLibraryWidgetConstructor; export declare enum ActionId { ChartAddIndicatorToAllCharts = "Chart.AddIndicatorToAllCharts", ChartAddSymbolToWatchList = "Chart.AddSymbolToWatchList", ChartApplyIndicatorsToAllCharts = "Chart.ApplyIndicatorsToAllCharts", ChartIndicatorAddFavorites = "Chart.Indicator.AddFavorites", 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", ChartDialogsShowGeneralScalesTab = "Chart.Dialogs.ShowGeneralSettings.ScalesTab", 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", ChartLegendToggleLastDayChangeValuesVisibility = "Chart.Legend.ToggleLastDayChangeValuesVisibility", 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", ChartLinesTogglePrePostMarketPriceLineVisibility = "Chart.Lines.TogglePrePostMarketPriceLineVisibility", ChartLinesToggleSeriesPrevCloseLineVisibility = "Chart.Lines.ToggleSeriesPrevCloseLineVisibility", ChartLinesToggleSeriesPriceLineVisibility = "Chart.Lines.ToggleSeriesPriceLineVisibility", ChartLineToolBarsPatternToggleFlipped = "Chart.LineTool.BarsPattern.ToggleFlipped", ChartLineToolBarsPatternToggleMirrored = "Chart.LineTool.BarsPattern.ToggleMirrored", ChartLineToolRiskRewardReverse = "Chart.LineTool.RiskReward.Reverse", 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", ChartDataWindowShow = "Chart.DataWindow.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", ChartSelectedObjectInsertRowTable = "Chart.SelectedObject.InsertRowTable", ChartSelectedObjectInsertColumnTable = "Chart.SelectedObject.InsertColumnTable", ChartSelectedObjectRemoveRowTable = "Chart.SelectedObject.RemoveRowTable", ChartSelectedObjectRemoveColumnTable = "Chart.SelectedObject.RemoveColumnTable", ChartSelectedObjectToggleLocked = "Chart.SelectedObject.ToggleLocked", ChartSelectedObjectToggleAnchored = "Chart.SelectedObject.ToggleAnchored", 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", ChartSourceResetInputPoints = "Chart.Source.ResetInputPoints", 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", TradingAddOrder = "Trading.AddOrder", TradingCancelOrder = "Trading.CancelOrder", TradingClosePosition = "Trading.ClosePosition", TradingCustomActionId = "Trading.CustomActionId", TradingDOMPlaceLimitOrder = "Trading.DOMPlaceLimitOrder", TradingDOMPlaceMarketOrder = "Trading.DOMPlaceMarketOrder", TradingDOMPlaceStopLimitOrder = "Trading.DOMPlaceStopLimitOrder", TradingDOMPlaceStopOrder = "Trading.DOMPlaceStopOrder", TradingEditOrder = "Trading.EditOrder", TradingModifyPosition = "Trading.ModifyPosition", TradingReversePosition = "Trading.ReversePosition", TradingSellBuyButtonsToggleVisibility = "Trading.SellBuyButtonsToggleVisibility", TradingTradeFromChart = "Trading.TradeFromChart", TradingNoOverlapMode = "Trading.NoOverlapMode", WatchlistAddSelectedSymbolsToCompare = "Watchlist.AddSelectedSymbolsToCompare ", WatchlistAddSymbolToCompare = "Watchlist.AddSymbolToCompare", WatchlistAddSymbolToSection = "Watchlist.AddSymbolToSection", WatchlistAddSymbol = "Watchlist.AddSymbol", WatchlistRemoveSection = "Watchlist.RemoveSection", WatchlistRenameSection = "Watchlist.RenameSection" } export declare 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, LineWithMarkers = 14, Stepline = 15, HLCArea = 16, VolCandle = 19, HLCBars = 21 } /** * Mode to clear the marks on the chart. */ export declare enum ClearMarksMode { /** Will clear both bar marks AND timescale marks - default value */ All = 0, /** Will only clear bar marks */ BarMarks = 1, /** Will only clear timescale marks */ TimeScaleMarks = 2 } export declare enum ConnectionStatus { Connected = 1, Connecting = 2, Disconnected = 3, Error = 4 } /** * Filled area type. */ export declare enum FilledAreaType { /** * Filled area type for plots. */ TypePlots = "plot_plot", /** * Filled area type for bands. */ TypeHlines = "hline_hline" } /** * Histogram Direction. * * Will determine which side of the chart that the histogram appears on. */ export declare enum HHistDirection { LeftToRight = "left_to_right", RightToLeft = "right_to_left" } /** * An enum describing a plot style. */ export 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 } /** * A line style. */ export declare enum LineStyle { /** * Solid line style. */ Solid = 0, /** * Dotted line style. */ Dotted = 1, /** * Dashed line style. */ Dashed = 2 } export declare enum MarkLocation { AboveBar = "AboveBar", BelowBar = "BelowBar", Top = "Top", Bottom = "Bottom", Right = "Right", Left = "Left", Absolute = "Absolute", AbsoluteUp = "AbsoluteUp", AbsoluteDown = "AbsoluteDown" } /** * Market status for the symbol. */ export declare enum MarketStatus { Open = "market", Pre = "pre_market", Post = "post_market", Close = "out_of_session", Holiday = "holiday" } export declare enum MenuItemType { Separator = "separator", Action = "action" } export declare enum NotificationType { Error = 0, Success = 1 } export declare enum OhlcStudyPlotStyle { OhlcBars = "ohlc_bars", OhlcCandles = "ohlc_candles" } export declare enum OrderOrPositionMessageType { Information = "information", Warning = "warning", Error = "error" } export declare enum OrderStatus { Canceled = 1, Filled = 2, Inactive = 3, Placing = 4, Rejected = 5, Working = 6 } export declare enum OrderStatusFilter { All = 0, Canceled = 1, Filled = 2, Inactive = 3, Rejected = 5, Working = 6 } export declare enum OrderTicketFocusControl { LimitPrice = 1, StopPrice = 2, TakeProfit = 3, StopLoss = 4, Quantity = 5 } export declare enum OrderType { Limit = 1, Market = 2, Stop = 3, StopLimit = 4 } /** * Plot line style */ export declare enum OverrideLineStyle { /** * Solid line style. */ Solid = 0, /** * Dotted line style. */ Dotted = 1, /** * Dashed line style. */ Dashed = 2 } /** * Last value label mode. */ export declare enum OverridePriceAxisLastValueMode { /** * Price and % value. */ LastPriceAndPercentageValue = 0, /** * Value according to scale. */ LastValueAccordingToScale = 1 } export declare enum ParentType { Order = 1, Position = 2, IndividualPosition = 3 } export declare enum PlDisplay { Money = 0, Pips = 1, Percentage = 2 } export declare 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 enum SeriesType { Bars = 0, Candles = 1, Line = 2, Area = 3, HeikenAshi = 8, HollowCandles = 9, Baseline = 10, HiLo = 12, Column = 13, LineWithMarkers = 14, Stepline = 15, HLCArea = 16, VolCandle = 19, HLCBars = 21, Renko = 4, Kagi = 5, PointAndFigure = 6, LineBreak = 7 } export declare enum Side { Buy = 1, Sell = -1 } /** * Enumeration of the built-in formatters for the Account Manager columns. * Refer to the [Value formatters](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters) section for more information. */ export declare enum StandardFormatterName { Date = "date", DateOrDateTime = "dateOrDateTime", Default = "default", Fixed = "fixed", FixedInCurrency = "fixedInCurrency", VariablePrecision = "variablePrecision", FormatQuantity = "formatQuantity", FormatPrice = "formatPrice", FormatPriceForexSup = "formatPriceForexSup", FormatPriceInCurrency = "formatPriceInCurrency", IntegerSeparated = "integerSeparated", LocalDate = "localDate", LocalDateOrDateTime = "localDateOrDateTime", Percentage = "percentage", Pips = "pips", Profit = "profit", ProfitInInstrumentCurrency = "profitInInstrumentCurrency", ProfitInPercent = "profitInPercent", Side = "side", PositionSide = "positionSide", Status = "status", Symbol = "symbol", Text = "text", Type = "type", MarginPercent = "marginPercent", Empty = "empty" } export declare 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 enum StudyPlotDisplayTarget { None = 0, Pane = 1, DataWindow = 2, PriceScale = 4, StatusLine = 8, All = 15 } export declare 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 enum StudyTargetPriceScale { Right = 0, Left = 1, NoScale = 2 } export declare enum TimeFrameType { PeriodBack = "period-back", TimeRange = "time-range" } export declare enum TimeHoursFormat { TwentyFourHours = "24-hours", TwelveHours = "12-hours" } export declare enum TradedGroupHorizontalAlignment { Left = 0, Center = 1, Right = 2 } export declare enum VisibilityType { AlwaysOn = "alwaysOn", VisibleOnMouseOver = "visibleOnMouseOver", AlwaysOff = "alwaysOff" } /** * 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; }; /** * Override properties for the Abcd drawing tool. */ export interface AbcdLineToolOverrides { /** Default value: `false` */ "linetoolabcd.bold": boolean; /** Default value: `#089981` */ "linetoolabcd.color": string; /** Default value: `12` */ "linetoolabcd.fontsize": number; /** Default value: `false` */ "linetoolabcd.italic": boolean; /** Default value: `2` */ "linetoolabcd.linewidth": number; /** Default value: `#ffffff` */ "linetoolabcd.textcolor": string; } /** * Overrides for the 'Accelerator Oscillator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface AcceleratorOscillatorIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `histogram` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#000080` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * 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 properties for the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager) pages. */ 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; /** Unique column identifier. */ id: string; /** * Defines a formatter to be applied for data formatting, which can either belong to the `StandardFormatterName` or `FormatterName` type. * If no specific formatter is set, the value is displayed as is. * * Default formatter names are enumerated in {@link StandardFormatterName}. * Refer to the [Built-in formatters](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters#built-in-formatters) section to see the full list of formatters. * * You can also create custom formatters using the {@link AccountManagerInfo.customFormatters} property. */ formatter?: TFormatterName; /** * The `dataFields` array contains fields from an order/position data object. * `dataFields` is used to generate the values displayed in a column. * The displayed value in the column updates only when the corresponding values in the data object change. * * If no {@link formatter} is specified, the displayed values will be space-separated in the column. * When a `formatter` is defined, it processes only the specified values. * If an empty array is assigned to `dataFields`, the `formatter` will receive the entire data object. * * **Example** * * - For a column with `dataFields` set as `['avgPrice', 'qty']`, the displayed value updates only when the `avgPrice` or `qty` values in the data object change. * - For a column with an empty `dataFields` array, the displayed value updates if any values in the data object change. */ dataFields: TFormatterName extends StandardFormatterName ? StandardFormattersDependenciesMapping[TFormatterName] : string[]; /** * Data object key that is used for data sorting. * * If `sortProp` is not provided, the first element of the `dataFields` array will be used. * If the `dataFields` array is empty, the 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`](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters#formatPrice) * and [`StandardFormatterName.FormatPriceForexSup`](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters#formatPriceForexSup) formatters to highlight the changes of the field. * If `highlightDiff is `true`, the custom formatters will also get previous values. */ highlightDiff?: boolean; /** Setting `notHideable` to `true` prevents the column from being hidden. */ notHideable?: boolean; /** Setting `hideByDefault` to `true` hides 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; /** Setting `showZeroValues` to `true` hides any zero values. The default value is `true`. */ showZeroValues?: boolean; } /** * The information object that is used to build the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager). */ export interface AccountManagerInfo { /** Name of the broker */ accountTitle: string; /** * Custom fields that are always displayed at the top-right corner of the Account Manager. * Refer to the [Account Summary row](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#account-summary-row) section for more information. */ summary: AccountManagerSummaryField[]; /** * An optional array for defining [custom formatters](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters#custom-formatters). * Each formatter description is an object with the following fields: * * - `name` ({@link FormatterName}): Unique formatter name. * * - `formatText` ({@link TableFormatTextFunction}): * Function that is used for formatting a cell value to a string. * The `formatText` field is required because it is used to generate exported data. * You can return an empty string if you do not need this function. * * - `formatElement` ({@link CustomTableFormatElementFunction} | `undefined`): * Optional function that is used for formatting a cell value to a string or an HTML element. * * If the `formatElement` function is provided, it only handles the formatting of displayed values. * Otherwise the `formatText` function is used. * For optimal performance, it is recommended to only use `formatText` if you intend to display only string values. * * **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[]; /** An array of data objects that create columns for the [Orders](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#orders-and-positions) 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; /** * An array of data objects that create columns for the [History](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#history) page where all orders from previous sessions are shown. * Note that this page is only shown * if you set the {@link BrokerConfigFlags.supportOrdersHistory} to `true` * and implement the [`ordersHistory`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#ordershistory) method. */ historyColumns?: AccountManagerColumn[]; /** Optional sorting of the table on the [History](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#history) page. */ historyColumnsSorting?: SortingParameters; /** * An array of data objects that create columns for the [Positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#orders-and-positions) page. * 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 an {@link IndividualPosition} * or add your own fields to an individualPosition object and display them. */ individualPositionColumns?: AccountManagerColumn[]; /** Adds [custom pages](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#custom-pages) to the Account Manager. Each page 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; /** * A function for creating a custom [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) for positions and orders in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager). * @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[]; /** Controls whether the number of items is displayed on a custom page. Set to `true` to display the count, or `false` to hide it. */ displayCounterInTab?: boolean; } /** 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; /** An optional parameter with text explaining the contents of this field. */ informerMessage?: string; } /** * 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>; /** This delegate is used to watch the data deletions and update the table. * Pass the id of the row that needs to be deleted to the `fire` method of the delegate. */ deleteDelegate?: ISubscription<(id: string) => 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 AccountMetainfo { /** * Account ID */ id: AccountId; /** * Account Name */ name: string; /** * Account Type */ type?: "live" | "demo"; /** * Currency */ currency?: string; /** * Currency Sign (Prefix) */ currencySign?: string; } /** * Overrides for the 'Accumulation/Distribution' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface AccumulationDistributionIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Accumulative Swing Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface AccumulativeSwingIndexIndicatorOverrides { /** Default value: `15` */ "asi.display": number; /** Default value: `0` */ "asi.linestyle": number; /** Default value: `1` */ "asi.linewidth": number; /** Default value: `line` */ "asi.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "asi.trackprice": boolean; /** Default value: `0` */ "asi.transparency": number; /** Default value: `#2196F3` */ "asi.color": string; [key: string]: StudyOverrideValueType; } 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; /** * Text title of an action consisting of several styled sections. If not defined then {@link label} is used instead. */ styledLabel?: StyledText[]; /** * 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; /** * A flag indicating whether the menu should remain open after clicking on the item. * When `true` the menu will remain open. */ doNotCloseOnClick: boolean; /** * This flag indicates that this action is static content only and is not interactive. */ noInteractive?: boolean; } export interface ActionsFactory { /** * Creates an action with provided options. */ createAction: (options: ActionOptions) => IAction; /** * 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) => IAction; /** * Creates a separator item. */ createSeparator: () => ISeparator; } /** * Custom symbol info fields to be shown in the Security 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; } /** * Overrides for the 'Advance/Decline' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface AdvanceDeclineIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Anchored VWAP' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface AnchoredVWAPIndicatorOverrides { /** Default value: `#4caf50` */ "background #1.color": string; /** Default value: `95` */ "background #1.transparency": number; /** Default value: `true` */ "background #1.visible": boolean; /** Default value: `15` */ "vwap.display": number; /** Default value: `#1e88e5` */ "vwap.color": string; /** Default value: `0` */ "vwap.linestyle": number; /** Default value: `1` */ "vwap.linewidth": number; /** Default value: `line` */ "vwap.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "vwap.trackprice": boolean; /** Default value: `0` */ "vwap.transparency": number; /** Default value: `15` */ "lower band #1.display": number; /** Default value: `#4caf50` */ "lower band #1.color": string; /** Default value: `0` */ "lower band #1.linestyle": number; /** Default value: `1` */ "lower band #1.linewidth": number; /** Default value: `line` */ "lower band #1.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lower band #1.trackprice": boolean; /** Default value: `0` */ "lower band #1.transparency": number; /** Default value: `15` */ "lower band #2.display": number; /** Default value: `#808000` */ "lower band #2.color": string; /** Default value: `0` */ "lower band #2.linestyle": number; /** Default value: `1` */ "lower band #2.linewidth": number; /** Default value: `line` */ "lower band #2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lower band #2.trackprice": boolean; /** Default value: `0` */ "lower band #2.transparency": number; /** Default value: `15` */ "lower band #3.display": number; /** Default value: `#00897b` */ "lower band #3.color": string; /** Default value: `0` */ "lower band #3.linestyle": number; /** Default value: `1` */ "lower band #3.linewidth": number; /** Default value: `line` */ "lower band #3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lower band #3.trackprice": boolean; /** Default value: `0` */ "lower band #3.transparency": number; /** Default value: `15` */ "upper band #1.display": number; /** Default value: `#4caf50` */ "upper band #1.color": string; /** Default value: `0` */ "upper band #1.linestyle": number; /** Default value: `1` */ "upper band #1.linewidth": number; /** Default value: `line` */ "upper band #1.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "upper band #1.trackprice": boolean; /** Default value: `0` */ "upper band #1.transparency": number; /** Default value: `15` */ "upper band #2.display": number; /** Default value: `#808000` */ "upper band #2.color": string; /** Default value: `0` */ "upper band #2.linestyle": number; /** Default value: `1` */ "upper band #2.linewidth": number; /** Default value: `line` */ "upper band #2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "upper band #2.trackprice": boolean; /** Default value: `0` */ "upper band #2.transparency": number; /** Default value: `15` */ "upper band #3.display": number; /** Default value: `#00897b` */ "upper band #3.color": string; /** Default value: `0` */ "upper band #3.linestyle": number; /** Default value: `1` */ "upper band #3.linewidth": number; /** Default value: `line` */ "upper band #3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "upper band #3.trackprice": boolean; /** Default value: `0` */ "upper band #3.transparency": number; [key: string]: StudyOverrideValueType; } /** * Override properties for the Anchoredvp drawing tool. */ export interface AnchoredvpLineToolOverrides { /** Default value: `undefined` */ "linetoolanchoredvp.graphics.hhists.histBars2.colors.0": string; /** Default value: `undefined` */ "linetoolanchoredvp.graphics.hhists.histBars2.colors.1": string; /** Default value: `undefined` */ "linetoolanchoredvp.graphics.hhists.histBars2.valuesColor": string; /** Default value: `undefined` */ "linetoolanchoredvp.graphics.hhists.histBarsVA.colors.0": string; /** Default value: `undefined` */ "linetoolanchoredvp.graphics.hhists.histBarsVA.colors.1": string; /** Default value: `undefined` */ "linetoolanchoredvp.graphics.hhists.histBarsVA.valuesColor": string; /** Default value: `undefined` */ "linetoolanchoredvp.graphics.horizlines.pocLines.color": string; /** Default value: `undefined` */ "linetoolanchoredvp.graphics.horizlines.vahLines.color": string; /** Default value: `undefined` */ "linetoolanchoredvp.graphics.horizlines.valLines.color": string; /** Default value: `undefined` */ "linetoolanchoredvp.graphics.polygons.histBoxBg.color": string; /** Default value: `undefined` */ "linetoolanchoredvp.styles.developingPoc.color": string; /** Default value: `undefined` */ "linetoolanchoredvp.styles.developingVAHigh.color": string; /** Default value: `undefined` */ "linetoolanchoredvp.styles.developingVALow.color": string; } /** * Override properties for the Anchoredvwap drawing tool. */ export interface AnchoredvwapLineToolOverrides { /** Default value: `#4caf50` */ "linetoolanchoredvwap.areaBackground.backgroundColor": string; /** Default value: `true` */ "linetoolanchoredvwap.areaBackground.fillBackground": boolean; /** Default value: `95` */ "linetoolanchoredvwap.areaBackground.transparency": number; /** Default value: `#4caf50` */ "linetoolanchoredvwap.filledAreasStyle.Background_1.color": string; /** Default value: `95` */ "linetoolanchoredvwap.filledAreasStyle.Background_1.transparency": number; /** Default value: `true` */ "linetoolanchoredvwap.filledAreasStyle.Background_1.visible": boolean; /** Default value: `Standard Deviation` */ "linetoolanchoredvwap.inputs.Bands Calculation Mode": string; /** Default value: `1` */ "linetoolanchoredvwap.inputs.bands_multiplier": number; /** Default value: `2` */ "linetoolanchoredvwap.inputs.bands_multiplier_2": number; /** Default value: `3` */ "linetoolanchoredvwap.inputs.bands_multiplier_3": number; /** Default value: `true` */ "linetoolanchoredvwap.inputs.calculate_stDev": boolean; /** Default value: `false` */ "linetoolanchoredvwap.inputs.calculate_stDev_2": boolean; /** Default value: `false` */ "linetoolanchoredvwap.inputs.calculate_stDev_3": boolean; /** Default value: `hlc3` */ "linetoolanchoredvwap.inputs.source": string; /** Default value: `0` */ "linetoolanchoredvwap.inputs.start_time": number; /** Default value: `default` */ "linetoolanchoredvwap.precision": string; /** Default value: `#4caf50` */ "linetoolanchoredvwap.styles.LowerBand.color": string; /** Default value: `15` */ "linetoolanchoredvwap.styles.LowerBand.display": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.LowerBand.linestyle": number; /** Default value: `1` */ "linetoolanchoredvwap.styles.LowerBand.linewidth": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.LowerBand.plottype": number; /** Default value: `false` */ "linetoolanchoredvwap.styles.LowerBand.trackPrice": boolean; /** Default value: `0` */ "linetoolanchoredvwap.styles.LowerBand.transparency": number; /** Default value: `#808000` */ "linetoolanchoredvwap.styles.LowerBand_2.color": string; /** Default value: `15` */ "linetoolanchoredvwap.styles.LowerBand_2.display": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.LowerBand_2.linestyle": number; /** Default value: `1` */ "linetoolanchoredvwap.styles.LowerBand_2.linewidth": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.LowerBand_2.plottype": number; /** Default value: `false` */ "linetoolanchoredvwap.styles.LowerBand_2.trackPrice": boolean; /** Default value: `0` */ "linetoolanchoredvwap.styles.LowerBand_2.transparency": number; /** Default value: `#00897b` */ "linetoolanchoredvwap.styles.LowerBand_3.color": string; /** Default value: `15` */ "linetoolanchoredvwap.styles.LowerBand_3.display": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.LowerBand_3.linestyle": number; /** Default value: `1` */ "linetoolanchoredvwap.styles.LowerBand_3.linewidth": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.LowerBand_3.plottype": number; /** Default value: `false` */ "linetoolanchoredvwap.styles.LowerBand_3.trackPrice": boolean; /** Default value: `0` */ "linetoolanchoredvwap.styles.LowerBand_3.transparency": number; /** Default value: `#4caf50` */ "linetoolanchoredvwap.styles.UpperBand.color": string; /** Default value: `15` */ "linetoolanchoredvwap.styles.UpperBand.display": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.UpperBand.linestyle": number; /** Default value: `1` */ "linetoolanchoredvwap.styles.UpperBand.linewidth": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.UpperBand.plottype": number; /** Default value: `false` */ "linetoolanchoredvwap.styles.UpperBand.trackPrice": boolean; /** Default value: `0` */ "linetoolanchoredvwap.styles.UpperBand.transparency": number; /** Default value: `#808000` */ "linetoolanchoredvwap.styles.UpperBand_2.color": string; /** Default value: `15` */ "linetoolanchoredvwap.styles.UpperBand_2.display": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.UpperBand_2.linestyle": number; /** Default value: `1` */ "linetoolanchoredvwap.styles.UpperBand_2.linewidth": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.UpperBand_2.plottype": number; /** Default value: `false` */ "linetoolanchoredvwap.styles.UpperBand_2.trackPrice": boolean; /** Default value: `0` */ "linetoolanchoredvwap.styles.UpperBand_2.transparency": number; /** Default value: `#00897b` */ "linetoolanchoredvwap.styles.UpperBand_3.color": string; /** Default value: `15` */ "linetoolanchoredvwap.styles.UpperBand_3.display": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.UpperBand_3.linestyle": number; /** Default value: `1` */ "linetoolanchoredvwap.styles.UpperBand_3.linewidth": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.UpperBand_3.plottype": number; /** Default value: `false` */ "linetoolanchoredvwap.styles.UpperBand_3.trackPrice": boolean; /** Default value: `0` */ "linetoolanchoredvwap.styles.UpperBand_3.transparency": number; /** Default value: `#1e88e5` */ "linetoolanchoredvwap.styles.VWAP.color": string; /** Default value: `15` */ "linetoolanchoredvwap.styles.VWAP.display": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.VWAP.linestyle": number; /** Default value: `1` */ "linetoolanchoredvwap.styles.VWAP.linewidth": number; /** Default value: `0` */ "linetoolanchoredvwap.styles.VWAP.plottype": number; /** Default value: `false` */ "linetoolanchoredvwap.styles.VWAP.trackPrice": boolean; /** Default value: `0` */ "linetoolanchoredvwap.styles.VWAP.transparency": number; } /** * Override properties for the Arc drawing tool. */ export interface ArcLineToolOverrides { /** Default value: `rgba(233, 30, 99, 0.2)` */ "linetoolarc.backgroundColor": string; /** Default value: `#e91e63` */ "linetoolarc.color": string; /** Default value: `true` */ "linetoolarc.fillBackground": boolean; /** Default value: `2` */ "linetoolarc.linewidth": number; /** Default value: `80` */ "linetoolarc.transparency": number; } export interface AreaStylePreferences { /** Top color of the gradient fill. Must be an RGBA color string (e.g., `"rgba(255, 0, 0, 0.5)"`). */ color1: string; /** Bottom color of the gradient fill. Must be an RGBA color string (e.g., `"rgba(255, 0, 0, 0.5)"`). */ color2: string; /** Line color. Must be a simple color string (e.g., `"red"`, `"#FF0000"`). */ 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; } /** * Overrides for the 'Arnaud Legoux Moving Average' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ArnaudLegouxMovingAverageIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Aroon' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface AroonIndicatorOverrides { /** Default value: `15` */ "upper.display": number; /** Default value: `0` */ "upper.linestyle": number; /** Default value: `1` */ "upper.linewidth": number; /** Default value: `line` */ "upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "upper.trackprice": boolean; /** Default value: `0` */ "upper.transparency": number; /** Default value: `#FB8C00` */ "upper.color": string; /** Default value: `15` */ "lower.display": number; /** Default value: `0` */ "lower.linestyle": number; /** Default value: `1` */ "lower.linewidth": number; /** Default value: `line` */ "lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lower.trackprice": boolean; /** Default value: `0` */ "lower.transparency": number; /** Default value: `#2196F3` */ "lower.color": string; [key: string]: StudyOverrideValueType; } /** * Override properties for the Arrow drawing tool. */ export interface ArrowLineToolOverrides { /** Default value: `false` */ "linetoolarrow.alwaysShowStats": boolean; /** Default value: `false` */ "linetoolarrow.bold": boolean; /** Default value: `false` */ "linetoolarrow.extendLeft": boolean; /** Default value: `false` */ "linetoolarrow.extendRight": boolean; /** Default value: `14` */ "linetoolarrow.fontsize": number; /** Default value: `center` */ "linetoolarrow.horzLabelsAlign": string; /** Default value: `false` */ "linetoolarrow.italic": boolean; /** Default value: `0` */ "linetoolarrow.leftEnd": number; /** Default value: `#2962FF` */ "linetoolarrow.linecolor": string; /** Default value: `0` */ "linetoolarrow.linestyle": number; /** Default value: `2` */ "linetoolarrow.linewidth": number; /** Default value: `1` */ "linetoolarrow.rightEnd": number; /** Default value: `false` */ "linetoolarrow.showAngle": boolean; /** Default value: `false` */ "linetoolarrow.showBarsRange": boolean; /** Default value: `false` */ "linetoolarrow.showDateTimeRange": boolean; /** Default value: `false` */ "linetoolarrow.showDistance": boolean; /** Default value: `false` */ "linetoolarrow.showMiddlePoint": boolean; /** Default value: `false` */ "linetoolarrow.showPercentPriceRange": boolean; /** Default value: `false` */ "linetoolarrow.showPipsPriceRange": boolean; /** Default value: `false` */ "linetoolarrow.showPriceLabels": boolean; /** Default value: `false` */ "linetoolarrow.showPriceRange": boolean; /** Default value: `2` */ "linetoolarrow.statsPosition": number; /** Default value: `#2962FF` */ "linetoolarrow.textcolor": string; /** Default value: `bottom` */ "linetoolarrow.vertLabelsAlign": string; } /** * Override properties for the Arrowmarkdown drawing tool. */ export interface ArrowmarkdownLineToolOverrides { /** Default value: `#CC2F3C` */ "linetoolarrowmarkdown.arrowColor": string; /** Default value: `false` */ "linetoolarrowmarkdown.bold": boolean; /** Default value: `#CC2F3C` */ "linetoolarrowmarkdown.color": string; /** Default value: `14` */ "linetoolarrowmarkdown.fontsize": number; /** Default value: `false` */ "linetoolarrowmarkdown.italic": boolean; /** Default value: `true` */ "linetoolarrowmarkdown.showLabel": boolean; } /** * Override properties for the Arrowmarker drawing tool. */ export interface ArrowmarkerLineToolOverrides { /** Default value: `#1E53E5` */ "linetoolarrowmarker.backgroundColor": string; /** Default value: `true` */ "linetoolarrowmarker.bold": boolean; /** Default value: `16` */ "linetoolarrowmarker.fontsize": number; /** Default value: `false` */ "linetoolarrowmarker.italic": boolean; /** Default value: `#1E53E5` */ "linetoolarrowmarker.textColor": string; } /** * Override properties for the Arrowmarkleft drawing tool. */ export interface ArrowmarkleftLineToolOverrides { /** Default value: `#2962FF` */ "linetoolarrowmarkleft.arrowColor": string; /** Default value: `false` */ "linetoolarrowmarkleft.bold": boolean; /** Default value: `#2962FF` */ "linetoolarrowmarkleft.color": string; /** Default value: `14` */ "linetoolarrowmarkleft.fontsize": number; /** Default value: `false` */ "linetoolarrowmarkleft.italic": boolean; /** Default value: `true` */ "linetoolarrowmarkleft.showLabel": boolean; } /** * Override properties for the Arrowmarkright drawing tool. */ export interface ArrowmarkrightLineToolOverrides { /** Default value: `#2962FF` */ "linetoolarrowmarkright.arrowColor": string; /** Default value: `false` */ "linetoolarrowmarkright.bold": boolean; /** Default value: `#2962FF` */ "linetoolarrowmarkright.color": string; /** Default value: `14` */ "linetoolarrowmarkright.fontsize": number; /** Default value: `false` */ "linetoolarrowmarkright.italic": boolean; /** Default value: `true` */ "linetoolarrowmarkright.showLabel": boolean; } /** * Override properties for the Arrowmarkup drawing tool. */ export interface ArrowmarkupLineToolOverrides { /** Default value: `#089981` */ "linetoolarrowmarkup.arrowColor": string; /** Default value: `false` */ "linetoolarrowmarkup.bold": boolean; /** Default value: `#089981` */ "linetoolarrowmarkup.color": string; /** Default value: `14` */ "linetoolarrowmarkup.fontsize": number; /** Default value: `false` */ "linetoolarrowmarkup.italic": boolean; /** Default value: `true` */ "linetoolarrowmarkup.showLabel": boolean; } 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; } /** * Overrides for the 'Average Directional Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface AverageDirectionalIndexIndicatorOverrides { /** Default value: `15` */ "adx.display": number; /** Default value: `0` */ "adx.linestyle": number; /** Default value: `1` */ "adx.linewidth": number; /** Default value: `line` */ "adx.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "adx.trackprice": boolean; /** Default value: `0` */ "adx.transparency": number; /** Default value: `#FF5252` */ "adx.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Average Price' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface AveragePriceIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Average True Range' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface AverageTrueRangeIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#801922` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Awesome Oscillator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface AwesomeOscillatorIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `histogram` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#000080` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Balance of Power' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface BalanceofPowerIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#FF5252` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Override properties for the Balloon drawing tool. */ export interface BalloonLineToolOverrides { /** Default value: `rgba(156, 39, 176, 0.7)` */ "linetoolballoon.backgroundColor": string; /** Default value: `rgba(156, 39, 176, 0)` */ "linetoolballoon.borderColor": string; /** Default value: `#ffffff` */ "linetoolballoon.color": string; /** Default value: `14` */ "linetoolballoon.fontsize": number; /** Default value: `30` */ "linetoolballoon.transparency": number; } /** * Bar data point */ export interface Bar { /** Bar time. * Amount of **milliseconds** since Unix epoch start in **UTC** timezone. * `time` for daily, weekly, and monthly bars is expected to be a trading day (not session start day) at 00:00 UTC. * The 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 BarState { isLast(): boolean; } 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; } /** * Override properties for the Barspattern drawing tool. */ export interface BarspatternLineToolOverrides { /** Default value: `#2962FF` */ "linetoolbarspattern.color": string; /** Default value: `false` */ "linetoolbarspattern.flipped": boolean; /** Default value: `false` */ "linetoolbarspattern.mirrored": boolean; /** Default value: `0` */ "linetoolbarspattern.mode": number; } 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; /** Top line style */ topLineStyle: number; /** Bottom line style */ bottomLineStyle: 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; } /** * Override properties for the Beziercubic drawing tool. */ export interface BeziercubicLineToolOverrides { /** Default value: `rgba(103, 58, 183, 0.2)` */ "linetoolbeziercubic.backgroundColor": string; /** Default value: `false` */ "linetoolbeziercubic.extendLeft": boolean; /** Default value: `false` */ "linetoolbeziercubic.extendRight": boolean; /** Default value: `false` */ "linetoolbeziercubic.fillBackground": boolean; /** Default value: `0` */ "linetoolbeziercubic.leftEnd": number; /** Default value: `#673ab7` */ "linetoolbeziercubic.linecolor": string; /** Default value: `0` */ "linetoolbeziercubic.linestyle": number; /** Default value: `2` */ "linetoolbeziercubic.linewidth": number; /** Default value: `0` */ "linetoolbeziercubic.rightEnd": number; /** Default value: `80` */ "linetoolbeziercubic.transparency": number; } /** * Override properties for the Bezierquadro drawing tool. */ export interface BezierquadroLineToolOverrides { /** Default value: `rgba(41, 98, 255, 0.2)` */ "linetoolbezierquadro.backgroundColor": string; /** Default value: `false` */ "linetoolbezierquadro.extendLeft": boolean; /** Default value: `false` */ "linetoolbezierquadro.extendRight": boolean; /** Default value: `false` */ "linetoolbezierquadro.fillBackground": boolean; /** Default value: `0` */ "linetoolbezierquadro.leftEnd": number; /** Default value: `#2962FF` */ "linetoolbezierquadro.linecolor": string; /** Default value: `0` */ "linetoolbezierquadro.linestyle": number; /** Default value: `2` */ "linetoolbezierquadro.linewidth": number; /** Default value: `0` */ "linetoolbezierquadro.rightEnd": number; /** Default value: `50` */ "linetoolbezierquadro.transparency": number; } /** * Overrides for the 'Bollinger Bands %B' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface BollingerBandsBIndicatorOverrides { /** Default value: `#26A69A` */ "hlines background.color": string; /** Default value: `90` */ "hlines background.transparency": number; /** Default value: `true` */ "hlines background.visible": boolean; /** Default value: `#787B86` */ "upperlimit.color": string; /** Default value: `2` */ "upperlimit.linestyle": number; /** Default value: `1` */ "upperlimit.linewidth": number; /** Default value: `true` */ "upperlimit.visible": boolean; /** Default value: `1` */ "upperlimit.value": number; /** Default value: `#787B86` */ "lowerlimit.color": string; /** Default value: `2` */ "lowerlimit.linestyle": number; /** Default value: `1` */ "lowerlimit.linewidth": number; /** Default value: `true` */ "lowerlimit.visible": boolean; /** Default value: `0` */ "lowerlimit.value": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `true` */ "plot.visible": boolean; /** Default value: `#22AB94` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Bollinger Bands' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface BollingerBandsIndicatorOverrides { /** Default value: `#2196F3` */ "plots background.color": string; /** Default value: `95` */ "plots background.transparency": number; /** Default value: `true` */ "plots background.visible": boolean; /** Default value: `0` */ "median.linestyle": number; /** Default value: `1` */ "median.linewidth": number; /** Default value: `line` */ "median.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "median.trackprice": boolean; /** Default value: `0` */ "median.transparency": number; /** Default value: `true` */ "median.visible": boolean; /** Default value: `#FF6D00` */ "median.color": string; /** Default value: `0` */ "upper.linestyle": number; /** Default value: `1` */ "upper.linewidth": number; /** Default value: `line` */ "upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "upper.trackprice": boolean; /** Default value: `0` */ "upper.transparency": number; /** Default value: `true` */ "upper.visible": boolean; /** Default value: `#2196F3` */ "upper.color": string; /** Default value: `0` */ "lower.linestyle": number; /** Default value: `1` */ "lower.linewidth": number; /** Default value: `line` */ "lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lower.trackprice": boolean; /** Default value: `0` */ "lower.transparency": number; /** Default value: `true` */ "lower.visible": boolean; /** Default value: `#2196F3` */ "lower.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Bollinger Bands Width' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface BollingerBandsWidthIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#FF6D00` */ "plot.color": string; [key: string]: StudyOverrideValueType; } export interface BoolInputOptions extends CommonInputOptions { } /** * An object that contains information about a bracket order. */ export interface BracketOrder extends BracketOrderBase, CustomFields { } export interface BracketOrderBase extends PlacedOrderBase { /** If an order is a bracket, it should contain an ID of a parent order/position. */ parentId: string; /** Type of the bracket's parent. */ parentType: ParentType; } export interface Brackets { /** Stop loss */ stopLoss?: number; /** Guaranteed Stop */ guaranteedStop?: number; /** Take Profit */ takeProfit?: number; /** Trailing Stop Pips */ trailingStopPips?: number; } export interface BrokerConfigFlags { /** * Changes _Amount_ to _Quantity_ in Order Ticket. * @default false */ showQuantityInsteadOfAmount?: boolean; /** * Enables order brackets: take-profit and stop-loss. * @default false */ supportOrderBrackets?: boolean; /** * Enables stop loss orders. If this flag is set to `true`, the library displays stop loss orders and a user can place a stop loss order using the Order Ticket. * If you set this flag to `false`, the {@link BrokerConfigFlags.supportTrailingStop} and/or {@link BrokerConfigFlags.supportGuaranteedStop} flag should be set to `true`. * If the `supportStopLoss`, `supportTrailingStop`, and `supportGuaranteedStop` flags are set to `false`, the default value will be used. * @default true */ supportStopLoss?: boolean; /** * Enables trailing stop orders. * If you set this flag to `true`, the library displays trailing stop orders and a user can place a trailing stop order using the Order Ticket. * @default false */ supportTrailingStop?: boolean; /** * Enables guaranteed stop loss orders. * If you set this flag to `true`, the library displays guaranteed stop orders and a user can place a guaranteed stop order using the Order Ticket. * @default false */ supportGuaranteedStop?: boolean; /** * Enables [positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions). * This flag requires the [`positions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#positions) method to be implemented. * If you set `supportPositions` to `false`, the _Positions_ tab in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager) will be hidden. * @default true */ supportPositions?: boolean; /** * Enables position brackets: take-profit and stop-loss orders. * If you set `supportPositionBrackets` to `true`, the library displays an _Edit_ button for positions and _Edit position..._ in the position's context menu. * This flag requires the {@link IBrokerTerminal.editPositionBrackets} method to be implemented. * @default false */ supportPositionBrackets?: boolean; /** * Enables brackets for individual positions: take-profit and stop-loss orders. * If you set this flag to `true`, the library displays an _Edit_ button for individual positions and _Edit position..._ in the individual position's context menu. * This flag requires the {@link IBrokerTerminal.editIndividualPositionBrackets} method to be implemented. * @default false */ supportIndividualPositionBrackets?: boolean; /** * Enables [position netting](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#position-netting). * This flag requires the [`positions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#positions) and [`individualPositions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#individualpositions) method to be implemented. * * If you set this flag to `true`, the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager) will have two tabs: _Individual Positions_ and _Net Positions_. * * @default false */ supportPositionNetting?: boolean; /** * Enables [position closing](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#close-positions). * - If `supportClosePosition` is set to `false`, positions are closed using [market orders](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders#order-types) of the opposite side. The library calls the {@link IBrokerTerminal.placeOrder} method, passing the `isClose` property set to `true` in the `PreOrder` object. * - If `supportClosePosition` is set to `true`, the library calls the {@link IBrokerTerminal.closePosition} method. * @default false */ supportClosePosition?: boolean; /** * Enables individual [position closing](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#close-positions). * This flag requires the {@link IBrokerTerminal.closeIndividualPosition} method to be implemented. * @default false */ supportCloseIndividualPosition?: boolean; /** * Enables order price editing. * If you set this flag to `false`, the price control in the _Order Ticket_ will be disabled when users modify orders. * @default true */ supportModifyOrderPrice?: boolean; /** * Enables order quantity editing. * If you set this flag to `false`, the quantity control in the _Order Ticket_ will be disabled when users modify orders. * @default true */ supportEditAmount?: boolean; /** * Enables order brackets editing. * If you set this flag to `false`, the bracket's control in the Order Ticket will be disabled, * and the _Modify_ button will be hidden from the chart and in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager). * @default true */ supportModifyBrackets?: boolean; /** * Enables Level 2 data for the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) widget. * This flag requires the [`subscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribedepth) and [`unsubscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#unsubscribedepth) methods to be implemented. * @default false */ supportLevel2Data?: boolean; /** * Enables [multiple positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#multiposition) for one instrument at the same time. * * Note that if the flag is set to `true`: * - The [default reversal](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#default-reversal) in the library does not work. You need to implement the [native reversal](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#native-reversal) on your backend side. * - The _Flatten_ button in the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) widget will be disabled. * @default false */ supportMultiposition?: boolean; /** * Allows using your own [profit and loss](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss) (P&L) values for positions. * By default, `supportPLUpdate` is set to `true`. * This means you should calculate the P&L value for a position and [provide values](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss#provide-pl-values) to the library. * * If `supportPLUpdate` is set to `false`, the library automatically calculates P&L values as the difference between the current trade and the average position price. * However, we recommend using your own P&L calculations for positions. * This helps avoid any discrepancies between the P&L values of the account and positions due to potential delays. * @default true */ supportPLUpdate?: boolean; /** * Enables [position reversing](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#reverse-positions). * If `supportReversePosition` is set to `false`, the _Reverse Position_ button will be hidden from the UI. * @default false */ supportReversePosition?: boolean; /** * Enables [native](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#native-reversal) position reversing. You should implement the {@link IBrokerTerminal.reversePosition} method to process reversing on your backend side. * Note that the {@link supportReversePosition} flag should be set to `true` to enable the reverse option in the UI. * * If `supportNativeReversePosition` is set to `false`, the library handles reversing using the built-in mechanism. For more information, refer to the [Default reversal](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#default-reversal) section. * @default false */ supportNativeReversePosition?: boolean; /** * Enables market orders type in the Order Ticket. * @default true */ supportMarketOrders?: boolean; /** * Enables limit orders type in the Order Ticket. * @default true */ supportLimitOrders?: boolean; /** * Enables stop orders type in the Order Ticket. * @default true */ supportStopOrders?: boolean; /** * Enables stop-limit orders type in the Order Ticket. * @default false */ supportStopLimitOrders?: boolean; /** * Enables demo live switcher. * @default true */ supportDemoLiveSwitcher?: boolean; /** * Enables brackets for market orders. * @default true */ supportMarketBrackets?: boolean; /** * Enables symbol searching. * @default false */ supportSymbolSearch?: boolean; /** * Allows modifying existing [order duration](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-time-in-force-menu). * @default false */ supportModifyDuration?: boolean; /** * Allows modifying trailing stop orders. * @default true */ supportModifyTrailingStop?: boolean; /** * Allows margin. * If `supportMargin` is set to `true`, you should call {@link IBrokerConnectionAdapterHost.marginAvailableUpdate} when the Trading Platform subscribes to margin available updates using {@link IBrokerTerminal.subscribeMarginAvailable}. * @default false */ supportMargin?: boolean; /** * Allows providing the estimated commission, fees, margin, and other order information before placing the order without actually placing it. * This information will be displayed in the _Order confirmation_ dialog. * * This flag requires the {@link IBrokerTerminal.previewOrder} method to be implemented and `confirmId` parameter to be passed in the {@link IBrokerTerminal.placeOrder} method. * Refer to [Enable order preview](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#add-custom-fields) for more information. * @default false */ supportPlaceOrderPreview?: boolean; /** * Allows providing the estimated commission, fees, margin, and other order information before modifying the order without actually modifying it. * This information will be displayed in the _Order confirmation_ dialog. * * This flag requires the {@link IBrokerTerminal.previewOrder} method to be implemented and `confirmId` parameter to be passed in the {@link IBrokerTerminal.modifyOrder} method. * Refer to [Enable order preview](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#add-custom-fields) for more information. * @default false */ supportModifyOrderPreview?: boolean; /** * Enables trading with leverage. * If the flag is set to `true`, you should calculate the leverage using the {@link IBrokerTerminal.leverageInfo} method. * @default false */ supportLeverage?: boolean; /** * Displays a leverage button in the UI. * Note that you should also enable the {@link BrokerConfigFlags.supportLeverage} flag. * If `supportLeverageButton` is set to `true`, the leverage input field appears in the Order Ticket. * Clicking the input field activates a dedicated Leverage Dialog. * @default true */ supportLeverageButton?: boolean; /** * Enables orders history. * If `supportOrdersHistory` is set to `true`, the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager) will have an additional tab: _Orders History_. * This flag requires the [`ordersHistory`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#ordershistory) method to be implemented. * The method should return a list of orders with the `filled`, `cancelled`, and `rejected` statuses from previous trade sessions. * @default false */ supportOrdersHistory?: boolean; /** * Enables adding brackets to the existing order. * @default true */ supportAddBracketsToExistingOrder?: boolean; /** * Allows getting crypto balances for an account. * Balances are displayed as the first table of the _Account Summary_ tab. * Use the flag for crypto currencies only. * This flag requires the {@link IBrokerConnectionAdapterHost.cryptoBalanceUpdate} method to be implemented. * @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 for a position. * @default false */ supportOnlyPairPositionBrackets?: boolean; /** * `Stop Loss` and `Take Profit` are added or removed only together for an order. * @default false */ supportOnlyPairOrderBrackets?: boolean; /** * Enables cryptocurrency trading (exchanging). * This flag switches the Order Ticket to Crypto Exchange mode, * which provides additional controls for entering the quantity in either the base or quote currency. * @default false */ supportCryptoExchangeOrderTicket?: boolean; /** * Enables displaying Profit & Loss values in instrument currency. * @default false */ positionPLInInstrumentCurrency?: boolean; /** * Enables the display of Risk in Currency control value in instrument currency for brackets. * @default false */ showRiskInInstrumentCurrency?: boolean; /** * Enables [partial position closing](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#partial-closing). * This flag requires the {@link IBrokerTerminal.closePosition} method to be implemented. * @default false */ supportPartialClosePosition?: boolean; /** * Enables [partial individual position closing](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#partial-closing). * This flag requires the {@link IBrokerTerminal.closeIndividualPosition} method to be implemented. * @default false */ supportPartialCloseIndividualPosition?: boolean; /** * Modifies the confirmation dialog text for closing a bracket order. * When set to `true`, the text explicitly states that cancelling a bracket order will also cancel its associated pair. * When set to `false`, the text will include the ID of the singular bracket order being cancelled. * * Note that the library does not cancel orders itself. * You should implement the {@link IBrokerTerminal.cancelOrder} or {@link IBrokerTerminal.cancelOrders } method. * @default false */ supportCancellingBothBracketsOnly?: boolean; /** * Enables crypto brackets. * @default false */ supportCryptoBrackets?: boolean; /** * Enables the _Notifications log_ tab in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/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 Ticket. * @default false */ supportStopOrdersInBothDirections?: boolean; /** * Whether stop-limit orders should behave like Limit-if-Touched in both directions. * Enabling this flag prevents the check of stop price direction from the stop limit Order Ticket. */ supportStopLimitOrdersInBothDirections?: boolean; /** * Whether the integration supports limit price validation in the order ticket to eliminate the possibility to place * an order on the wrong side of the market that will most likely trigger and get filled immediately. */ supportStrictCheckingLimitOrderPrice?: boolean; /** * If set to `true`, executions are displayed on the chart. * This flag requires the [`executions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#executions) method to be implemented. * @default true */ supportExecutions?: boolean; /** * Allows modifying order type. * @default false */ supportModifyOrderType?: boolean; /** * Enables closing of individual positions in FIFO order. * @default false */ requiresFIFOCloseIndividualPositions?: boolean; /** * Allows brokers to add their own parameters that will be displayed in Order info. * @default false */ supportCustomOrderInfo?: boolean; /** * Allows brokers to send position closing information that will be displayed in Close Position Dialog * @default false */ supportPreviewClosePosition?: boolean; } export interface BrokerCustomUI { /** * Shows Order Ticket 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|IndividualPosition} 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 | IndividualPosition, 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|IndividualPosition} position - position to be closed */ showClosePositionDialog?: (position: Position | IndividualPosition) => Promise; /** * Shows the Reverse Position Dialog. * @param {Position} position - position to be reversed */ showReversePositionDialog?: (position: Position) => Promise; } /** * Override properties that can be used within {@link TradingCustomization.brokerOrder} of the {@link TradingTerminalWidgetOptions.trading_customization} object. * * In a property name, "normal" indicates the line is active and visible in the UI, while "disabled" means the line is inactive, such as when another dialog is open. */ export interface BrokerOrderOverrides { "buy.normal.anchor.backgroundColor": string; "buy.normal.anchor.borderColor": string; "buy.normal.anchor.shadowColor": string; "buy.normal.borderBackgroundColor": string; "buy.normal.borderColor": string; "buy.normal.close.activeColor": string; "buy.normal.close.backgroundColor": string; "buy.normal.close.iconColor": string; "buy.normal.confirm.activeColor": string; "buy.normal.confirm.backgroundColor": string; "buy.normal.confirm.borderColor": string; "buy.normal.confirm.disableBackgroundColor": string; "buy.normal.confirm.disableTextColor": string; "buy.normal.confirm.textColor": string; "buy.normal.disabledLineColor": string; "buy.normal.informer.backgroundColor": string; "buy.normal.informer.iconColor": string; "buy.normal.labelTickColor": string; "buy.normal.lineColor": string; "buy.normal.negativePlColor": string; "buy.normal.pointBackgroundColor": string; "buy.normal.pointShadowColor": string; "buy.normal.positivePlColor": string; "buy.normal.qty.activeColor": string; "buy.normal.qty.backgroundColor": string; "buy.normal.qty.dividerColor": string; "buy.normal.qty.textColor": string; "buy.normal.text.backgroundColor": string; "buy.normal.text.buttonTextColor": string; "buy.normal.text.dividerColor": string; "buy.normal.text.textColor": string; "buy.normal.text.activeColor": string; "buy.disabled.anchor.backgroundColor": string; "buy.disabled.anchor.borderColor": string; "buy.disabled.anchor.shadowColor": string; "buy.disabled.borderBackgroundColor": string; "buy.disabled.borderColor": string; "buy.disabled.close.activeColor": string; "buy.disabled.close.backgroundColor": string; "buy.disabled.close.iconColor": string; "buy.disabled.confirm.activeColor": string; "buy.disabled.confirm.backgroundColor": string; "buy.disabled.confirm.borderColor": string; "buy.disabled.confirm.disableBackgroundColor": string; "buy.disabled.confirm.disableTextColor": string; "buy.disabled.confirm.textColor": string; "buy.disabled.disabledLineColor": string; "buy.disabled.informer.backgroundColor": string; "buy.disabled.informer.iconColor": string; "buy.disabled.labelTickColor": string; "buy.disabled.lineColor": string; "buy.disabled.negativePlColor": string; "buy.disabled.pointBackgroundColor": string; "buy.disabled.pointShadowColor": string; "buy.disabled.positivePlColor": string; "buy.disabled.qty.activeColor": string; "buy.disabled.qty.backgroundColor": string; "buy.disabled.qty.dividerColor": string; "buy.disabled.qty.textColor": string; "buy.disabled.text.backgroundColor": string; "buy.disabled.text.buttonTextColor": string; "buy.disabled.text.dividerColor": string; "buy.disabled.text.textColor": string; "buy.disabled.text.activeColor": string; "sell.normal.anchor.backgroundColor": string; "sell.normal.anchor.borderColor": string; "sell.normal.anchor.shadowColor": string; "sell.normal.borderBackgroundColor": string; "sell.normal.borderColor": string; "sell.normal.close.activeColor": string; "sell.normal.close.backgroundColor": string; "sell.normal.close.iconColor": string; "sell.normal.confirm.activeColor": string; "sell.normal.confirm.backgroundColor": string; "sell.normal.confirm.borderColor": string; "sell.normal.confirm.disableBackgroundColor": string; "sell.normal.confirm.disableTextColor": string; "sell.normal.confirm.textColor": string; "sell.normal.disabledLineColor": string; "sell.normal.informer.backgroundColor": string; "sell.normal.informer.iconColor": string; "sell.normal.labelTickColor": string; "sell.normal.lineColor": string; "sell.normal.negativePlColor": string; "sell.normal.pointBackgroundColor": string; "sell.normal.pointShadowColor": string; "sell.normal.positivePlColor": string; "sell.normal.qty.activeColor": string; "sell.normal.qty.backgroundColor": string; "sell.normal.qty.dividerColor": string; "sell.normal.qty.textColor": string; "sell.normal.text.backgroundColor": string; "sell.normal.text.buttonTextColor": string; "sell.normal.text.dividerColor": string; "sell.normal.text.textColor": string; "sell.normal.text.activeColor": string; "sell.disabled.anchor.backgroundColor": string; "sell.disabled.anchor.borderColor": string; "sell.disabled.anchor.shadowColor": string; "sell.disabled.borderBackgroundColor": string; "sell.disabled.borderColor": string; "sell.disabled.close.activeColor": string; "sell.disabled.close.backgroundColor": string; "sell.disabled.close.iconColor": string; "sell.disabled.confirm.activeColor": string; "sell.disabled.confirm.backgroundColor": string; "sell.disabled.confirm.borderColor": string; "sell.disabled.confirm.disableBackgroundColor": string; "sell.disabled.confirm.disableTextColor": string; "sell.disabled.confirm.textColor": string; "sell.disabled.disabledLineColor": string; "sell.disabled.informer.backgroundColor": string; "sell.disabled.informer.iconColor": string; "sell.disabled.labelTickColor": string; "sell.disabled.lineColor": string; "sell.disabled.negativePlColor": string; "sell.disabled.pointBackgroundColor": string; "sell.disabled.pointShadowColor": string; "sell.disabled.positivePlColor": string; "sell.disabled.qty.activeColor": string; "sell.disabled.qty.backgroundColor": string; "sell.disabled.qty.dividerColor": string; "sell.disabled.qty.textColor": string; "sell.disabled.text.backgroundColor": string; "sell.disabled.text.buttonTextColor": string; "sell.disabled.text.dividerColor": string; "sell.disabled.text.textColor": string; "sell.disabled.text.activeColor": string; "takeProfit.normal.anchor.backgroundColor": string; "takeProfit.normal.anchor.borderColor": string; "takeProfit.normal.anchor.shadowColor": string; "takeProfit.normal.borderBackgroundColor": string; "takeProfit.normal.borderColor": string; "takeProfit.normal.close.activeColor": string; "takeProfit.normal.close.backgroundColor": string; "takeProfit.normal.close.iconColor": string; "takeProfit.normal.confirm.activeColor": string; "takeProfit.normal.confirm.backgroundColor": string; "takeProfit.normal.confirm.borderColor": string; "takeProfit.normal.confirm.disableBackgroundColor": string; "takeProfit.normal.confirm.disableTextColor": string; "takeProfit.normal.confirm.textColor": string; "takeProfit.normal.disabledLineColor": string; "takeProfit.normal.informer.backgroundColor": string; "takeProfit.normal.informer.iconColor": string; "takeProfit.normal.labelTickColor": string; "takeProfit.normal.lineColor": string; "takeProfit.normal.negativePlColor": string; "takeProfit.normal.pointBackgroundColor": string; "takeProfit.normal.pointShadowColor": string; "takeProfit.normal.positivePlColor": string; "takeProfit.normal.qty.activeColor": string; "takeProfit.normal.qty.backgroundColor": string; "takeProfit.normal.qty.dividerColor": string; "takeProfit.normal.qty.textColor": string; "takeProfit.normal.text.backgroundColor": string; "takeProfit.normal.text.buttonTextColor": string; "takeProfit.normal.text.dividerColor": string; "takeProfit.normal.text.textColor": string; "takeProfit.normal.text.activeColor": string; "takeProfit.normal.text.hintAreaColor": string; "takeProfit.normal.movingBackgroundColor": string; "takeProfit.disabled.anchor.backgroundColor": string; "takeProfit.disabled.anchor.borderColor": string; "takeProfit.disabled.anchor.shadowColor": string; "takeProfit.disabled.borderBackgroundColor": string; "takeProfit.disabled.borderColor": string; "takeProfit.disabled.close.activeColor": string; "takeProfit.disabled.close.backgroundColor": string; "takeProfit.disabled.close.iconColor": string; "takeProfit.disabled.confirm.activeColor": string; "takeProfit.disabled.confirm.backgroundColor": string; "takeProfit.disabled.confirm.borderColor": string; "takeProfit.disabled.confirm.disableBackgroundColor": string; "takeProfit.disabled.confirm.disableTextColor": string; "takeProfit.disabled.confirm.textColor": string; "takeProfit.disabled.disabledLineColor": string; "takeProfit.disabled.informer.backgroundColor": string; "takeProfit.disabled.informer.iconColor": string; "takeProfit.disabled.labelTickColor": string; "takeProfit.disabled.lineColor": string; "takeProfit.disabled.negativePlColor": string; "takeProfit.disabled.pointBackgroundColor": string; "takeProfit.disabled.pointShadowColor": string; "takeProfit.disabled.positivePlColor": string; "takeProfit.disabled.qty.activeColor": string; "takeProfit.disabled.qty.backgroundColor": string; "takeProfit.disabled.qty.dividerColor": string; "takeProfit.disabled.qty.textColor": string; "takeProfit.disabled.text.backgroundColor": string; "takeProfit.disabled.text.buttonTextColor": string; "takeProfit.disabled.text.dividerColor": string; "takeProfit.disabled.text.textColor": string; "takeProfit.disabled.text.activeColor": string; "takeProfit.disabled.text.hintAreaColor": string; "takeProfit.disabled.movingBackgroundColor": string; "stopLoss.normal.anchor.backgroundColor": string; "stopLoss.normal.anchor.borderColor": string; "stopLoss.normal.anchor.shadowColor": string; "stopLoss.normal.borderBackgroundColor": string; "stopLoss.normal.borderColor": string; "stopLoss.normal.close.activeColor": string; "stopLoss.normal.close.backgroundColor": string; "stopLoss.normal.close.iconColor": string; "stopLoss.normal.confirm.activeColor": string; "stopLoss.normal.confirm.backgroundColor": string; "stopLoss.normal.confirm.borderColor": string; "stopLoss.normal.confirm.disableBackgroundColor": string; "stopLoss.normal.confirm.disableTextColor": string; "stopLoss.normal.confirm.textColor": string; "stopLoss.normal.disabledLineColor": string; "stopLoss.normal.informer.backgroundColor": string; "stopLoss.normal.informer.iconColor": string; "stopLoss.normal.labelTickColor": string; "stopLoss.normal.lineColor": string; "stopLoss.normal.negativePlColor": string; "stopLoss.normal.pointBackgroundColor": string; "stopLoss.normal.pointShadowColor": string; "stopLoss.normal.positivePlColor": string; "stopLoss.normal.qty.activeColor": string; "stopLoss.normal.qty.backgroundColor": string; "stopLoss.normal.qty.dividerColor": string; "stopLoss.normal.qty.textColor": string; "stopLoss.normal.text.backgroundColor": string; "stopLoss.normal.text.buttonTextColor": string; "stopLoss.normal.text.dividerColor": string; "stopLoss.normal.text.textColor": string; "stopLoss.normal.text.activeColor": string; "stopLoss.normal.text.hintAreaColor": string; "stopLoss.normal.movingBackgroundColor": string; "stopLoss.disabled.anchor.backgroundColor": string; "stopLoss.disabled.anchor.borderColor": string; "stopLoss.disabled.anchor.shadowColor": string; "stopLoss.disabled.borderBackgroundColor": string; "stopLoss.disabled.borderColor": string; "stopLoss.disabled.close.activeColor": string; "stopLoss.disabled.close.backgroundColor": string; "stopLoss.disabled.close.iconColor": string; "stopLoss.disabled.confirm.activeColor": string; "stopLoss.disabled.confirm.backgroundColor": string; "stopLoss.disabled.confirm.borderColor": string; "stopLoss.disabled.confirm.disableBackgroundColor": string; "stopLoss.disabled.confirm.disableTextColor": string; "stopLoss.disabled.confirm.textColor": string; "stopLoss.disabled.disabledLineColor": string; "stopLoss.disabled.informer.backgroundColor": string; "stopLoss.disabled.informer.iconColor": string; "stopLoss.disabled.labelTickColor": string; "stopLoss.disabled.lineColor": string; "stopLoss.disabled.negativePlColor": string; "stopLoss.disabled.pointBackgroundColor": string; "stopLoss.disabled.pointShadowColor": string; "stopLoss.disabled.positivePlColor": string; "stopLoss.disabled.qty.activeColor": string; "stopLoss.disabled.qty.backgroundColor": string; "stopLoss.disabled.qty.dividerColor": string; "stopLoss.disabled.qty.textColor": string; "stopLoss.disabled.text.backgroundColor": string; "stopLoss.disabled.text.buttonTextColor": string; "stopLoss.disabled.text.dividerColor": string; "stopLoss.disabled.text.textColor": string; "stopLoss.disabled.text.activeColor": string; "stopLoss.disabled.text.hintAreaColor": string; "stopLoss.disabled.movingBackgroundColor": string; } /** * Override properties that can be used within {@link TradingCustomization.brokerPosition} of the {@link TradingTerminalWidgetOptions.trading_customization} object. * * In a property name, "normal" indicates the line is active and visible in the UI, while "disabled" means the line is inactive, such as when another dialog is open. */ export interface BrokerPositionOverrides { "buy.normal.borderBackgroundColor": string; "buy.normal.borderColor": string; "buy.normal.close.activeColor": string; "buy.normal.close.backgroundColor": string; "buy.normal.close.iconColor": string; "buy.normal.confirm.activeColor": string; "buy.normal.confirm.backgroundColor": string; "buy.normal.confirm.borderColor": string; "buy.normal.confirm.disableBackgroundColor": string; "buy.normal.confirm.disableTextColor": string; "buy.normal.confirm.textColor": string; "buy.normal.disabledLineColor": string; "buy.normal.informer.backgroundColor": string; "buy.normal.informer.iconColor": string; "buy.normal.lineColor": string; "buy.normal.negativePlColor": string; "buy.normal.pointBackgroundColor": string; "buy.normal.pointShadowColor": string; "buy.normal.positivePlColor": string; "buy.normal.qty.activeColor": string; "buy.normal.qty.backgroundColor": string; "buy.normal.qty.dividerColor": string; "buy.normal.qty.textColor": string; "buy.normal.reverse.activeColor": string; "buy.normal.reverse.backgroundColor": string; "buy.normal.reverse.borderColor": string; "buy.normal.reverse.iconColor": string; "buy.normal.text.backgroundColor": string; "buy.normal.text.dividerColor": string; "buy.normal.text.textColor": string; "buy.disabled.borderBackgroundColor": string; "buy.disabled.borderColor": string; "buy.disabled.close.activeColor": string; "buy.disabled.close.backgroundColor": string; "buy.disabled.close.iconColor": string; "buy.disabled.confirm.activeColor": string; "buy.disabled.confirm.backgroundColor": string; "buy.disabled.confirm.borderColor": string; "buy.disabled.confirm.disableBackgroundColor": string; "buy.disabled.confirm.disableTextColor": string; "buy.disabled.confirm.textColor": string; "buy.disabled.disabledLineColor": string; "buy.disabled.informer.backgroundColor": string; "buy.disabled.informer.iconColor": string; "buy.disabled.lineColor": string; "buy.disabled.negativePlColor": string; "buy.disabled.pointBackgroundColor": string; "buy.disabled.pointShadowColor": string; "buy.disabled.positivePlColor": string; "buy.disabled.qty.activeColor": string; "buy.disabled.qty.backgroundColor": string; "buy.disabled.qty.dividerColor": string; "buy.disabled.qty.textColor": string; "buy.disabled.reverse.activeColor": string; "buy.disabled.reverse.backgroundColor": string; "buy.disabled.reverse.borderColor": string; "buy.disabled.reverse.iconColor": string; "buy.disabled.text.backgroundColor": string; "buy.disabled.text.dividerColor": string; "buy.disabled.text.textColor": string; "sell.normal.borderBackgroundColor": string; "sell.normal.borderColor": string; "sell.normal.close.activeColor": string; "sell.normal.close.backgroundColor": string; "sell.normal.close.iconColor": string; "sell.normal.confirm.activeColor": string; "sell.normal.confirm.backgroundColor": string; "sell.normal.confirm.borderColor": string; "sell.normal.confirm.disableBackgroundColor": string; "sell.normal.confirm.disableTextColor": string; "sell.normal.confirm.textColor": string; "sell.normal.disabledLineColor": string; "sell.normal.informer.backgroundColor": string; "sell.normal.informer.iconColor": string; "sell.normal.lineColor": string; "sell.normal.negativePlColor": string; "sell.normal.pointBackgroundColor": string; "sell.normal.pointShadowColor": string; "sell.normal.positivePlColor": string; "sell.normal.qty.activeColor": string; "sell.normal.qty.backgroundColor": string; "sell.normal.qty.dividerColor": string; "sell.normal.qty.textColor": string; "sell.normal.reverse.activeColor": string; "sell.normal.reverse.backgroundColor": string; "sell.normal.reverse.borderColor": string; "sell.normal.reverse.iconColor": string; "sell.normal.text.backgroundColor": string; "sell.normal.text.dividerColor": string; "sell.normal.text.textColor": string; "sell.disabled.borderBackgroundColor": string; "sell.disabled.borderColor": string; "sell.disabled.close.activeColor": string; "sell.disabled.close.backgroundColor": string; "sell.disabled.close.iconColor": string; "sell.disabled.confirm.activeColor": string; "sell.disabled.confirm.backgroundColor": string; "sell.disabled.confirm.borderColor": string; "sell.disabled.confirm.disableBackgroundColor": string; "sell.disabled.confirm.disableTextColor": string; "sell.disabled.confirm.textColor": string; "sell.disabled.disabledLineColor": string; "sell.disabled.informer.backgroundColor": string; "sell.disabled.informer.iconColor": string; "sell.disabled.lineColor": string; "sell.disabled.negativePlColor": string; "sell.disabled.pointBackgroundColor": string; "sell.disabled.pointShadowColor": string; "sell.disabled.positivePlColor": string; "sell.disabled.qty.activeColor": string; "sell.disabled.qty.backgroundColor": string; "sell.disabled.qty.dividerColor": string; "sell.disabled.qty.textColor": string; "sell.disabled.reverse.activeColor": string; "sell.disabled.reverse.backgroundColor": string; "sell.disabled.reverse.borderColor": string; "sell.disabled.reverse.iconColor": string; "sell.disabled.text.backgroundColor": string; "sell.disabled.text.dividerColor": string; "sell.disabled.text.textColor": string; } /** * Override properties for the Brush drawing tool. */ export interface BrushLineToolOverrides { /** Default value: `#00bcd4` */ "linetoolbrush.backgroundColor": string; /** Default value: `false` */ "linetoolbrush.fillBackground": boolean; /** Default value: `0` */ "linetoolbrush.leftEnd": number; /** Default value: `#00bcd4` */ "linetoolbrush.linecolor": string; /** Default value: `2` */ "linetoolbrush.linewidth": number; /** Default value: `0` */ "linetoolbrush.rightEnd": number; /** Default value: `5` */ "linetoolbrush.smooth": number; /** Default value: `50` */ "linetoolbrush.transparency": number; } /** * Override properties for the Callout drawing tool. */ export interface CalloutLineToolOverrides { /** Default value: `rgba(0, 151, 167, 0.7)` */ "linetoolcallout.backgroundColor": string; /** Default value: `false` */ "linetoolcallout.bold": boolean; /** Default value: `#0097A7` */ "linetoolcallout.bordercolor": string; /** Default value: `#ffffff` */ "linetoolcallout.color": string; /** Default value: `14` */ "linetoolcallout.fontsize": number; /** Default value: `false` */ "linetoolcallout.italic": boolean; /** Default value: `2` */ "linetoolcallout.linewidth": number; /** Default value: `50` */ "linetoolcallout.transparency": number; /** Default value: `false` */ "linetoolcallout.wordWrap": boolean; /** Default value: `200` */ "linetoolcallout.wordWrapWidth": number; } 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; } /** * Overrides for the 'Chaikin Money Flow' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ChaikinMoneyFlowIndicatorOverrides { /** Default value: `#787B86` */ "zero.color": string; /** Default value: `2` */ "zero.linestyle": number; /** Default value: `1` */ "zero.linewidth": number; /** Default value: `true` */ "zero.visible": boolean; /** Default value: `0` */ "zero.value": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#43A047` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Chaikin Oscillator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ChaikinOscillatorIndicatorOverrides { /** Default value: `#787B86` */ "zero.color": string; /** Default value: `2` */ "zero.linestyle": number; /** Default value: `1` */ "zero.linewidth": number; /** Default value: `true` */ "zero.visible": boolean; /** Default value: `0` */ "zero.value": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#EC407A` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Chaikin Volatility' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ChaikinVolatilityIndicatorOverrides { /** Default value: `#787B86` */ "zero.color": string; /** Default value: `2` */ "zero.linestyle": number; /** Default value: `1` */ "zero.linewidth": number; /** Default value: `true` */ "zero.visible": boolean; /** Default value: `0` */ "zero.value": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#AB47BC` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Chande Kroll Stop' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ChandeKrollStopIndicatorOverrides { /** Default value: `15` */ "long.display": number; /** Default value: `0` */ "long.linestyle": number; /** Default value: `1` */ "long.linewidth": number; /** Default value: `line` */ "long.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "long.trackprice": boolean; /** Default value: `0` */ "long.transparency": number; /** Default value: `#2196F3` */ "long.color": string; /** Default value: `15` */ "short.display": number; /** Default value: `0` */ "short.linestyle": number; /** Default value: `1` */ "short.linewidth": number; /** Default value: `line` */ "short.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "short.trackprice": boolean; /** Default value: `0` */ "short.transparency": number; /** Default value: `#FF6D00` */ "short.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Chande Momentum Oscillator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ChandeMomentumOscillatorIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } 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 | number; /** name of the chart */ name: string; /** symbol of the chart */ symbol: string; /** resolution of the chart */ resolution: ResolutionString; /** content of the chart */ content: string; /** UNIX time when the chart was last modified. Date and time will be displayed in the Load layout dialog. */ timestamp: number; } export interface ChartDescriptionContext { /** Style of chart */ chartType: SeriesType; /** Name of chart style */ chartTypeName: string; /** Symbol's description from the Symbol Info */ description?: string; /** Symbol identifier, typically the symbols ticker or name defined in the Symbol Info */ symbol: string; /** Symbol's exchange */ exchange?: string; /** Symbol's ticker identifier */ ticker?: string; /** Visible time range */ visibleRange: VisibleTimeRange; /** Visible data. Only included if [aria_detailed_chart_descriptions](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#aria_detailed_chart_descriptions) featureset is enabled */ visibleData?: ExportedData; /** The complete Symbol Info for the chart's main series */ symbolInfo: LibrarySymbolInfo | null; /** Index of the current chart within a multi-chart layout */ chartIndex: number; /** Number of visible charts in the current layout */ chartCount: number; /** Symbol's default price formatter */ priceFormatter: ISymbolValueFormatter; /** Resolution (interval) of the chart */ interval: ResolutionString; /** Is the resolution (interval) intraday */ isIntraday: boolean; } /** * Meta information about a saved chart */ export interface ChartMetaInfo { /** unique ID of the chart. */ id: number | string; /** 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 { /** * Override values. */ [key: string]: string | number | boolean; /** * 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. In the dark theme, the default value is 'gradient'. * * @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": OverrideLineStyle; /** * 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": OverrideLineStyle; /** * Pane grid line mode. * * @default "both" */ "paneProperties.gridLinesMode": GridLinesMode; /** * Crosshair color. * * @default '#9598A1' */ "paneProperties.crossHairProperties.color": string; /** * Crosshair style. * * @default LineStyle.Dashed */ "paneProperties.crossHairProperties.style": OverrideLineStyle; /** * Crosshair transparency. To use this property, specify `paneProperties.crossHairProperties.color` with a **hexadecimal** value such as `#ff0000`. Otherwise, transparency is not applied. * * @default 0 */ "paneProperties.crossHairProperties.transparency": number; /** * Crosshair width. * * @default 1 */ "paneProperties.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; /** * Pane separator color. * * @default '#EBEBEB' */ "paneProperties.separatorColor": string; /** * Study legend input values visibility. * * @default true */ "paneProperties.legendProperties.showStudyArguments": boolean; /** * Study legend title visibility. * * @default true */ "paneProperties.legendProperties.showStudyTitles": boolean; /** * Toggle the visibility for all studies legend values. * * @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; /** * Adds the ability to show daily changes in the chart legend. * * @default false */ "paneProperties.legendProperties.showLastDayChange": boolean; /** * Series legend change value visibility. * * @default true */ "paneProperties.legendProperties.showBarChange": boolean; /** * Series series legend close value visibility when on mobile. * * @default true */ "paneProperties.legendProperties.showSeriesLegendCloseOnMobile": 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; /** * 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": OverridePriceAxisLastValueMode; /** * 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; /** * Sets the highlight color of the scales when adding a drawing. * * @default 'rgba(41, 98, 255, 0.25)' */ "scalesProperties.axisHighlightColor": string; /** * Configures the background color of a label shown on an axis scale when a drawing is selected. * * @default '#2962FF' */ "scalesProperties.axisLineToolLabelBackgroundColorCommon": string; /** * Dynamically changes the background color of all labels on the price scale when a drawing is in motion. * * @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; /** * When enabled, autoscaling considers only the main series prices and ignores other series added with the _Compare_ button. * * @default false */ "scalesProperties.scaleSeriesOnly": boolean; /** * Main series chart style. * * @default ChartStyle.Candle */ "mainSeriesProperties.style": ChartStyle; /** * Displays the countdown to the bar closing on the price scale. Available only for [intraday](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-minutes-intraday) resolutions. * * @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": OverrideLineStyle; /** * 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; /** * Sessions to display on the chart. Use `'extended'` to include pre- and post-market subsessions. See the [Extended Sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions) guide for more info. * * @default 'regular' */ "mainSeriesProperties.sessionId": "regular" | "extended"; /** * 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 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 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 volume candle style up color. * * @default "#089981" */ "mainSeriesProperties.volCandlesStyle.upColor": string; /** * Main series volume candle style down color. * * @default "#F23645" */ "mainSeriesProperties.volCandlesStyle.downColor": string; /** * Main series volume candle style wick visibility. * * @default true */ "mainSeriesProperties.volCandlesStyle.drawWick": boolean; /** * Main series volume candle style border visibility. * * @default true */ "mainSeriesProperties.volCandlesStyle.drawBorder": boolean; /** * * Main series volume candle style border color. * * @default "#378658" */ "mainSeriesProperties.volCandlesStyle.borderColor": string; /** * * Main series volume candle style border up color. * * @default "#089981" */ "mainSeriesProperties.volCandlesStyle.borderUpColor": string; /** * Main series volume candle style border down color. * * @default "#F23645" */ "mainSeriesProperties.volCandlesStyle.borderDownColor": string; /** * Main series volume candle style wick color. * * @default "#737375" */ "mainSeriesProperties.volCandlesStyle.wickColor": string; /** * Main series volume candle style wick up color. * * @default "#089981" */ "mainSeriesProperties.volCandlesStyle.wickUpColor": string; /** * Main series volume candle style wick down color. * * @default "#F23645" */ "mainSeriesProperties.volCandlesStyle.wickDownColor": string; /** * * Main series volume candle style color on previous close behaviour. * * @default false */ "mainSeriesProperties.volCandlesStyle.barColorsOnPrevClose": boolean; /** * Main series volume candle style body visibility. * * @default true */ "mainSeriesProperties.volCandlesStyle.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": OverrideLineStyle; /** * 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 step line style color. * * @default "#2962FF" */ "mainSeriesProperties.steplineStyle.color": string; /** * Main series step line style line style. * * @default LineStyle.Solid */ "mainSeriesProperties.steplineStyle.linestyle": OverrideLineStyle; /** * Main series step line style line width. * * @default 2 */ "mainSeriesProperties.steplineStyle.linewidth": number; /** * Main series step line style price source. * * @default "close" */ "mainSeriesProperties.steplineStyle.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": OverrideLineStyle; /** * 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 hlc area style close line color. * * @default "#868993" */ "mainSeriesProperties.hlcAreaStyle.closeLineColor": string; /** * Main series hlc area style close line style. * * @default LineStyle.Solid */ "mainSeriesProperties.hlcAreaStyle.closeLineStyle": OverrideLineStyle; /** * Main series hlc area style close line width. * * @default 2 */ "mainSeriesProperties.hlcAreaStyle.closeLineWidth": number; /** * Main series hlc area style close low fill color. * * @default "rgba(242, 54, 69, 0.2)" */ "mainSeriesProperties.hlcAreaStyle.closeLowFillColor": string; /** * Main series hlc area style high close fill color. * * @default "rgba(8, 153, 129, 0.2)" */ "mainSeriesProperties.hlcAreaStyle.highCloseFillColor": string; /** * Main series hlc area style high line color. * * @default "#089981" */ "mainSeriesProperties.hlcAreaStyle.highLineColor": string; /** * Main series hlc area style high line style. * * @default LineStyle.Solid */ "mainSeriesProperties.hlcAreaStyle.highLineStyle": OverrideLineStyle; /** * Main series hlc area style high line width. * * @default 2 */ "mainSeriesProperties.hlcAreaStyle.highLineWidth": number; /** * Main series hlc area style low line color. * * @default "#F23645" */ "mainSeriesProperties.hlcAreaStyle.lowLineColor": string; /** * Main series hlc area style low line style. * * @default LineStyle.Solid */ "mainSeriesProperties.hlcAreaStyle.lowLineStyle": OverrideLineStyle; /** * Main series hlc area style low line width. * * @default 2 */ "mainSeriesProperties.hlcAreaStyle.lowLineWidth": 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 Line With Markers style Line Color. * * @default '#2962FF' */ "mainSeriesProperties.lineWithMarkersStyle.color": string; /** * Main series Line With Markers style Line style. * * @default LineStyle.Solid */ "mainSeriesProperties.lineWithMarkersStyle.linestyle": OverrideLineStyle; /** * Main series Line With Markers style Line width. * * @default 2 */ "mainSeriesProperties.lineWithMarkersStyle.linewidth": number; /** * Main series Line With Markers style Price Source. * * @default 'close' */ "mainSeriesProperties.lineWithMarkersStyle.priceSource": string; /** * Show positions. * * Trading Platform only */ "tradingProperties.showPositions": boolean; /** * Show profit & loss for positions. * * Trading Platform only */ "tradingProperties.positionPL.visibility": boolean; /** * Displayed unit for profit & loss for positions. * * Trading Platform only */ "tradingProperties.positionPL.display": PlDisplay; /** * Show profit & loss for brackets. * * Trading Platform only */ "tradingProperties.bracketsPL.visibility": boolean; /** * Displayed unit for profit & loss for brackets. * * Trading Platform only */ "tradingProperties.bracketsPL.display": PlDisplay; /** * Show profit & loss for brackets and positions. * * Trading Platform only */ "tradingProperties.positionAndBracketsPL": boolean; /** * Show orders. * * Trading Platform only */ "tradingProperties.showOrders": boolean; /** * Show executions. * * Trading Platform only */ "tradingProperties.showExecutions": boolean; /** * Show execution shapes. * * Trading Platform only */ "tradingProperties.showExecutionsLabels": boolean; /** * Show reverse position. * * Trading Platform only */ "tradingProperties.showReverse": boolean; /** * Extend lines to the left for positions and orders. * * Trading Platform only */ "tradingProperties.extendLeft": boolean; /** * Displayed lines length for positions and orders. * * Trading Platform only */ "tradingProperties.lineLength": number; /** * Horizontal alignment of labels on position and order lines. * * Trading Platform only */ "tradingProperties.horizontalAlignment": TradedGroupHorizontalAlignment; /** * Width of line for position and order lines. * * Trading Platform only */ "tradingProperties.lineWidth": number; /** * Style of line for position and order lines. * * Trading Platform only */ /** * Size of the volume panel. * Only works when `volume_force_overlay` featureset is disabled. * * @default PaneSize.Large */ "volumePaneSize": PaneSize; } /** * A chart template. */ export interface ChartTemplate { /** * The template content. */ content?: ChartTemplateContent; } /** * Chart template content. The properties of the chart that are saved/loaded when the library saves/loads a chart template. */ export interface ChartTemplateContent { [key: string]: any; /** * Chart properties (for example color, etc). */ chartProperties?: { /** * Chart pane properties. */ paneProperties: any; /** * Chart scales properties. */ scalesProperties: any; }; /** * Series properties (for example chart style, etc). */ mainSourceProperties?: any; /** * The version of the chart template. */ version?: number; } export interface ChartingLibraryWidgetConstructor { /** * Constructor for the Advanced Charts Widget * @param {ChartingLibraryWidgetOptions|TradingTerminalWidgetOptions} options - Constructor options */ new (options: ChartingLibraryWidgetOptions | TradingTerminalWidgetOptions): IChartingLibraryWidget; } export interface ChartingLibraryWidgetOptions { /** * 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/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` makes the library write detailed [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api) logs into the browser console. * Alternatively, you can use the [`charting_library_debug_mode`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#charting_library_debug_mode) featureset or the {@link IChartingLibraryWidget.setDebugMode} method. * * ```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 in [Featuresets](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 in [Featuresets](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 the 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 allowed at one time within the 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 search requests when the user enters the symbol name in the [Symbol Search](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search). * * ```javascript * symbol_search_request_delay: 1000, * ``` */ symbol_search_request_delay?: number; /** * Sets the default time frame of the chart. * * The time frame can be relative to the current date, or a range. * * A relative time frame 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 time zone of the chart. The time on the timescale is displayed according to this time zone. * See the [list of supported time zones](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezones#supported-time-zones) for available values. Set it to `exchange` to use the exchange time zone. 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 chart API. * Refer to [Save and load REST API](https://www.tradingview.com/charting-library-docs/latest/api/save-load-rest-api) for more information. * * ```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. * Refer to [Saving and Loading Charts](https://www.tradingview.com/charting-library-docs/latest/saving_loading/saving_loading) for more information. * * ```javascript * client_id: 'yourserver.com', * ``` */ client_id?: string; /** * Set the user ID for the high-level saving / loading charts API. * Refer to [Saving and Loading Charts](https://www.tradingview.com/charting-library-docs/latest/saving_loading/saving_loading) for more information. * * ```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/saving_loading) first to make it work. * * Note that the {@link symbol} property takes precedence over `load_last_chart`. If `symbol` is specified, its value is displayed on the chart instead of the saved symbol. To avoid this issue, consider removing the `symbol` property when `load_last_chart` is enabled. * * ```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. * Refer to [Indicator Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides#specify-default-properties) for more information. * Overrides for built-in indicators are listed in {@link StudyOverrides}. * * ```javascript * studies_overrides: { * "volume.volume.color.0": "#00FFFF", * }, * ``` */ studies_overrides?: Partial; /** * 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 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/Overrides). */ overrides?: Partial; /** * This URL is used to send a POST request with binary chart snapshots when a user clicks the [snapshot](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Snapshots) 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 response. * * ```javascript * snapshot_url: "https://myserver.com/snapshot", * ``` */ snapshot_url?: string; /** * List of visible time frames that can be selected at the bottom of the chart. See [Time frame toolbar](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale#time-frame-toolbar) for more information. Time frame is an object containing the 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; /** * Changes the font family used on the chart including the [time scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale), [price scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale), and chart's pane. * If you want to customize fonts outside the chart, for example, within [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) or another widget, * you should use the {@link ChartingLibraryWidgetOptions.custom_css_url} property to provide custom CSS styles. * * Specify `custom_font_family` in [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) as follows: * * ```javascript * custom_font_family: "'Inconsolata', monospace", * ``` * * The `custom_font_family` value should have the same format as the `font-family` property in CSS. * To use a font that is not available by default on your system, you should first add this font to your [custom CSS](#custom_css_url). * For example, the code sample below imports a Google font into your custom CSS: * * ```css * @import url('https://fonts.googleapis.com/css2?family=Inconsolata:wght@500&display=swap'); * ``` * */ custom_font_family?: string; /** * Elements that should be marked as favorites for a new browser or user. * You can use this property to specify default favorite chart types, drawings, indicators, and resolutions. * To do this, assign a {@link Favorites} object to `favorites`. The example of such object is demonstrated below. * * ```javascript * favorites: { * intervals: ["1D", "3D", "3W", "W", "M"], * indicators: ["Awesome Oscillator", "Bollinger Bands"], * drawingTools: ['LineToolBrush', 'LineToolCallout', 'LineToolCircle'], * chartTypes: ['Area', 'Candles'], * }, * ``` * * To allow users to add/remove items from favorites, enable the [`items_favoriting`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#items_favoriting) featureset. * * Note that favorites saved in [`localStorage`](https) take precedence over the ones specified in the `favorites` property. * Therefore, the library tries to load the favorites from `localStorage` first, and then use the elements in `favorites` if there is nothing saved in `localStorage`. * If you want the elements specified within `favorites` to always apply, disable `localStorage` using the [`use_localstorage_for_settings`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#use_localstorage_for_settings) featureset. * * You can also use {@link ChartingLibraryWidgetOptions.settings_adapter} to store favorites. These favorites take precedence over favorites in the `favorites` property and `localStorage`. * Refer to the [Customization precedence](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedence) article to learn more about the application order of different approaches for changing the chart appearance and behavior. */ favorites?: Favorites; /** * An object containing the save/load functions. * It is used to implement a custom save/load algorithm. * Refer to [API handlers](https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapter) for more information. */ 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 [user settings](https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings) to your preferred storage, including the server-side one. * * Example: * ```javascript * settings_adapter: { * initialSettings: { * "symbolWatermark": '{ "visibility": "true", "color": "rgba(244, 67, 54, 0.25)" }', * "trading.Broker": '{"qty": {"AAPL": 10, "NasdaqNM:AAPL": 10}, "orderType": {"NasdaqNM:AAPL": 3}}', * }, * setValue: function(key, value) { * console.log(`set value: ${key} ${value}`); * }, * removeValue: function(key) { * console.log(`remove value: ${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. * * Refer to [Custom indicators](https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom_studies) for more information. * * ```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 Security Info dialog. * * Refer to [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; /** * Use this property to override the [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu). You can also change the menu on the fly using the {@link IChartingLibraryWidget.onContextMenu} method. */ 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 a custom translation function for UI strings. * It accepts the original text, the singular form of the text, and the translated text as arguments. * The function should return a string with the new translation or `null` to fall back to the default translation. * * The example below shows how to rename the "Trend Line" drawing to "Line Drawing". * * ```javascript * custom_translate_function: (originalText, singularOriginalText, translatedText) => { * if (originalText === "Trend Line") { * return "Line Drawing"; * } * return null; * } * ``` */ custom_translate_function?: CustomTranslateFunction; /** * Use this property to set a function to override the symbol input from the [Symbol Search](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search). * * For example, 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 time zones. * * Refer to [Timezones](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezones) for more information. */ custom_timezones?: CustomAliasedTimezone[]; /** * Use this property to set your own chart description function. `context` will be passed to the function. * * This description is read aloud by screen readers when a chart within the layout is selected via the `Tab` key. * * The function should return either a string with a description or `null` to fallback to the default description. * * ```javascript * custom_chart_description_function: (context) => { * return Promise.resolve(`Chart ${context.chartIndex + 1} of ${context.chartCount}. ${context.chartTypeName} chart of ${context.symbol}.`); * } * ``` */ custom_chart_description_function?: ChartDescriptorFunction; /** * Custom theme colors to override the default light and dark themes. For more information on custom themes, refer to the [Custom themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes) article. */ custom_themes?: CustomThemes; /** * EXPERIMENTAL. Customise the storage of image data for the image drawing tool. * * By default images have no size limit and are saved in the chart layout which may not be suitable, depending on your chart storage implementation. */ image_storage_adapter?: IImageStorageAdapter; } 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; } /** * Overrides for the 'Chop Zone' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ChopZoneIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `columns` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#000080` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Choppiness Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ChoppinessIndexIndicatorOverrides { /** Default value: `#2196F3` */ "hlines background.color": string; /** Default value: `90` */ "hlines background.transparency": number; /** Default value: `true` */ "hlines background.visible": boolean; /** Default value: `#787B86` */ "upperlimit.color": string; /** Default value: `2` */ "upperlimit.linestyle": number; /** Default value: `1` */ "upperlimit.linewidth": number; /** Default value: `true` */ "upperlimit.visible": boolean; /** Default value: `61.8` */ "upperlimit.value": number; /** Default value: `#787B86` */ "lowerlimit.color": string; /** Default value: `2` */ "lowerlimit.linestyle": number; /** Default value: `1` */ "lowerlimit.linewidth": number; /** Default value: `true` */ "lowerlimit.visible": boolean; /** Default value: `38.2` */ "lowerlimit.value": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Override properties for the Circle drawing tool. */ export interface CircleLineToolOverrides { /** Default value: `rgba(255, 152, 0, 0.2)` */ "linetoolcircle.backgroundColor": string; /** Default value: `false` */ "linetoolcircle.bold": boolean; /** Default value: `#FF9800` */ "linetoolcircle.color": string; /** Default value: `true` */ "linetoolcircle.fillBackground": boolean; /** Default value: `14` */ "linetoolcircle.fontSize": number; /** Default value: `false` */ "linetoolcircle.italic": boolean; /** Default value: `2` */ "linetoolcircle.linewidth": number; /** Default value: `#FF9800` */ "linetoolcircle.textColor": 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; /** Hide studies from Legend */ hideStudiesFromLegend: boolean; } export interface Colors { blue: "#2962ff"; gray: "#787B86"; green: "#4CAF50"; olive: "#808000"; teal: "#00897B"; new: (color: string, transparency: number) => string; } export interface ColumnStylePreferences { /** Up column color */ upColor: string; /** Down column color */ downColor: string; /** Color column based on previous close */ barColorsOnPrevClose: boolean; /** Column baseline position */ baselinePosition: ColumnStyleBaselinePosition; } /** * Override properties for the Comment drawing tool. */ export interface CommentLineToolOverrides { /** Default value: `#2962FF` */ "linetoolcomment.backgroundColor": string; /** Default value: `#2962FF` */ "linetoolcomment.borderColor": string; /** Default value: `#ffffff` */ "linetoolcomment.color": string; /** Default value: `16` */ "linetoolcomment.fontsize": number; /** Default value: `0` */ "linetoolcomment.transparency": number; } /** * Overrides for the 'Commodity Channel Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface CommodityChannelIndexIndicatorOverrides { /** Default value: `#2196F3` */ "hlines background.color": string; /** Default value: `90` */ "hlines background.transparency": number; /** Default value: `true` */ "hlines background.visible": boolean; /** Default value: `#787B86` */ "upperlimit.color": string; /** Default value: `2` */ "upperlimit.linestyle": number; /** Default value: `1` */ "upperlimit.linewidth": number; /** Default value: `true` */ "upperlimit.visible": boolean; /** Default value: `100` */ "upperlimit.value": number; /** Default value: `#787B86` */ "lowerlimit.color": string; /** Default value: `2` */ "lowerlimit.linestyle": number; /** Default value: `1` */ "lowerlimit.linewidth": number; /** Default value: `true` */ "lowerlimit.visible": boolean; /** Default value: `-100` */ "lowerlimit.value": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; /** Default value: `0` */ "smoothed ma.display": number; /** Default value: `0` */ "smoothed ma.linestyle": number; /** Default value: `1` */ "smoothed ma.linewidth": number; /** Default value: `line` */ "smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "smoothed ma.trackprice": boolean; /** Default value: `0` */ "smoothed ma.transparency": number; [key: string]: StudyOverrideValueType; } export interface CommonFillOptions { display: Extract; title: string; } export interface CommonInputOptions { confirm: boolean; display: DisplayOption; group: string; inline: string; tooltip: string; } /** * Overrides for the 'Compare' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface CompareIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `2` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#9C27B0` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * 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; } /** * Overrides for the 'Connors RSI' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ConnorsRSIIndicatorOverrides { /** Default value: `#2196F3` */ "hlines background.color": string; /** Default value: `90` */ "hlines background.transparency": number; /** Default value: `true` */ "hlines background.visible": boolean; /** Default value: `#787B86` */ "upperlimit.color": string; /** Default value: `2` */ "upperlimit.linestyle": number; /** Default value: `1` */ "upperlimit.linewidth": number; /** Default value: `true` */ "upperlimit.visible": boolean; /** Default value: `70` */ "upperlimit.value": number; /** Default value: `#787B86` */ "lowerlimit.color": string; /** Default value: `2` */ "lowerlimit.linestyle": number; /** Default value: `1` */ "lowerlimit.linewidth": number; /** Default value: `true` */ "lowerlimit.visible": boolean; /** Default value: `30` */ "lowerlimit.value": number; /** Default value: `15` */ "crsi.display": number; /** Default value: `0` */ "crsi.linestyle": number; /** Default value: `1` */ "crsi.linewidth": number; /** Default value: `line` */ "crsi.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "crsi.trackprice": boolean; /** Default value: `0` */ "crsi.transparency": number; /** Default value: `#2196F3` */ "crsi.color": string; [key: string]: StudyOverrideValueType; } 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; } /** Use this interface to override the [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu). */ 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 will provide a list of items to display. * This function should return an array of items to display. * * Example: * * ```js * context_menu: { * items_processor: function(items, actionsFactory, params) { * console.log(`Menu name is: ${params.menuName}`); * const newItem = actionsFactory.createAction({ * actionId: 'hello-world', * label: 'Say Hello', * onExecute: function() { * alert('Hello World'); * }, * }); * items.unshift(newItem); * return Promise.resolve(items); * }, * }, * ``` */ items_processor?: ContextMenuItemsProcessor; /** * Provide this function to override the default renderer for context menu so you can adjust existing menu items. */ 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). * The value `'auto'` behaves as `undefined` but additionally checks if there is enough space to place the menu and if it's not then the result value is inverted. */ attachToXBy?: "left" | "right" | "auto"; /** * 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 box}) * - `'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 optional structure that helps to more accurate calculate a position of the menu (see {@link attachToYBy}). */ box?: { /** menu x coordinate */ x: number; /** menu y coordinate */ y: number; /** menu width */ w: number; /** menu height */ h: number; /** x coordinate overlaps */ overlapX?: boolean; }; /** * Additional horizontal margin. */ marginX?: number; /** * Additional vertical margin. */ marginY?: number; } /** * Overrides for the 'Coppock Curve' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface CoppockCurveIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Correlation Coefficient' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface CorrelationCoefficientIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `area` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Correlation - Log' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface CorrelationLogIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * 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`, `groupOfShapes`, `position`, `order`, `priceScale`. */ 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; } | { /** Trading position */ type: "position"; /** id */ id: string | null; } | { /** Trading order */ type: "order"; /** id */ id: string | null; } | { /** Price scale */ type: "priceScale"; /** id */ id: string; /** Pane index */ paneIndex: number; /** Chart index */ chartIndex: number; }; } 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" | "emoji" | "sticker" | "text" | "anchored_text" | "note" | "anchored_note"; /** * The ID of an indicator that the drawing is attached to. * For more information, refer to the [Attach drawing to indicator](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api#attach-drawing-to-indicator) section. */ 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; /** * If `true`, users cannot cancel the drawing creation in the UI. However, users can still click the _Undo_ button to cancel previous actions. */ disableUndo?: boolean; /** * Drawing properties overrides. Refer to [Drawing Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Drawings-Overrides) for more information. */ 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; /** * The ID of an indicator that the drawing is attached to. For more information, refer to the [Attach drawing to indicator](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api#attach-drawing-to-indicator) section. */ ownerStudyId?: EntityId; /** * Enable/disable filling the drawing with color (if the drawing supports filling). */ filled?: boolean; /** * Specify an icon to render. Only icons from the [Drawings list](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/Drawings-List#icons) are supported. * Note that the value should be a **hex number**, not a string. */ 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 crosshair time coordinate represented with a UNIX timestamp in UTC. * You can use this property to do some calculations or retrieve additional data from the datafeed. */ time: number; /** * The price coordinate of the crosshair. */ price: number; /** * The crosshair time coordinate represented with a UNIX timestamp in the selected time zone. * You can use this property to display the crosshair time value in the UI, for example, in a tooltip or data window. */ userTime?: number; /** * Series and study values at the crosshair position. The object keys are study or series IDs, and the object value are study or series values. * The ID for the main series will always be the string `'_seriesId'`. */ entityValues?: Record; /** * X coordinate of the crosshair relative to the left edge of the element containing the library. */ offsetX?: number; /** * Y coordinate of the crosshair relative to the top edge of the element containing the library. */ offsetY?: number; } /** * Data source (a series or a study) values for a crosshair position. */ export interface CrossHairMovedEventSource { /** * `true` if the source is hovered by the crosshair `false` otherwise. */ isHovered: boolean; /** * The title of the source. Matches the title shown in the data window. */ title: string; /** * The values of the source. Matches the values shown in the data window. */ values: CrossHairMovedEventSourceValue[]; } export interface CrossHairMovedEventSourceValue { /** * Value title. E.g. 'open', 'high', 'change', etc. Matches the title shown in the data window. */ title: string; /** * The value formatted as a string. Matches the value shown in the data window. */ value: string; } /** * Override properties for the Crossline drawing tool. */ export interface CrosslineLineToolOverrides { /** Default value: `#2962FF` */ "linetoolcrossline.linecolor": string; /** Default value: `0` */ "linetoolcrossline.linestyle": number; /** Default value: `2` */ "linetoolcrossline.linewidth": number; /** Default value: `true` */ "linetoolcrossline.showPrice": boolean; /** Default value: `true` */ "linetoolcrossline.showTime": boolean; } 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; } /** * Contains information on the currency currently displayed on the [price scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale). * To get a `CurrencyInfo` instance, call the {@link IPriceScaleApi.currency} method. */ export interface CurrencyInfo { /** * Returns the currently selected currency for the [price scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale). Returns `null` if there are several different currencies on the scale. */ selectedCurrency: string | null; /** * Original currencies for the price scale. */ originalCurrencies: string[]; /** * Available currencies for the price scale provided by the datafeed. */ currencies: string[]; /** * Symbols on the price scale */ symbols: string[]; } 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 time zone. */ formatLocal(date: Date): string; /** * Returns a value in a format known by the UI. * Required when using `dateFormatter`, it has to return a date in the following format: `YYYY-MM-DD`. */ parse(value: string): 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 (time zone) */ timeFormatter?: CustomFormatter; /** * Used to format the date displayed over the timescale when hovering over a chart. * Note that by declaring this formatter all the default ones defined in Chart settings/Scales/Date format * will display the exact same outcome as the formatter. */ 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 time zone. */ tickMarkFormatter?: (date: Date, tickMarkType: TickMarkType) => string; /** Used to format numeric price values on the [price scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale) and [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) (*Last* and *Chg* columns). */ 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 library */ readonly name: string; /** * The metainfo field is designed to contain the main info about the custom study. * * Refer to [Custom Studies Metainfo](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/metainfo) for more information. */ readonly metainfo: StudyMetaInfo; /** * The field should contain an ES5 constructor function. The library applies the `new` operator to the constructor to create an instance of the custom indicator. * The constructor contains the mandatory `main` method and the optional `init` method. * Once the indicator instance is created, the library calls `init` (if exists) and `main` sequentially with empty context to collect information about all variables. * * Refer to the [Constructor](https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom-indicator-constructor) article 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; } /** * Action link to be displayed at the end of the section for the * status item in the pop-up tooltip. */ export interface CustomStatusDropDownAction { /** * Text to be displayed as the link */ text: string; /** * Tooltip text to be displayed when the user hovers over * the action link. */ tooltip?: string; /** * Callback function to be executed when the user clicks * on the action. */ onClick: () => void; } /** * Specifies the content to be displayed within a section of * the pop-up tooltip which is displayed when a user clicks on * the symbol status items. * * The pop-up tooltip should be used to display additional * information related to the status item. */ export interface CustomStatusDropDownContent { /** * Title to be displayed next to the icon for this section * of the pop-up tooltip. */ title: string; /** * Color to be used for the icon and title. If unspecified * then the color from the status item will be used. */ color?: string; /** * Icon to be displayed next to the title for this section * of the pop-up tooltip. If unspecified then the icon from * the status item will be used. */ icon?: string; /** * Content to the displayed within this section of the * pop-up tooltip. * * **It is essential to protect the content you provide * against cross-site scripting (XSS) attacks, as these * strings will be interpreted as HTML markup.** */ content: string[]; /** * Optional action link to be displayed at the bottom of * the status section. */ action?: CustomStatusDropDownAction; } /** * Study format description used in custom study formatters. */ export interface CustomStudyFormatterFormat { /** * The format of the plot. */ type: "price" | "volume" | "percent" | "inherit"; /** * 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; /** Allow usage of priceFormatter */ isPriceFormatterNeeded?: boolean; } /** * Custom colors to override either the default light or dark theme. */ export interface CustomThemeColors { /** * Replaces the TradingView blue color. */ color1: ColorGradient; /** * Replaces the TradingView grey color. */ color2: ColorGradient; /** * Replaces the TradingView red color. */ color3: ColorGradient; /** * Replaces the TradingView green color. */ color4: ColorGradient; /** * Replaces the TradingView orange color. */ color5: ColorGradient; /** * Replaces the TradingView purple color. */ color6: ColorGradient; /** * Replaces the TradingView yellow color. */ color7: ColorGradient; white: string; black: string; } /** * Custom color palettes for the light and dark themes. */ export interface CustomThemes { light: CustomThemeColors; dark: CustomThemeColors; } 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; } /** * Override properties for the Cypherpattern drawing tool. */ export interface CypherpatternLineToolOverrides { /** Default value: `#2962FF` */ "linetoolcypherpattern.backgroundColor": string; /** Default value: `false` */ "linetoolcypherpattern.bold": boolean; /** Default value: `#2962FF` */ "linetoolcypherpattern.color": string; /** Default value: `true` */ "linetoolcypherpattern.fillBackground": boolean; /** Default value: `12` */ "linetoolcypherpattern.fontsize": number; /** Default value: `false` */ "linetoolcypherpattern.italic": boolean; /** Default value: `2` */ "linetoolcypherpattern.linewidth": number; /** Default value: `#ffffff` */ "linetoolcypherpattern.textcolor": string; /** Default value: `85` */ "linetoolcypherpattern.transparency": number; } /** * 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; } /** * Datafeed configuration data. * Pass the resulting array of properties as a parameter to {@link OnReadyCallback} of the [`onReady`](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#onready) method. */ 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 [resolutions](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution) that the chart should support. * Each item of the array is expected to be a string that has a specific [format](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-format). * If you set this property to `undefined` or an empty array, the _Resolution_ drop-down menu displays the list of resolutions available for * the current symbol ({@link LibrarySymbolInfo.supported_resolutions}). * * @example * `["1", "15", "240", "D", "6M"]` will give you "1 minute, 15 minutes, 4 hours, 1 day, 6 months" in the _Resolution_ drop-down menu. */ 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](https://www.tradingview.com/charting-library-docs/latest/ui_elements/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. * Refer to [Symbol grouping](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search#symbol-grouping) for more information. */ symbols_grouping?: Record; } /** * This object contains symbol quote values, where a [quote](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/quotes) represents a set of data describing the current price. * The library uses quote data for various trading functionalities, including the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket), [Legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend), * and widgets, such as [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List), [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details), * [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news), and [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#depth-of-market). * * While all properties in this object are marked as optional, populating most of them is required for supporting trading functionalities. * Providing values that do not match the expected data types can cause issues such as UI [loading delays](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues#delays-in-trading-platform-ui-elements) or [missing data](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues#quotes-are-not-displayed-or-refreshed). * See property descriptions for more information. */ export interface DatafeedQuoteValues { /** * Price change. It is usually calculated as a difference between the current price and close price of the previous day (regular session). * In the UI, `ch` and {@link chp} are represented as the last day change parameter in *Data Window*. * You can also display these values in the [legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#last-day-change-values). * If `ch` and `chp` are not provided, `0.00 (0.00%)` is displayed instead. * * Note that `ch` and `chp` are **required** for mobile apps. Otherwise, [`NaN` values](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#nan-values-in-legend) will appear in the legend. */ ch?: number; /** * Price change percentage. In the UI, `chp` and {@link ch} are represented as the last day change parameter in *Data Window*. * You can also display these values in the [Legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#last-day-change-values). * If `ch` and `chp` are not provided, `0.00 (0.00%)` is displayed instead. * * Note that `ch` and `chp` are **required** for mobile apps. Otherwise, [`NaN` values](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#nan-values-in-legend) will appear in the Legend. */ chp?: number; /** Short name for a symbol. Short name is used in the title for the [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news), [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) and [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widgets. You can disable the [`prefer_quote_short_name`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#prefer_quote_short_name) to use the {@link LibrarySymbolInfo.ticker} value instead. */ short_name?: string; /** The name of the exchange. The exchange name is displayed in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ exchange?: string; /** A short description of the symbol. This description is displayed in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget and the tooltip of the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) widget. */ description?: string; /** * The price at which the most recent trade of a security occurred, regardless of whether it was a buy or sell. * Required for the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket), [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#depth-of-market), [Buy/Sell buttons](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#buysell-buttons-and-lines), and [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) and [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) widgets. */ lp?: number; /** Ask price – the lowest price a seller is willing to accept for a security. The value is displayed in the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) and [Buy/Sell buttons](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#buysell-buttons-and-lines). */ ask?: number; /** Bid price – the highest price a buyer is willing to pay for a security. The value is displayed in the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) and [Buy/Sell buttons](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#buysell-buttons-and-lines). */ bid?: number; /** Spread – the difference between the ask and bid prices. The value is displayed between [Buy/Sell buttons](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#buysell-buttons-and-lines). */ spread?: number; /** Today's opening price */ open_price?: number; /** Today's high price. The value is displayed in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ high_price?: number; /** Today's low price. The value is displayed in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ low_price?: number; /** * Closing price of the symbol from the previous regular market session. * * Required for mobile apps. Otherwise, `NaN` values will appear in the [Legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend). */ prev_close_price?: number; /** Today's trading volume. This value is displayed in the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) widget. */ volume?: number; /** Original name */ original_name?: string; /** Pre-/post-market price. This value is required to display the [pre-/post-market price line](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions#enable-the-price-line) on the chart and information on the extended session in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ rtc?: number; /** Pre-/post-market price update time. This value is required to display information on the [extended session](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions) in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ rtc_time?: number; /** Pre-/post-market price change. This value is required to display information on the [extended session](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions) in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ rch?: number; /** Pre-/post-market price change percentage. This value is required to display information on the [extended session](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions) the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ rchp?: number; [valueName: string]: string | number | 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; } /** * Overrides for the 'Detrended Price Oscillator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface DetrendedPriceOscillatorIndicatorOverrides { /** Default value: `#787B86` */ "zero.color": string; /** Default value: `2` */ "zero.linestyle": number; /** Default value: `1` */ "zero.linewidth": number; /** Default value: `true` */ "zero.visible": boolean; /** Default value: `0` */ "zero.value": number; /** Default value: `15` */ "dpo.display": number; /** Default value: `0` */ "dpo.linestyle": number; /** Default value: `1` */ "dpo.linewidth": number; /** Default value: `line` */ "dpo.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "dpo.trackprice": boolean; /** Default value: `0` */ "dpo.transparency": number; /** Default value: `#43A047` */ "dpo.color": string; [key: string]: StudyOverrideValueType; } export interface DialogParams { /** Dialog title */ title: string; /** Dialog content */ body: string; /** Callback */ callback: CallbackType; } /** * Overrides for the 'Directional Movement' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface DirectionalMovementIndicatorOverrides { /** Default value: `15` */ "+di.display": number; /** Default value: `0` */ "+di.linestyle": number; /** Default value: `1` */ "+di.linewidth": number; /** Default value: `line` */ "+di.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "+di.trackprice": boolean; /** Default value: `0` */ "+di.transparency": number; /** Default value: `#2196F3` */ "+di.color": string; /** Default value: `15` */ "-di.display": number; /** Default value: `0` */ "-di.linestyle": number; /** Default value: `1` */ "-di.linewidth": number; /** Default value: `line` */ "-di.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "-di.trackprice": boolean; /** Default value: `0` */ "-di.transparency": number; /** Default value: `#FF6D00` */ "-di.color": string; /** Default value: `15` */ "adx.display": number; /** Default value: `0` */ "adx.linestyle": number; /** Default value: `1` */ "adx.linewidth": number; /** Default value: `line` */ "adx.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "adx.trackprice": boolean; /** Default value: `0` */ "adx.transparency": number; /** Default value: `#F50057` */ "adx.color": string; /** Default value: `15` */ "dx.display": number; /** Default value: `0` */ "dx.linestyle": number; /** Default value: `1` */ "dx.linewidth": number; /** Default value: `line` */ "dx.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "dx.trackprice": boolean; /** Default value: `0` */ "dx.transparency": number; /** Default value: `#FFA726` */ "dx.color": string; /** Default value: `15` */ "adxr.display": number; /** Default value: `0` */ "adxr.linestyle": number; /** Default value: `1` */ "adxr.linewidth": number; /** Default value: `line` */ "adxr.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "adxr.trackprice": boolean; /** Default value: `0` */ "adxr.transparency": number; /** Default value: `#ab47bc` */ "adxr.color": string; [key: string]: StudyOverrideValueType; } export interface DisconnectionInfo { message?: string; heading?: string; additionalInfo?: string; disconnectType?: DisconnectType; } /** * Override properties for the Disjointangle drawing tool. */ export interface DisjointangleLineToolOverrides { /** Default value: `rgba(8, 153, 129, 0.2)` */ "linetooldisjointangle.backgroundColor": string; /** Default value: `false` */ "linetooldisjointangle.bold": boolean; /** Default value: `false` */ "linetooldisjointangle.extendLeft": boolean; /** Default value: `false` */ "linetooldisjointangle.extendRight": boolean; /** Default value: `true` */ "linetooldisjointangle.fillBackground": boolean; /** Default value: `12` */ "linetooldisjointangle.fontsize": number; /** Default value: `false` */ "linetooldisjointangle.italic": boolean; /** Default value: `false` */ "linetooldisjointangle.labelBold": boolean; /** Default value: `14` */ "linetooldisjointangle.labelFontSize": number; /** Default value: `left` */ "linetooldisjointangle.labelHorzAlign": string; /** Default value: `false` */ "linetooldisjointangle.labelItalic": boolean; /** Default value: `#089981` */ "linetooldisjointangle.labelTextColor": string; /** Default value: `bottom` */ "linetooldisjointangle.labelVertAlign": string; /** Default value: `false` */ "linetooldisjointangle.labelVisible": boolean; /** Default value: `0` */ "linetooldisjointangle.leftEnd": number; /** Default value: `#089981` */ "linetooldisjointangle.linecolor": string; /** Default value: `0` */ "linetooldisjointangle.linestyle": number; /** Default value: `2` */ "linetooldisjointangle.linewidth": number; /** Default value: `0` */ "linetooldisjointangle.rightEnd": number; /** Default value: `false` */ "linetooldisjointangle.showBarsRange": boolean; /** Default value: `false` */ "linetooldisjointangle.showDateTimeRange": boolean; /** Default value: `false` */ "linetooldisjointangle.showPriceRange": boolean; /** Default value: `false` */ "linetooldisjointangle.showPrices": boolean; /** Default value: `#089981` */ "linetooldisjointangle.textcolor": string; /** Default value: `20` */ "linetooldisjointangle.transparency": number; } /** * Overrides for the 'Donchian Channels' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface DonchianChannelsIndicatorOverrides { /** Default value: `#2196F3` */ "plots background.color": string; /** Default value: `95` */ "plots background.transparency": number; /** Default value: `true` */ "plots background.visible": boolean; /** Default value: `15` */ "lower.display": number; /** Default value: `0` */ "lower.linestyle": number; /** Default value: `1` */ "lower.linewidth": number; /** Default value: `line` */ "lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lower.trackprice": boolean; /** Default value: `0` */ "lower.transparency": number; /** Default value: `#2196F3` */ "lower.color": string; /** Default value: `15` */ "upper.display": number; /** Default value: `0` */ "upper.linestyle": number; /** Default value: `1` */ "upper.linewidth": number; /** Default value: `line` */ "upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "upper.trackprice": boolean; /** Default value: `0` */ "upper.transparency": number; /** Default value: `#2196F3` */ "upper.color": string; /** Default value: `15` */ "basis.display": number; /** Default value: `0` */ "basis.linestyle": number; /** Default value: `1` */ "basis.linewidth": number; /** Default value: `line` */ "basis.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "basis.trackprice": boolean; /** Default value: `0` */ "basis.transparency": number; /** Default value: `#FF6D00` */ "basis.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Double EMA' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface DoubleEMAIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#43A047` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Drag start parameters */ export interface DragStartParams { /** * Prevent default drag event */ preventDefault: () => void; /** * Hovered source ID */ hoveredSourceId: EntityId | null; /** * Export data function */ exportData: (exportOptions: Partial) => void; /** * Set data function */ setData: (format: string, data: string) => void; /** * Set drag image */ setDragImage: (image: HTMLElement, xOffset: number, yOffset: number) => void; } /** Item within a dropdown menu */ export interface DropdownItem { /** Title of the menu item */ title: string; /** Icons for the menu item (SVG mark-up) */ icon?: 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"; } /** * Overrides for the 'EMA Cross' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface EMACrossIndicatorOverrides { /** Default value: `15` */ "short:plot.display": number; /** Default value: `0` */ "short:plot.linestyle": number; /** Default value: `1` */ "short:plot.linewidth": number; /** Default value: `line` */ "short:plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "short:plot.trackprice": boolean; /** Default value: `0` */ "short:plot.transparency": number; /** Default value: `#FF6D00` */ "short:plot.color": string; /** Default value: `15` */ "long:plot.display": number; /** Default value: `0` */ "long:plot.linestyle": number; /** Default value: `1` */ "long:plot.linewidth": number; /** Default value: `line` */ "long:plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "long:plot.trackprice": boolean; /** Default value: `0` */ "long:plot.transparency": number; /** Default value: `#43A047` */ "long:plot.color": string; /** Default value: `15` */ "crosses.display": number; /** Default value: `0` */ "crosses.linestyle": number; /** Default value: `4` */ "crosses.linewidth": number; /** Default value: `cross` */ "crosses.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "crosses.trackprice": boolean; /** Default value: `0` */ "crosses.transparency": number; /** Default value: `#2196F3` */ "crosses.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Ease Of Movement' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface EaseOfMovementIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#43A047` */ "plot.color": string; [key: string]: StudyOverrideValueType; } export interface EditObjectDialogEventParams { /** Dialog type */ objectType: EditObjectDialogObjectType; /** Title of the object described within the dialog */ scriptTitle: string; } /** * Overrides for the 'Elder's Force Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface EldersForceIndexIndicatorOverrides { /** Default value: `#787B86` */ "zero.color": string; /** Default value: `2` */ "zero.linestyle": number; /** Default value: `1` */ "zero.linewidth": number; /** Default value: `true` */ "zero.visible": boolean; /** Default value: `0` */ "zero.value": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#F23645` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Override properties for the Elliottcorrection drawing tool. */ export interface ElliottcorrectionLineToolOverrides { /** Default value: `#3d85c6` */ "linetoolelliottcorrection.color": string; /** Default value: `7` */ "linetoolelliottcorrection.degree": number; /** Default value: `2` */ "linetoolelliottcorrection.linewidth": number; /** Default value: `true` */ "linetoolelliottcorrection.showWave": boolean; } /** * Override properties for the Elliottdoublecombo drawing tool. */ export interface ElliottdoublecomboLineToolOverrides { /** Default value: `#6aa84f` */ "linetoolelliottdoublecombo.color": string; /** Default value: `7` */ "linetoolelliottdoublecombo.degree": number; /** Default value: `2` */ "linetoolelliottdoublecombo.linewidth": number; /** Default value: `true` */ "linetoolelliottdoublecombo.showWave": boolean; } /** * Override properties for the Elliottimpulse drawing tool. */ export interface ElliottimpulseLineToolOverrides { /** Default value: `#3d85c6` */ "linetoolelliottimpulse.color": string; /** Default value: `7` */ "linetoolelliottimpulse.degree": number; /** Default value: `2` */ "linetoolelliottimpulse.linewidth": number; /** Default value: `true` */ "linetoolelliottimpulse.showWave": boolean; } /** * Override properties for the Elliotttriangle drawing tool. */ export interface ElliotttriangleLineToolOverrides { /** Default value: `#FF9800` */ "linetoolelliotttriangle.color": string; /** Default value: `7` */ "linetoolelliotttriangle.degree": number; /** Default value: `2` */ "linetoolelliotttriangle.linewidth": number; /** Default value: `true` */ "linetoolelliotttriangle.showWave": boolean; } /** * Override properties for the Elliotttriplecombo drawing tool. */ export interface ElliotttriplecomboLineToolOverrides { /** Default value: `#6aa84f` */ "linetoolelliotttriplecombo.color": string; /** Default value: `7` */ "linetoolelliotttriplecombo.degree": number; /** Default value: `2` */ "linetoolelliotttriplecombo.linewidth": number; /** Default value: `true` */ "linetoolelliotttriplecombo.showWave": boolean; } /** * Override properties for the Ellipse drawing tool. */ export interface EllipseLineToolOverrides { /** Default value: `rgba(242, 54, 69, 0.2)` */ "linetoolellipse.backgroundColor": string; /** Default value: `false` */ "linetoolellipse.bold": boolean; /** Default value: `#F23645` */ "linetoolellipse.color": string; /** Default value: `true` */ "linetoolellipse.fillBackground": boolean; /** Default value: `14` */ "linetoolellipse.fontSize": number; /** Default value: `false` */ "linetoolellipse.italic": boolean; /** Default value: `2` */ "linetoolellipse.linewidth": number; /** Default value: `#F23645` */ "linetoolellipse.textColor": string; /** Default value: `50` */ "linetoolellipse.transparency": number; } /** * Override properties for the Emoji drawing tool. */ export interface EmojiLineToolOverrides { /** Default value: `1.5707963267948966` */ "linetoolemoji.angle": number; /** * Default value: `😀` * * Refer to [Drawings list](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/Drawings-List#emojis) for a list of emojis. * Note that the emoji code requires `u/` before it. */ /** Default value: `40` */ "linetoolemoji.size": number; } export interface EmojiOptions { /** Emoji */ emoji: string; } export interface EntityInfo { /** Entity id (string) */ id: EntityId; /** Name of entity */ name: string; } /** * Overrides for the 'Envelopes' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface EnvelopesIndicatorOverrides { /** Default value: `#2196F3` */ "plots background.color": string; /** Default value: `95` */ "plots background.transparency": number; /** Default value: `true` */ "plots background.visible": boolean; /** Default value: `15` */ "average.display": number; /** Default value: `0` */ "average.linestyle": number; /** Default value: `1` */ "average.linewidth": number; /** Default value: `line` */ "average.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "average.trackprice": boolean; /** Default value: `0` */ "average.transparency": number; /** Default value: `#FF6D00` */ "average.color": string; /** Default value: `15` */ "upper.display": number; /** Default value: `0` */ "upper.linestyle": number; /** Default value: `1` */ "upper.linewidth": number; /** Default value: `line` */ "upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "upper.trackprice": boolean; /** Default value: `0` */ "upper.transparency": number; /** Default value: `#2196F3` */ "upper.color": string; /** Default value: `15` */ "lower.display": number; /** Default value: `0` */ "lower.linestyle": number; /** Default value: `1` */ "lower.linewidth": number; /** Default value: `line` */ "lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lower.trackprice": boolean; /** Default value: `0` */ "lower.transparency": number; /** Default value: `#2196F3` */ "lower.color": string; [key: string]: StudyOverrideValueType; } 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 when a buy or sell order is completed for a financial instrument. */ 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; } /** * Override properties for the Execution drawing tool. */ export interface ExecutionLineToolOverrides { /** Default value: `#4094e8` */ "linetoolexecution.arrowBuyColor": string; /** Default value: `8` */ "linetoolexecution.arrowHeight": number; /** Default value: `#e75656` */ "linetoolexecution.arrowSellColor": string; /** Default value: `1` */ "linetoolexecution.arrowSpacing": number; /** Default value: `buy` */ "linetoolexecution.direction": string; /** Default value: `false` */ "linetoolexecution.fontBold": boolean; /** Default value: `Verdana` */ "linetoolexecution.fontFamily": string; /** Default value: `false` */ "linetoolexecution.fontItalic": boolean; /** Default value: `10` */ "linetoolexecution.fontSize": number; /** Default value: `undefined` */ "linetoolexecution.text": string; /** Default value: `#000000` */ "linetoolexecution.textColor": string; /** Default value: `0` */ "linetoolexecution.textTransparency": number; /** Default value: `undefined` */ "linetoolexecution.tooltip": string; } 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. * User time is the time that user sees on the chart. * This time depends on the selected time zone and resolution. * * @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; /** * Include open, high, low, and close values for plots that only display a single value on the chart. For example line series or symbols with visible_plot_set = 'c'. */ includeOHLCValuesForSingleValuePlots?: boolean; /** * Include hidden studies in the exported data. * * @default false */ includeHiddenStudies?: 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[][]; } /** * Override properties for the Extended drawing tool. */ export interface ExtendedLineToolOverrides { /** Default value: `false` */ "linetoolextended.alwaysShowStats": boolean; /** Default value: `false` */ "linetoolextended.bold": boolean; /** Default value: `true` */ "linetoolextended.extendLeft": boolean; /** Default value: `true` */ "linetoolextended.extendRight": boolean; /** Default value: `14` */ "linetoolextended.fontsize": number; /** Default value: `center` */ "linetoolextended.horzLabelsAlign": string; /** Default value: `false` */ "linetoolextended.italic": boolean; /** Default value: `0` */ "linetoolextended.leftEnd": number; /** Default value: `#2962FF` */ "linetoolextended.linecolor": string; /** Default value: `0` */ "linetoolextended.linestyle": number; /** Default value: `2` */ "linetoolextended.linewidth": number; /** Default value: `0` */ "linetoolextended.rightEnd": number; /** Default value: `false` */ "linetoolextended.showAngle": boolean; /** Default value: `false` */ "linetoolextended.showBarsRange": boolean; /** Default value: `false` */ "linetoolextended.showDateTimeRange": boolean; /** Default value: `false` */ "linetoolextended.showDistance": boolean; /** Default value: `false` */ "linetoolextended.showMiddlePoint": boolean; /** Default value: `false` */ "linetoolextended.showPercentPriceRange": boolean; /** Default value: `false` */ "linetoolextended.showPipsPriceRange": boolean; /** Default value: `false` */ "linetoolextended.showPriceLabels": boolean; /** Default value: `false` */ "linetoolextended.showPriceRange": boolean; /** Default value: `2` */ "linetoolextended.statsPosition": number; /** Default value: `#2962FF` */ "linetoolextended.textcolor": string; /** Default value: `bottom` */ "linetoolextended.vertLabelsAlign": string; } /** * Favorites which can be defined within the Widget Constructor options (see {@link ChartingLibraryWidgetOptions.favorites}). */ export interface Favorites { /** * An array of time intervals that are marked as favorite. * * Example: `["D", "2D"]` */ intervals?: ResolutionString[]; /** * An array of indicator titles that are marked as favorite. * The names of indicators are identical to the `title` property of the indicator. For built-in indicators * this will match the chart UI in the English version. * * Example: `["Awesome Oscillator", "Bollinger Bands"]`. */ indicators?: string[]; /** * An array of chart types that are marked as favorite. * The names of chart types are listed within the {@link ChartTypeFavorites} or {@link TradingTerminalChartTypeFavorites} type. * * Example: `["Area", "Candles"]`. */ chartTypes?: TChartTypeFavorites[]; /** * 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[]; } /** * Override properties for the Fibchannel drawing tool. */ export interface FibchannelLineToolOverrides { /** Default value: `false` */ "linetoolfibchannel.coeffsAsPercents": boolean; /** Default value: `false` */ "linetoolfibchannel.extendLeft": boolean; /** Default value: `false` */ "linetoolfibchannel.extendRight": boolean; /** Default value: `true` */ "linetoolfibchannel.fillBackground": boolean; /** Default value: `left` */ "linetoolfibchannel.horzLabelsAlign": string; /** Default value: `12` */ "linetoolfibchannel.labelFontSize": number; /** Default value: `0` */ "linetoolfibchannel.level1.coeff": number; /** Default value: `#808080` */ "linetoolfibchannel.level1.color": string; /** Default value: `true` */ "linetoolfibchannel.level1.visible": boolean; /** Default value: `3.618` */ "linetoolfibchannel.level10.coeff": number; /** Default value: `#9c27b0` */ "linetoolfibchannel.level10.color": string; /** Default value: `true` */ "linetoolfibchannel.level10.visible": boolean; /** Default value: `4.236` */ "linetoolfibchannel.level11.coeff": number; /** Default value: `#e91e63` */ "linetoolfibchannel.level11.color": string; /** Default value: `true` */ "linetoolfibchannel.level11.visible": boolean; /** Default value: `1.272` */ "linetoolfibchannel.level12.coeff": number; /** Default value: `#FF9800` */ "linetoolfibchannel.level12.color": string; /** Default value: `false` */ "linetoolfibchannel.level12.visible": boolean; /** Default value: `1.414` */ "linetoolfibchannel.level13.coeff": number; /** Default value: `#F23645` */ "linetoolfibchannel.level13.color": string; /** Default value: `false` */ "linetoolfibchannel.level13.visible": boolean; /** Default value: `2.272` */ "linetoolfibchannel.level14.coeff": number; /** Default value: `#FF9800` */ "linetoolfibchannel.level14.color": string; /** Default value: `false` */ "linetoolfibchannel.level14.visible": boolean; /** Default value: `2.414` */ "linetoolfibchannel.level15.coeff": number; /** Default value: `#4caf50` */ "linetoolfibchannel.level15.color": string; /** Default value: `false` */ "linetoolfibchannel.level15.visible": boolean; /** Default value: `2` */ "linetoolfibchannel.level16.coeff": number; /** Default value: `#089981` */ "linetoolfibchannel.level16.color": string; /** Default value: `false` */ "linetoolfibchannel.level16.visible": boolean; /** Default value: `3` */ "linetoolfibchannel.level17.coeff": number; /** Default value: `#00bcd4` */ "linetoolfibchannel.level17.color": string; /** Default value: `false` */ "linetoolfibchannel.level17.visible": boolean; /** Default value: `3.272` */ "linetoolfibchannel.level18.coeff": number; /** Default value: `#808080` */ "linetoolfibchannel.level18.color": string; /** Default value: `false` */ "linetoolfibchannel.level18.visible": boolean; /** Default value: `3.414` */ "linetoolfibchannel.level19.coeff": number; /** Default value: `#2962FF` */ "linetoolfibchannel.level19.color": string; /** Default value: `false` */ "linetoolfibchannel.level19.visible": boolean; /** Default value: `0.236` */ "linetoolfibchannel.level2.coeff": number; /** Default value: `#F23645` */ "linetoolfibchannel.level2.color": string; /** Default value: `true` */ "linetoolfibchannel.level2.visible": boolean; /** Default value: `4` */ "linetoolfibchannel.level20.coeff": number; /** Default value: `#F23645` */ "linetoolfibchannel.level20.color": string; /** Default value: `false` */ "linetoolfibchannel.level20.visible": boolean; /** Default value: `4.272` */ "linetoolfibchannel.level21.coeff": number; /** Default value: `#9c27b0` */ "linetoolfibchannel.level21.color": string; /** Default value: `false` */ "linetoolfibchannel.level21.visible": boolean; /** Default value: `4.414` */ "linetoolfibchannel.level22.coeff": number; /** Default value: `#e91e63` */ "linetoolfibchannel.level22.color": string; /** Default value: `false` */ "linetoolfibchannel.level22.visible": boolean; /** Default value: `4.618` */ "linetoolfibchannel.level23.coeff": number; /** Default value: `#FF9800` */ "linetoolfibchannel.level23.color": string; /** Default value: `false` */ "linetoolfibchannel.level23.visible": boolean; /** Default value: `4.764` */ "linetoolfibchannel.level24.coeff": number; /** Default value: `#089981` */ "linetoolfibchannel.level24.color": string; /** Default value: `false` */ "linetoolfibchannel.level24.visible": boolean; /** Default value: `0.382` */ "linetoolfibchannel.level3.coeff": number; /** Default value: `#FF9800` */ "linetoolfibchannel.level3.color": string; /** Default value: `true` */ "linetoolfibchannel.level3.visible": boolean; /** Default value: `0.5` */ "linetoolfibchannel.level4.coeff": number; /** Default value: `#4caf50` */ "linetoolfibchannel.level4.color": string; /** Default value: `true` */ "linetoolfibchannel.level4.visible": boolean; /** Default value: `0.618` */ "linetoolfibchannel.level5.coeff": number; /** Default value: `#089981` */ "linetoolfibchannel.level5.color": string; /** Default value: `true` */ "linetoolfibchannel.level5.visible": boolean; /** Default value: `0.786` */ "linetoolfibchannel.level6.coeff": number; /** Default value: `#00bcd4` */ "linetoolfibchannel.level6.color": string; /** Default value: `true` */ "linetoolfibchannel.level6.visible": boolean; /** Default value: `1` */ "linetoolfibchannel.level7.coeff": number; /** Default value: `#808080` */ "linetoolfibchannel.level7.color": string; /** Default value: `true` */ "linetoolfibchannel.level7.visible": boolean; /** Default value: `1.618` */ "linetoolfibchannel.level8.coeff": number; /** Default value: `#2962FF` */ "linetoolfibchannel.level8.color": string; /** Default value: `true` */ "linetoolfibchannel.level8.visible": boolean; /** Default value: `2.618` */ "linetoolfibchannel.level9.coeff": number; /** Default value: `#F23645` */ "linetoolfibchannel.level9.color": string; /** Default value: `true` */ "linetoolfibchannel.level9.visible": boolean; /** Default value: `0` */ "linetoolfibchannel.levelsStyle.linestyle": number; /** Default value: `2` */ "linetoolfibchannel.levelsStyle.linewidth": number; /** Default value: `true` */ "linetoolfibchannel.showCoeffs": boolean; /** Default value: `true` */ "linetoolfibchannel.showPrices": boolean; /** Default value: `80` */ "linetoolfibchannel.transparency": number; /** Default value: `middle` */ "linetoolfibchannel.vertLabelsAlign": string; } /** * Override properties for the Fibcircles drawing tool. */ export interface FibcirclesLineToolOverrides { /** Default value: `false` */ "linetoolfibcircles.coeffsAsPercents": boolean; /** Default value: `true` */ "linetoolfibcircles.fillBackground": boolean; /** Default value: `0.236` */ "linetoolfibcircles.level1.coeff": number; /** Default value: `#F23645` */ "linetoolfibcircles.level1.color": string; /** Default value: `0` */ "linetoolfibcircles.level1.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level1.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level1.visible": boolean; /** Default value: `4.236` */ "linetoolfibcircles.level10.coeff": number; /** Default value: `#e91e63` */ "linetoolfibcircles.level10.color": string; /** Default value: `0` */ "linetoolfibcircles.level10.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level10.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level10.visible": boolean; /** Default value: `4.618` */ "linetoolfibcircles.level11.coeff": number; /** Default value: `#F23645` */ "linetoolfibcircles.level11.color": string; /** Default value: `0` */ "linetoolfibcircles.level11.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level11.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level11.visible": boolean; /** Default value: `0.382` */ "linetoolfibcircles.level2.coeff": number; /** Default value: `#FF9800` */ "linetoolfibcircles.level2.color": string; /** Default value: `0` */ "linetoolfibcircles.level2.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level2.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level2.visible": boolean; /** Default value: `0.5` */ "linetoolfibcircles.level3.coeff": number; /** Default value: `#089981` */ "linetoolfibcircles.level3.color": string; /** Default value: `0` */ "linetoolfibcircles.level3.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level3.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level3.visible": boolean; /** Default value: `0.618` */ "linetoolfibcircles.level4.coeff": number; /** Default value: `#4caf50` */ "linetoolfibcircles.level4.color": string; /** Default value: `0` */ "linetoolfibcircles.level4.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level4.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level4.visible": boolean; /** Default value: `0.786` */ "linetoolfibcircles.level5.coeff": number; /** Default value: `#00bcd4` */ "linetoolfibcircles.level5.color": string; /** Default value: `0` */ "linetoolfibcircles.level5.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level5.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level5.visible": boolean; /** Default value: `1` */ "linetoolfibcircles.level6.coeff": number; /** Default value: `#808080` */ "linetoolfibcircles.level6.color": string; /** Default value: `0` */ "linetoolfibcircles.level6.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level6.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level6.visible": boolean; /** Default value: `1.618` */ "linetoolfibcircles.level7.coeff": number; /** Default value: `#2962FF` */ "linetoolfibcircles.level7.color": string; /** Default value: `0` */ "linetoolfibcircles.level7.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level7.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level7.visible": boolean; /** Default value: `2.618` */ "linetoolfibcircles.level8.coeff": number; /** Default value: `#e91e63` */ "linetoolfibcircles.level8.color": string; /** Default value: `0` */ "linetoolfibcircles.level8.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level8.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level8.visible": boolean; /** Default value: `3.618` */ "linetoolfibcircles.level9.coeff": number; /** Default value: `#2962FF` */ "linetoolfibcircles.level9.color": string; /** Default value: `0` */ "linetoolfibcircles.level9.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.level9.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.level9.visible": boolean; /** Default value: `true` */ "linetoolfibcircles.showCoeffs": boolean; /** Default value: `80` */ "linetoolfibcircles.transparency": number; /** Default value: `#808080` */ "linetoolfibcircles.trendline.color": string; /** Default value: `2` */ "linetoolfibcircles.trendline.linestyle": number; /** Default value: `2` */ "linetoolfibcircles.trendline.linewidth": number; /** Default value: `true` */ "linetoolfibcircles.trendline.visible": boolean; } /** * Override properties for the Fibretracement drawing tool. */ export interface FibretracementLineToolOverrides { /** Default value: `false` */ "linetoolfibretracement.coeffsAsPercents": boolean; /** Default value: `false` */ "linetoolfibretracement.extendLines": boolean; /** Default value: `false` */ "linetoolfibretracement.extendLinesLeft": boolean; /** Default value: `false` */ "linetoolfibretracement.fibLevelsBasedOnLogScale": boolean; /** Default value: `true` */ "linetoolfibretracement.fillBackground": boolean; /** Default value: `left` */ "linetoolfibretracement.horzLabelsAlign": string; /** Default value: `center` */ "linetoolfibretracement.horzTextAlign": string; /** Default value: `12` */ "linetoolfibretracement.labelFontSize": number; /** Default value: `0` */ "linetoolfibretracement.level1.coeff": number; /** Default value: `#808080` */ "linetoolfibretracement.level1.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level1.text": string; /** Default value: `true` */ "linetoolfibretracement.level1.visible": boolean; /** Default value: `3.618` */ "linetoolfibretracement.level10.coeff": number; /** Default value: `#9c27b0` */ "linetoolfibretracement.level10.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level10.text": string; /** Default value: `true` */ "linetoolfibretracement.level10.visible": boolean; /** Default value: `4.236` */ "linetoolfibretracement.level11.coeff": number; /** Default value: `#e91e63` */ "linetoolfibretracement.level11.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level11.text": string; /** Default value: `true` */ "linetoolfibretracement.level11.visible": boolean; /** Default value: `1.272` */ "linetoolfibretracement.level12.coeff": number; /** Default value: `#FF9800` */ "linetoolfibretracement.level12.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level12.text": string; /** Default value: `false` */ "linetoolfibretracement.level12.visible": boolean; /** Default value: `1.414` */ "linetoolfibretracement.level13.coeff": number; /** Default value: `#F23645` */ "linetoolfibretracement.level13.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level13.text": string; /** Default value: `false` */ "linetoolfibretracement.level13.visible": boolean; /** Default value: `2.272` */ "linetoolfibretracement.level14.coeff": number; /** Default value: `#FF9800` */ "linetoolfibretracement.level14.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level14.text": string; /** Default value: `false` */ "linetoolfibretracement.level14.visible": boolean; /** Default value: `2.414` */ "linetoolfibretracement.level15.coeff": number; /** Default value: `#4caf50` */ "linetoolfibretracement.level15.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level15.text": string; /** Default value: `false` */ "linetoolfibretracement.level15.visible": boolean; /** Default value: `2` */ "linetoolfibretracement.level16.coeff": number; /** Default value: `#089981` */ "linetoolfibretracement.level16.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level16.text": string; /** Default value: `false` */ "linetoolfibretracement.level16.visible": boolean; /** Default value: `3` */ "linetoolfibretracement.level17.coeff": number; /** Default value: `#00bcd4` */ "linetoolfibretracement.level17.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level17.text": string; /** Default value: `false` */ "linetoolfibretracement.level17.visible": boolean; /** Default value: `3.272` */ "linetoolfibretracement.level18.coeff": number; /** Default value: `#808080` */ "linetoolfibretracement.level18.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level18.text": string; /** Default value: `false` */ "linetoolfibretracement.level18.visible": boolean; /** Default value: `3.414` */ "linetoolfibretracement.level19.coeff": number; /** Default value: `#2962FF` */ "linetoolfibretracement.level19.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level19.text": string; /** Default value: `false` */ "linetoolfibretracement.level19.visible": boolean; /** Default value: `0.236` */ "linetoolfibretracement.level2.coeff": number; /** Default value: `#F23645` */ "linetoolfibretracement.level2.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level2.text": string; /** Default value: `true` */ "linetoolfibretracement.level2.visible": boolean; /** Default value: `4` */ "linetoolfibretracement.level20.coeff": number; /** Default value: `#F23645` */ "linetoolfibretracement.level20.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level20.text": string; /** Default value: `false` */ "linetoolfibretracement.level20.visible": boolean; /** Default value: `4.272` */ "linetoolfibretracement.level21.coeff": number; /** Default value: `#9c27b0` */ "linetoolfibretracement.level21.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level21.text": string; /** Default value: `false` */ "linetoolfibretracement.level21.visible": boolean; /** Default value: `4.414` */ "linetoolfibretracement.level22.coeff": number; /** Default value: `#e91e63` */ "linetoolfibretracement.level22.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level22.text": string; /** Default value: `false` */ "linetoolfibretracement.level22.visible": boolean; /** Default value: `4.618` */ "linetoolfibretracement.level23.coeff": number; /** Default value: `#FF9800` */ "linetoolfibretracement.level23.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level23.text": string; /** Default value: `false` */ "linetoolfibretracement.level23.visible": boolean; /** Default value: `4.764` */ "linetoolfibretracement.level24.coeff": number; /** Default value: `#089981` */ "linetoolfibretracement.level24.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level24.text": string; /** Default value: `false` */ "linetoolfibretracement.level24.visible": boolean; /** Default value: `0.382` */ "linetoolfibretracement.level3.coeff": number; /** Default value: `#FF9800` */ "linetoolfibretracement.level3.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level3.text": string; /** Default value: `true` */ "linetoolfibretracement.level3.visible": boolean; /** Default value: `0.5` */ "linetoolfibretracement.level4.coeff": number; /** Default value: `#4caf50` */ "linetoolfibretracement.level4.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level4.text": string; /** Default value: `true` */ "linetoolfibretracement.level4.visible": boolean; /** Default value: `0.618` */ "linetoolfibretracement.level5.coeff": number; /** Default value: `#089981` */ "linetoolfibretracement.level5.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level5.text": string; /** Default value: `true` */ "linetoolfibretracement.level5.visible": boolean; /** Default value: `0.786` */ "linetoolfibretracement.level6.coeff": number; /** Default value: `#00bcd4` */ "linetoolfibretracement.level6.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level6.text": string; /** Default value: `true` */ "linetoolfibretracement.level6.visible": boolean; /** Default value: `1` */ "linetoolfibretracement.level7.coeff": number; /** Default value: `#808080` */ "linetoolfibretracement.level7.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level7.text": string; /** Default value: `true` */ "linetoolfibretracement.level7.visible": boolean; /** Default value: `1.618` */ "linetoolfibretracement.level8.coeff": number; /** Default value: `#2962FF` */ "linetoolfibretracement.level8.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level8.text": string; /** Default value: `true` */ "linetoolfibretracement.level8.visible": boolean; /** Default value: `2.618` */ "linetoolfibretracement.level9.coeff": number; /** Default value: `#F23645` */ "linetoolfibretracement.level9.color": string; /** Default value: `undefined` */ "linetoolfibretracement.level9.text": string; /** Default value: `true` */ "linetoolfibretracement.level9.visible": boolean; /** Default value: `0` */ "linetoolfibretracement.levelsStyle.linestyle": number; /** Default value: `2` */ "linetoolfibretracement.levelsStyle.linewidth": number; /** Default value: `false` */ "linetoolfibretracement.reverse": boolean; /** Default value: `true` */ "linetoolfibretracement.showCoeffs": boolean; /** Default value: `true` */ "linetoolfibretracement.showPrices": boolean; /** Default value: `true` */ "linetoolfibretracement.showText": boolean; /** Default value: `80` */ "linetoolfibretracement.transparency": number; /** Default value: `#808080` */ "linetoolfibretracement.trendline.color": string; /** Default value: `2` */ "linetoolfibretracement.trendline.linestyle": number; /** Default value: `2` */ "linetoolfibretracement.trendline.linewidth": number; /** Default value: `true` */ "linetoolfibretracement.trendline.visible": boolean; /** Default value: `middle` */ "linetoolfibretracement.vertLabelsAlign": string; /** Default value: `middle` */ "linetoolfibretracement.vertTextAlign": string; } /** * Override properties for the Fibspeedresistancearcs drawing tool. */ export interface FibspeedresistancearcsLineToolOverrides { /** Default value: `true` */ "linetoolfibspeedresistancearcs.fillBackground": boolean; /** Default value: `false` */ "linetoolfibspeedresistancearcs.fullCircles": boolean; /** Default value: `0.236` */ "linetoolfibspeedresistancearcs.level1.coeff": number; /** Default value: `#F23645` */ "linetoolfibspeedresistancearcs.level1.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level1.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level1.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level1.visible": boolean; /** Default value: `4.236` */ "linetoolfibspeedresistancearcs.level10.coeff": number; /** Default value: `#e91e63` */ "linetoolfibspeedresistancearcs.level10.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level10.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level10.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level10.visible": boolean; /** Default value: `4.618` */ "linetoolfibspeedresistancearcs.level11.coeff": number; /** Default value: `#F23645` */ "linetoolfibspeedresistancearcs.level11.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level11.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level11.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level11.visible": boolean; /** Default value: `0.382` */ "linetoolfibspeedresistancearcs.level2.coeff": number; /** Default value: `#FF9800` */ "linetoolfibspeedresistancearcs.level2.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level2.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level2.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level2.visible": boolean; /** Default value: `0.5` */ "linetoolfibspeedresistancearcs.level3.coeff": number; /** Default value: `#089981` */ "linetoolfibspeedresistancearcs.level3.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level3.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level3.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level3.visible": boolean; /** Default value: `0.618` */ "linetoolfibspeedresistancearcs.level4.coeff": number; /** Default value: `#4caf50` */ "linetoolfibspeedresistancearcs.level4.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level4.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level4.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level4.visible": boolean; /** Default value: `0.786` */ "linetoolfibspeedresistancearcs.level5.coeff": number; /** Default value: `#00bcd4` */ "linetoolfibspeedresistancearcs.level5.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level5.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level5.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level5.visible": boolean; /** Default value: `1` */ "linetoolfibspeedresistancearcs.level6.coeff": number; /** Default value: `#808080` */ "linetoolfibspeedresistancearcs.level6.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level6.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level6.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level6.visible": boolean; /** Default value: `1.618` */ "linetoolfibspeedresistancearcs.level7.coeff": number; /** Default value: `#2962FF` */ "linetoolfibspeedresistancearcs.level7.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level7.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level7.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level7.visible": boolean; /** Default value: `2.618` */ "linetoolfibspeedresistancearcs.level8.coeff": number; /** Default value: `#e91e63` */ "linetoolfibspeedresistancearcs.level8.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level8.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level8.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level8.visible": boolean; /** Default value: `3.618` */ "linetoolfibspeedresistancearcs.level9.coeff": number; /** Default value: `#2962FF` */ "linetoolfibspeedresistancearcs.level9.color": string; /** Default value: `0` */ "linetoolfibspeedresistancearcs.level9.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.level9.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.level9.visible": boolean; /** Default value: `true` */ "linetoolfibspeedresistancearcs.showCoeffs": boolean; /** Default value: `80` */ "linetoolfibspeedresistancearcs.transparency": number; /** Default value: `#808080` */ "linetoolfibspeedresistancearcs.trendline.color": string; /** Default value: `2` */ "linetoolfibspeedresistancearcs.trendline.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancearcs.trendline.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancearcs.trendline.visible": boolean; } /** * Override properties for the Fibspeedresistancefan drawing tool. */ export interface FibspeedresistancefanLineToolOverrides { /** Default value: `true` */ "linetoolfibspeedresistancefan.fillBackground": boolean; /** Default value: `rgba(21, 56, 153, 0.8)` */ "linetoolfibspeedresistancefan.grid.color": string; /** Default value: `0` */ "linetoolfibspeedresistancefan.grid.linestyle": number; /** Default value: `1` */ "linetoolfibspeedresistancefan.grid.linewidth": number; /** Default value: `true` */ "linetoolfibspeedresistancefan.grid.visible": boolean; /** Default value: `0` */ "linetoolfibspeedresistancefan.hlevel1.coeff": number; /** Default value: `#808080` */ "linetoolfibspeedresistancefan.hlevel1.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.hlevel1.visible": boolean; /** Default value: `0.25` */ "linetoolfibspeedresistancefan.hlevel2.coeff": number; /** Default value: `#FF9800` */ "linetoolfibspeedresistancefan.hlevel2.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.hlevel2.visible": boolean; /** Default value: `0.382` */ "linetoolfibspeedresistancefan.hlevel3.coeff": number; /** Default value: `#00bcd4` */ "linetoolfibspeedresistancefan.hlevel3.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.hlevel3.visible": boolean; /** Default value: `0.5` */ "linetoolfibspeedresistancefan.hlevel4.coeff": number; /** Default value: `#4caf50` */ "linetoolfibspeedresistancefan.hlevel4.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.hlevel4.visible": boolean; /** Default value: `0.618` */ "linetoolfibspeedresistancefan.hlevel5.coeff": number; /** Default value: `#089981` */ "linetoolfibspeedresistancefan.hlevel5.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.hlevel5.visible": boolean; /** Default value: `0.75` */ "linetoolfibspeedresistancefan.hlevel6.coeff": number; /** Default value: `#2962FF` */ "linetoolfibspeedresistancefan.hlevel6.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.hlevel6.visible": boolean; /** Default value: `1` */ "linetoolfibspeedresistancefan.hlevel7.coeff": number; /** Default value: `#808080` */ "linetoolfibspeedresistancefan.hlevel7.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.hlevel7.visible": boolean; /** Default value: `0` */ "linetoolfibspeedresistancefan.linestyle": number; /** Default value: `2` */ "linetoolfibspeedresistancefan.linewidth": number; /** Default value: `false` */ "linetoolfibspeedresistancefan.reverse": boolean; /** Default value: `true` */ "linetoolfibspeedresistancefan.showBottomLabels": boolean; /** Default value: `true` */ "linetoolfibspeedresistancefan.showLeftLabels": boolean; /** Default value: `true` */ "linetoolfibspeedresistancefan.showRightLabels": boolean; /** Default value: `true` */ "linetoolfibspeedresistancefan.showTopLabels": boolean; /** Default value: `80` */ "linetoolfibspeedresistancefan.transparency": number; /** Default value: `0` */ "linetoolfibspeedresistancefan.vlevel1.coeff": number; /** Default value: `#808080` */ "linetoolfibspeedresistancefan.vlevel1.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.vlevel1.visible": boolean; /** Default value: `0.25` */ "linetoolfibspeedresistancefan.vlevel2.coeff": number; /** Default value: `#FF9800` */ "linetoolfibspeedresistancefan.vlevel2.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.vlevel2.visible": boolean; /** Default value: `0.382` */ "linetoolfibspeedresistancefan.vlevel3.coeff": number; /** Default value: `#00bcd4` */ "linetoolfibspeedresistancefan.vlevel3.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.vlevel3.visible": boolean; /** Default value: `0.5` */ "linetoolfibspeedresistancefan.vlevel4.coeff": number; /** Default value: `#4caf50` */ "linetoolfibspeedresistancefan.vlevel4.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.vlevel4.visible": boolean; /** Default value: `0.618` */ "linetoolfibspeedresistancefan.vlevel5.coeff": number; /** Default value: `#089981` */ "linetoolfibspeedresistancefan.vlevel5.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.vlevel5.visible": boolean; /** Default value: `0.75` */ "linetoolfibspeedresistancefan.vlevel6.coeff": number; /** Default value: `#2962FF` */ "linetoolfibspeedresistancefan.vlevel6.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.vlevel6.visible": boolean; /** Default value: `1` */ "linetoolfibspeedresistancefan.vlevel7.coeff": number; /** Default value: `#808080` */ "linetoolfibspeedresistancefan.vlevel7.color": string; /** Default value: `true` */ "linetoolfibspeedresistancefan.vlevel7.visible": boolean; } /** * Override properties for the Fibtimezone drawing tool. */ export interface FibtimezoneLineToolOverrides { /** Default value: `false` */ "linetoolfibtimezone.fillBackground": boolean; /** Default value: `right` */ "linetoolfibtimezone.horzLabelsAlign": string; /** Default value: `0` */ "linetoolfibtimezone.level1.coeff": number; /** Default value: `#808080` */ "linetoolfibtimezone.level1.color": string; /** Default value: `0` */ "linetoolfibtimezone.level1.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level1.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level1.visible": boolean; /** Default value: `55` */ "linetoolfibtimezone.level10.coeff": number; /** Default value: `#2962FF` */ "linetoolfibtimezone.level10.color": string; /** Default value: `0` */ "linetoolfibtimezone.level10.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level10.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level10.visible": boolean; /** Default value: `89` */ "linetoolfibtimezone.level11.coeff": number; /** Default value: `#2962FF` */ "linetoolfibtimezone.level11.color": string; /** Default value: `0` */ "linetoolfibtimezone.level11.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level11.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level11.visible": boolean; /** Default value: `1` */ "linetoolfibtimezone.level2.coeff": number; /** Default value: `#2962FF` */ "linetoolfibtimezone.level2.color": string; /** Default value: `0` */ "linetoolfibtimezone.level2.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level2.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level2.visible": boolean; /** Default value: `2` */ "linetoolfibtimezone.level3.coeff": number; /** Default value: `#2962FF` */ "linetoolfibtimezone.level3.color": string; /** Default value: `0` */ "linetoolfibtimezone.level3.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level3.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level3.visible": boolean; /** Default value: `3` */ "linetoolfibtimezone.level4.coeff": number; /** Default value: `#2962FF` */ "linetoolfibtimezone.level4.color": string; /** Default value: `0` */ "linetoolfibtimezone.level4.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level4.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level4.visible": boolean; /** Default value: `5` */ "linetoolfibtimezone.level5.coeff": number; /** Default value: `#2962FF` */ "linetoolfibtimezone.level5.color": string; /** Default value: `0` */ "linetoolfibtimezone.level5.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level5.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level5.visible": boolean; /** Default value: `8` */ "linetoolfibtimezone.level6.coeff": number; /** Default value: `#2962FF` */ "linetoolfibtimezone.level6.color": string; /** Default value: `0` */ "linetoolfibtimezone.level6.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level6.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level6.visible": boolean; /** Default value: `13` */ "linetoolfibtimezone.level7.coeff": number; /** Default value: `#2962FF` */ "linetoolfibtimezone.level7.color": string; /** Default value: `0` */ "linetoolfibtimezone.level7.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level7.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level7.visible": boolean; /** Default value: `21` */ "linetoolfibtimezone.level8.coeff": number; /** Default value: `#2962FF` */ "linetoolfibtimezone.level8.color": string; /** Default value: `0` */ "linetoolfibtimezone.level8.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level8.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level8.visible": boolean; /** Default value: `34` */ "linetoolfibtimezone.level9.coeff": number; /** Default value: `#2962FF` */ "linetoolfibtimezone.level9.color": string; /** Default value: `0` */ "linetoolfibtimezone.level9.linestyle": number; /** Default value: `2` */ "linetoolfibtimezone.level9.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.level9.visible": boolean; /** Default value: `true` */ "linetoolfibtimezone.showLabels": boolean; /** Default value: `80` */ "linetoolfibtimezone.transparency": number; /** Default value: `#808080` */ "linetoolfibtimezone.trendline.color": string; /** Default value: `2` */ "linetoolfibtimezone.trendline.linestyle": number; /** Default value: `1` */ "linetoolfibtimezone.trendline.linewidth": number; /** Default value: `true` */ "linetoolfibtimezone.trendline.visible": boolean; /** Default value: `bottom` */ "linetoolfibtimezone.vertLabelsAlign": string; } /** * Override properties for the Fibwedge drawing tool. */ export interface FibwedgeLineToolOverrides { /** Default value: `true` */ "linetoolfibwedge.fillBackground": boolean; /** Default value: `0.236` */ "linetoolfibwedge.level1.coeff": number; /** Default value: `#F23645` */ "linetoolfibwedge.level1.color": string; /** Default value: `0` */ "linetoolfibwedge.level1.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level1.linewidth": number; /** Default value: `true` */ "linetoolfibwedge.level1.visible": boolean; /** Default value: `4.236` */ "linetoolfibwedge.level10.coeff": number; /** Default value: `#e91e63` */ "linetoolfibwedge.level10.color": string; /** Default value: `0` */ "linetoolfibwedge.level10.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level10.linewidth": number; /** Default value: `false` */ "linetoolfibwedge.level10.visible": boolean; /** Default value: `4.618` */ "linetoolfibwedge.level11.coeff": number; /** Default value: `#e91e63` */ "linetoolfibwedge.level11.color": string; /** Default value: `0` */ "linetoolfibwedge.level11.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level11.linewidth": number; /** Default value: `false` */ "linetoolfibwedge.level11.visible": boolean; /** Default value: `0.382` */ "linetoolfibwedge.level2.coeff": number; /** Default value: `#FF9800` */ "linetoolfibwedge.level2.color": string; /** Default value: `0` */ "linetoolfibwedge.level2.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level2.linewidth": number; /** Default value: `true` */ "linetoolfibwedge.level2.visible": boolean; /** Default value: `0.5` */ "linetoolfibwedge.level3.coeff": number; /** Default value: `#4caf50` */ "linetoolfibwedge.level3.color": string; /** Default value: `0` */ "linetoolfibwedge.level3.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level3.linewidth": number; /** Default value: `true` */ "linetoolfibwedge.level3.visible": boolean; /** Default value: `0.618` */ "linetoolfibwedge.level4.coeff": number; /** Default value: `#089981` */ "linetoolfibwedge.level4.color": string; /** Default value: `0` */ "linetoolfibwedge.level4.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level4.linewidth": number; /** Default value: `true` */ "linetoolfibwedge.level4.visible": boolean; /** Default value: `0.786` */ "linetoolfibwedge.level5.coeff": number; /** Default value: `#00bcd4` */ "linetoolfibwedge.level5.color": string; /** Default value: `0` */ "linetoolfibwedge.level5.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level5.linewidth": number; /** Default value: `true` */ "linetoolfibwedge.level5.visible": boolean; /** Default value: `1` */ "linetoolfibwedge.level6.coeff": number; /** Default value: `#808080` */ "linetoolfibwedge.level6.color": string; /** Default value: `0` */ "linetoolfibwedge.level6.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level6.linewidth": number; /** Default value: `true` */ "linetoolfibwedge.level6.visible": boolean; /** Default value: `1.618` */ "linetoolfibwedge.level7.coeff": number; /** Default value: `#2962FF` */ "linetoolfibwedge.level7.color": string; /** Default value: `0` */ "linetoolfibwedge.level7.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level7.linewidth": number; /** Default value: `false` */ "linetoolfibwedge.level7.visible": boolean; /** Default value: `2.618` */ "linetoolfibwedge.level8.coeff": number; /** Default value: `#F23645` */ "linetoolfibwedge.level8.color": string; /** Default value: `0` */ "linetoolfibwedge.level8.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level8.linewidth": number; /** Default value: `false` */ "linetoolfibwedge.level8.visible": boolean; /** Default value: `3.618` */ "linetoolfibwedge.level9.coeff": number; /** Default value: `#673ab7` */ "linetoolfibwedge.level9.color": string; /** Default value: `0` */ "linetoolfibwedge.level9.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.level9.linewidth": number; /** Default value: `false` */ "linetoolfibwedge.level9.visible": boolean; /** Default value: `true` */ "linetoolfibwedge.showCoeffs": boolean; /** Default value: `80` */ "linetoolfibwedge.transparency": number; /** Default value: `#808080` */ "linetoolfibwedge.trendline.color": string; /** Default value: `0` */ "linetoolfibwedge.trendline.linestyle": number; /** Default value: `2` */ "linetoolfibwedge.trendline.linewidth": number; /** Default value: `true` */ "linetoolfibwedge.trendline.visible": boolean; } /** * Overrides for the '52 Week High/Low' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface FiftyTwoWeekHighLowIndicatorOverrides { [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Fisher Transform' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface FisherTransformIndicatorOverrides { /** Default value: `#E91E63` */ "level:band.color": string; /** Default value: `2` */ "level:band.linestyle": number; /** Default value: `1` */ "level:band.linewidth": number; /** Default value: `true` */ "level:band.visible": boolean; /** Default value: `-1.5` */ "level:band.value": number; /** Default value: `15` */ "fisher.display": number; /** Default value: `0` */ "fisher.linestyle": number; /** Default value: `1` */ "fisher.linewidth": number; /** Default value: `line` */ "fisher.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "fisher.trackprice": boolean; /** Default value: `0` */ "fisher.transparency": number; /** Default value: `#2196F3` */ "fisher.color": string; /** Default value: `15` */ "trigger.display": number; /** Default value: `0` */ "trigger.linestyle": number; /** Default value: `1` */ "trigger.linewidth": number; /** Default value: `line` */ "trigger.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "trigger.trackprice": boolean; /** Default value: `0` */ "trigger.transparency": number; /** Default value: `#FF6D00` */ "trigger.color": string; [key: string]: StudyOverrideValueType; } /** * Override properties for the Fivepointspattern drawing tool. */ export interface FivepointspatternLineToolOverrides { /** Default value: `#2962FF` */ "linetool5pointspattern.backgroundColor": string; /** Default value: `false` */ "linetool5pointspattern.bold": boolean; /** Default value: `#2962FF` */ "linetool5pointspattern.color": string; /** Default value: `true` */ "linetool5pointspattern.fillBackground": boolean; /** Default value: `12` */ "linetool5pointspattern.fontsize": number; /** Default value: `false` */ "linetool5pointspattern.italic": boolean; /** Default value: `2` */ "linetool5pointspattern.linewidth": number; /** Default value: `#ffffff` */ "linetool5pointspattern.textcolor": string; /** Default value: `85` */ "linetool5pointspattern.transparency": number; } /** * Overrides for the 'Fixed Range' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface FixedRangeIndicatorOverrides { /** Default value: `undefined` */ "developing poc.color": string; /** Default value: `0` */ "developing poc.linestyle": number; /** Default value: `1` */ "developing poc.linewidth": number; /** Default value: `step_line` */ "developing poc.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "developing poc.trackprice": boolean; /** Default value: `0` */ "developing poc.transparency": number; /** Default value: `0` */ "developing poc.display": number; /** Default value: `undefined` */ "developing va high.color": string; /** Default value: `0` */ "developing va high.linestyle": number; /** Default value: `1` */ "developing va high.linewidth": number; /** Default value: `step_line` */ "developing va high.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "developing va high.trackprice": boolean; /** Default value: `0` */ "developing va high.transparency": number; /** Default value: `0` */ "developing va high.display": number; /** Default value: `undefined` */ "developing va low.color": string; /** Default value: `0` */ "developing va low.linestyle": number; /** Default value: `1` */ "developing va low.linewidth": number; /** Default value: `step_line` */ "developing va low.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "developing va low.trackprice": boolean; /** Default value: `0` */ "developing va low.transparency": number; /** Default value: `0` */ "developing va low.display": number; [key: string]: StudyOverrideValueType; } /** * Override properties for the Flagmark drawing tool. */ export interface FlagmarkLineToolOverrides { /** Default value: `#2962FF` */ "linetoolflagmark.flagColor": string; } /** * Override properties for the Flatbottom drawing tool. */ export interface FlatbottomLineToolOverrides { /** Default value: `rgba(255, 152, 0, 0.2)` */ "linetoolflatbottom.backgroundColor": string; /** Default value: `false` */ "linetoolflatbottom.bold": boolean; /** Default value: `false` */ "linetoolflatbottom.extendLeft": boolean; /** Default value: `false` */ "linetoolflatbottom.extendRight": boolean; /** Default value: `true` */ "linetoolflatbottom.fillBackground": boolean; /** Default value: `12` */ "linetoolflatbottom.fontsize": number; /** Default value: `false` */ "linetoolflatbottom.italic": boolean; /** Default value: `false` */ "linetoolflatbottom.labelBold": boolean; /** Default value: `14` */ "linetoolflatbottom.labelFontSize": number; /** Default value: `left` */ "linetoolflatbottom.labelHorzAlign": string; /** Default value: `false` */ "linetoolflatbottom.labelItalic": boolean; /** Default value: `#FF9800` */ "linetoolflatbottom.labelTextColor": string; /** Default value: `bottom` */ "linetoolflatbottom.labelVertAlign": string; /** Default value: `false` */ "linetoolflatbottom.labelVisible": boolean; /** Default value: `0` */ "linetoolflatbottom.leftEnd": number; /** Default value: `#FF9800` */ "linetoolflatbottom.linecolor": string; /** Default value: `0` */ "linetoolflatbottom.linestyle": number; /** Default value: `2` */ "linetoolflatbottom.linewidth": number; /** Default value: `0` */ "linetoolflatbottom.rightEnd": number; /** Default value: `false` */ "linetoolflatbottom.showBarsRange": boolean; /** Default value: `false` */ "linetoolflatbottom.showDateTimeRange": boolean; /** Default value: `false` */ "linetoolflatbottom.showPriceRange": boolean; /** Default value: `false` */ "linetoolflatbottom.showPrices": boolean; /** Default value: `#FF9800` */ "linetoolflatbottom.textcolor": string; /** Default value: `20` */ "linetoolflatbottom.transparency": number; } /** * Format options */ export interface FormatterFormatOptions { /** * Ignore locale number format settings like decimal/thousands separators */ ignoreLocaleNumberFormat?: boolean; } /** * Format options */ export interface FormatterParseOptions { /** * Ignore locale number format settings like decimal/thousands separators */ ignoreLocaleNumberFormat?: boolean; } export interface FormatterParseResult { /** Returns if the formatter support parsing */ res: boolean; } /** * Override properties for the Ganncomplex drawing tool. */ export interface GanncomplexLineToolOverrides { /** Default value: `#FF9800` */ "linetoolganncomplex.arcs.0.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.0.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.0.width": number; /** Default value: `1` */ "linetoolganncomplex.arcs.0.x": number; /** Default value: `0` */ "linetoolganncomplex.arcs.0.y": number; /** Default value: `#FF9800` */ "linetoolganncomplex.arcs.1.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.1.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.1.width": number; /** Default value: `1` */ "linetoolganncomplex.arcs.1.x": number; /** Default value: `1` */ "linetoolganncomplex.arcs.1.y": number; /** Default value: `#2962FF` */ "linetoolganncomplex.arcs.10.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.10.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.10.width": number; /** Default value: `5` */ "linetoolganncomplex.arcs.10.x": number; /** Default value: `1` */ "linetoolganncomplex.arcs.10.y": number; /** Default value: `#FF9800` */ "linetoolganncomplex.arcs.2.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.2.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.2.width": number; /** Default value: `1.5` */ "linetoolganncomplex.arcs.2.x": number; /** Default value: `0` */ "linetoolganncomplex.arcs.2.y": number; /** Default value: `#00bcd4` */ "linetoolganncomplex.arcs.3.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.3.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.3.width": number; /** Default value: `2` */ "linetoolganncomplex.arcs.3.x": number; /** Default value: `0` */ "linetoolganncomplex.arcs.3.y": number; /** Default value: `#00bcd4` */ "linetoolganncomplex.arcs.4.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.4.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.4.width": number; /** Default value: `2` */ "linetoolganncomplex.arcs.4.x": number; /** Default value: `1` */ "linetoolganncomplex.arcs.4.y": number; /** Default value: `#4caf50` */ "linetoolganncomplex.arcs.5.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.5.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.5.width": number; /** Default value: `3` */ "linetoolganncomplex.arcs.5.x": number; /** Default value: `0` */ "linetoolganncomplex.arcs.5.y": number; /** Default value: `#4caf50` */ "linetoolganncomplex.arcs.6.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.6.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.6.width": number; /** Default value: `3` */ "linetoolganncomplex.arcs.6.x": number; /** Default value: `1` */ "linetoolganncomplex.arcs.6.y": number; /** Default value: `#089981` */ "linetoolganncomplex.arcs.7.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.7.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.7.width": number; /** Default value: `4` */ "linetoolganncomplex.arcs.7.x": number; /** Default value: `0` */ "linetoolganncomplex.arcs.7.y": number; /** Default value: `#089981` */ "linetoolganncomplex.arcs.8.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.8.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.8.width": number; /** Default value: `4` */ "linetoolganncomplex.arcs.8.x": number; /** Default value: `1` */ "linetoolganncomplex.arcs.8.y": number; /** Default value: `#2962FF` */ "linetoolganncomplex.arcs.9.color": string; /** Default value: `true` */ "linetoolganncomplex.arcs.9.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.arcs.9.width": number; /** Default value: `5` */ "linetoolganncomplex.arcs.9.x": number; /** Default value: `0` */ "linetoolganncomplex.arcs.9.y": number; /** Default value: `true` */ "linetoolganncomplex.arcsBackground.fillBackground": boolean; /** Default value: `80` */ "linetoolganncomplex.arcsBackground.transparency": number; /** Default value: `#B39DDB` */ "linetoolganncomplex.fanlines.0.color": string; /** Default value: `false` */ "linetoolganncomplex.fanlines.0.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.0.width": number; /** Default value: `8` */ "linetoolganncomplex.fanlines.0.x": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.0.y": number; /** Default value: `#F23645` */ "linetoolganncomplex.fanlines.1.color": string; /** Default value: `false` */ "linetoolganncomplex.fanlines.1.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.1.width": number; /** Default value: `5` */ "linetoolganncomplex.fanlines.1.x": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.1.y": number; /** Default value: `#B39DDB` */ "linetoolganncomplex.fanlines.10.color": string; /** Default value: `false` */ "linetoolganncomplex.fanlines.10.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.10.width": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.10.x": number; /** Default value: `8` */ "linetoolganncomplex.fanlines.10.y": number; /** Default value: `#808080` */ "linetoolganncomplex.fanlines.2.color": string; /** Default value: `false` */ "linetoolganncomplex.fanlines.2.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.2.width": number; /** Default value: `4` */ "linetoolganncomplex.fanlines.2.x": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.2.y": number; /** Default value: `#FF9800` */ "linetoolganncomplex.fanlines.3.color": string; /** Default value: `false` */ "linetoolganncomplex.fanlines.3.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.3.width": number; /** Default value: `3` */ "linetoolganncomplex.fanlines.3.x": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.3.y": number; /** Default value: `#00bcd4` */ "linetoolganncomplex.fanlines.4.color": string; /** Default value: `true` */ "linetoolganncomplex.fanlines.4.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.4.width": number; /** Default value: `2` */ "linetoolganncomplex.fanlines.4.x": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.4.y": number; /** Default value: `#4caf50` */ "linetoolganncomplex.fanlines.5.color": string; /** Default value: `true` */ "linetoolganncomplex.fanlines.5.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.5.width": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.5.x": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.5.y": number; /** Default value: `#089981` */ "linetoolganncomplex.fanlines.6.color": string; /** Default value: `true` */ "linetoolganncomplex.fanlines.6.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.6.width": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.6.x": number; /** Default value: `2` */ "linetoolganncomplex.fanlines.6.y": number; /** Default value: `#089981` */ "linetoolganncomplex.fanlines.7.color": string; /** Default value: `false` */ "linetoolganncomplex.fanlines.7.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.7.width": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.7.x": number; /** Default value: `3` */ "linetoolganncomplex.fanlines.7.y": number; /** Default value: `#2962FF` */ "linetoolganncomplex.fanlines.8.color": string; /** Default value: `false` */ "linetoolganncomplex.fanlines.8.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.8.width": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.8.x": number; /** Default value: `4` */ "linetoolganncomplex.fanlines.8.y": number; /** Default value: `#9575cd` */ "linetoolganncomplex.fanlines.9.color": string; /** Default value: `false` */ "linetoolganncomplex.fanlines.9.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.fanlines.9.width": number; /** Default value: `1` */ "linetoolganncomplex.fanlines.9.x": number; /** Default value: `5` */ "linetoolganncomplex.fanlines.9.y": number; /** Default value: `false` */ "linetoolganncomplex.fillBackground": boolean; /** Default value: `false` */ "linetoolganncomplex.labelsStyle.bold": boolean; /** Default value: `12` */ "linetoolganncomplex.labelsStyle.fontSize": number; /** Default value: `false` */ "linetoolganncomplex.labelsStyle.italic": boolean; /** Default value: `#808080` */ "linetoolganncomplex.levels.0.color": string; /** Default value: `true` */ "linetoolganncomplex.levels.0.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.levels.0.width": number; /** Default value: `#FF9800` */ "linetoolganncomplex.levels.1.color": string; /** Default value: `true` */ "linetoolganncomplex.levels.1.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.levels.1.width": number; /** Default value: `#00bcd4` */ "linetoolganncomplex.levels.2.color": string; /** Default value: `true` */ "linetoolganncomplex.levels.2.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.levels.2.width": number; /** Default value: `#4caf50` */ "linetoolganncomplex.levels.3.color": string; /** Default value: `true` */ "linetoolganncomplex.levels.3.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.levels.3.width": number; /** Default value: `#089981` */ "linetoolganncomplex.levels.4.color": string; /** Default value: `true` */ "linetoolganncomplex.levels.4.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.levels.4.width": number; /** Default value: `#808080` */ "linetoolganncomplex.levels.5.color": string; /** Default value: `true` */ "linetoolganncomplex.levels.5.visible": boolean; /** Default value: `2` */ "linetoolganncomplex.levels.5.width": number; /** Default value: `false` */ "linetoolganncomplex.reverse": boolean; /** Default value: `undefined` */ "linetoolganncomplex.scaleRatio": string; /** Default value: `true` */ "linetoolganncomplex.showLabels": boolean; } /** * Override properties for the Gannfan drawing tool. */ export interface GannfanLineToolOverrides { /** Default value: `true` */ "linetoolgannfan.fillBackground": boolean; /** Default value: `1` */ "linetoolgannfan.level1.coeff1": number; /** Default value: `8` */ "linetoolgannfan.level1.coeff2": number; /** Default value: `#FF9800` */ "linetoolgannfan.level1.color": string; /** Default value: `0` */ "linetoolgannfan.level1.linestyle": number; /** Default value: `2` */ "linetoolgannfan.level1.linewidth": number; /** Default value: `true` */ "linetoolgannfan.level1.visible": boolean; /** Default value: `1` */ "linetoolgannfan.level2.coeff1": number; /** Default value: `4` */ "linetoolgannfan.level2.coeff2": number; /** Default value: `#089981` */ "linetoolgannfan.level2.color": string; /** Default value: `0` */ "linetoolgannfan.level2.linestyle": number; /** Default value: `2` */ "linetoolgannfan.level2.linewidth": number; /** Default value: `true` */ "linetoolgannfan.level2.visible": boolean; /** Default value: `1` */ "linetoolgannfan.level3.coeff1": number; /** Default value: `3` */ "linetoolgannfan.level3.coeff2": number; /** Default value: `#4caf50` */ "linetoolgannfan.level3.color": string; /** Default value: `0` */ "linetoolgannfan.level3.linestyle": number; /** Default value: `2` */ "linetoolgannfan.level3.linewidth": number; /** Default value: `true` */ "linetoolgannfan.level3.visible": boolean; /** Default value: `1` */ "linetoolgannfan.level4.coeff1": number; /** Default value: `2` */ "linetoolgannfan.level4.coeff2": number; /** Default value: `#089981` */ "linetoolgannfan.level4.color": string; /** Default value: `0` */ "linetoolgannfan.level4.linestyle": number; /** Default value: `2` */ "linetoolgannfan.level4.linewidth": number; /** Default value: `true` */ "linetoolgannfan.level4.visible": boolean; /** Default value: `1` */ "linetoolgannfan.level5.coeff1": number; /** Default value: `1` */ "linetoolgannfan.level5.coeff2": number; /** Default value: `#00bcd4` */ "linetoolgannfan.level5.color": string; /** Default value: `0` */ "linetoolgannfan.level5.linestyle": number; /** Default value: `2` */ "linetoolgannfan.level5.linewidth": number; /** Default value: `true` */ "linetoolgannfan.level5.visible": boolean; /** Default value: `2` */ "linetoolgannfan.level6.coeff1": number; /** Default value: `1` */ "linetoolgannfan.level6.coeff2": number; /** Default value: `#2962FF` */ "linetoolgannfan.level6.color": string; /** Default value: `0` */ "linetoolgannfan.level6.linestyle": number; /** Default value: `2` */ "linetoolgannfan.level6.linewidth": number; /** Default value: `true` */ "linetoolgannfan.level6.visible": boolean; /** Default value: `3` */ "linetoolgannfan.level7.coeff1": number; /** Default value: `1` */ "linetoolgannfan.level7.coeff2": number; /** Default value: `#9c27b0` */ "linetoolgannfan.level7.color": string; /** Default value: `0` */ "linetoolgannfan.level7.linestyle": number; /** Default value: `2` */ "linetoolgannfan.level7.linewidth": number; /** Default value: `true` */ "linetoolgannfan.level7.visible": boolean; /** Default value: `4` */ "linetoolgannfan.level8.coeff1": number; /** Default value: `1` */ "linetoolgannfan.level8.coeff2": number; /** Default value: `#e91e63` */ "linetoolgannfan.level8.color": string; /** Default value: `0` */ "linetoolgannfan.level8.linestyle": number; /** Default value: `2` */ "linetoolgannfan.level8.linewidth": number; /** Default value: `true` */ "linetoolgannfan.level8.visible": boolean; /** Default value: `8` */ "linetoolgannfan.level9.coeff1": number; /** Default value: `1` */ "linetoolgannfan.level9.coeff2": number; /** Default value: `#F23645` */ "linetoolgannfan.level9.color": string; /** Default value: `0` */ "linetoolgannfan.level9.linestyle": number; /** Default value: `2` */ "linetoolgannfan.level9.linewidth": number; /** Default value: `true` */ "linetoolgannfan.level9.visible": boolean; /** Default value: `2` */ "linetoolgannfan.linewidth": number; /** Default value: `true` */ "linetoolgannfan.showLabels": boolean; /** Default value: `80` */ "linetoolgannfan.transparency": number; } /** * Override properties for the Gannfixed drawing tool. */ export interface GannfixedLineToolOverrides { /** Default value: `#FF9800` */ "linetoolgannfixed.arcs.0.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.0.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.0.width": number; /** Default value: `1` */ "linetoolgannfixed.arcs.0.x": number; /** Default value: `0` */ "linetoolgannfixed.arcs.0.y": number; /** Default value: `#FF9800` */ "linetoolgannfixed.arcs.1.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.1.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.1.width": number; /** Default value: `1` */ "linetoolgannfixed.arcs.1.x": number; /** Default value: `1` */ "linetoolgannfixed.arcs.1.y": number; /** Default value: `#2962FF` */ "linetoolgannfixed.arcs.10.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.10.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.10.width": number; /** Default value: `5` */ "linetoolgannfixed.arcs.10.x": number; /** Default value: `1` */ "linetoolgannfixed.arcs.10.y": number; /** Default value: `#FF9800` */ "linetoolgannfixed.arcs.2.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.2.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.2.width": number; /** Default value: `1.5` */ "linetoolgannfixed.arcs.2.x": number; /** Default value: `0` */ "linetoolgannfixed.arcs.2.y": number; /** Default value: `#00bcd4` */ "linetoolgannfixed.arcs.3.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.3.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.3.width": number; /** Default value: `2` */ "linetoolgannfixed.arcs.3.x": number; /** Default value: `0` */ "linetoolgannfixed.arcs.3.y": number; /** Default value: `#00bcd4` */ "linetoolgannfixed.arcs.4.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.4.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.4.width": number; /** Default value: `2` */ "linetoolgannfixed.arcs.4.x": number; /** Default value: `1` */ "linetoolgannfixed.arcs.4.y": number; /** Default value: `#4caf50` */ "linetoolgannfixed.arcs.5.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.5.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.5.width": number; /** Default value: `3` */ "linetoolgannfixed.arcs.5.x": number; /** Default value: `0` */ "linetoolgannfixed.arcs.5.y": number; /** Default value: `#4caf50` */ "linetoolgannfixed.arcs.6.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.6.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.6.width": number; /** Default value: `3` */ "linetoolgannfixed.arcs.6.x": number; /** Default value: `1` */ "linetoolgannfixed.arcs.6.y": number; /** Default value: `#089981` */ "linetoolgannfixed.arcs.7.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.7.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.7.width": number; /** Default value: `4` */ "linetoolgannfixed.arcs.7.x": number; /** Default value: `0` */ "linetoolgannfixed.arcs.7.y": number; /** Default value: `#089981` */ "linetoolgannfixed.arcs.8.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.8.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.8.width": number; /** Default value: `4` */ "linetoolgannfixed.arcs.8.x": number; /** Default value: `1` */ "linetoolgannfixed.arcs.8.y": number; /** Default value: `#2962FF` */ "linetoolgannfixed.arcs.9.color": string; /** Default value: `true` */ "linetoolgannfixed.arcs.9.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.arcs.9.width": number; /** Default value: `5` */ "linetoolgannfixed.arcs.9.x": number; /** Default value: `0` */ "linetoolgannfixed.arcs.9.y": number; /** Default value: `true` */ "linetoolgannfixed.arcsBackground.fillBackground": boolean; /** Default value: `80` */ "linetoolgannfixed.arcsBackground.transparency": number; /** Default value: `#B39DDB` */ "linetoolgannfixed.fanlines.0.color": string; /** Default value: `false` */ "linetoolgannfixed.fanlines.0.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.0.width": number; /** Default value: `8` */ "linetoolgannfixed.fanlines.0.x": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.0.y": number; /** Default value: `#F23645` */ "linetoolgannfixed.fanlines.1.color": string; /** Default value: `false` */ "linetoolgannfixed.fanlines.1.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.1.width": number; /** Default value: `5` */ "linetoolgannfixed.fanlines.1.x": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.1.y": number; /** Default value: `#B39DDB` */ "linetoolgannfixed.fanlines.10.color": string; /** Default value: `false` */ "linetoolgannfixed.fanlines.10.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.10.width": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.10.x": number; /** Default value: `8` */ "linetoolgannfixed.fanlines.10.y": number; /** Default value: `#808080` */ "linetoolgannfixed.fanlines.2.color": string; /** Default value: `false` */ "linetoolgannfixed.fanlines.2.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.2.width": number; /** Default value: `4` */ "linetoolgannfixed.fanlines.2.x": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.2.y": number; /** Default value: `#FF9800` */ "linetoolgannfixed.fanlines.3.color": string; /** Default value: `false` */ "linetoolgannfixed.fanlines.3.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.3.width": number; /** Default value: `3` */ "linetoolgannfixed.fanlines.3.x": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.3.y": number; /** Default value: `#00bcd4` */ "linetoolgannfixed.fanlines.4.color": string; /** Default value: `true` */ "linetoolgannfixed.fanlines.4.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.4.width": number; /** Default value: `2` */ "linetoolgannfixed.fanlines.4.x": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.4.y": number; /** Default value: `#4caf50` */ "linetoolgannfixed.fanlines.5.color": string; /** Default value: `true` */ "linetoolgannfixed.fanlines.5.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.5.width": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.5.x": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.5.y": number; /** Default value: `#089981` */ "linetoolgannfixed.fanlines.6.color": string; /** Default value: `true` */ "linetoolgannfixed.fanlines.6.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.6.width": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.6.x": number; /** Default value: `2` */ "linetoolgannfixed.fanlines.6.y": number; /** Default value: `#089981` */ "linetoolgannfixed.fanlines.7.color": string; /** Default value: `false` */ "linetoolgannfixed.fanlines.7.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.7.width": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.7.x": number; /** Default value: `3` */ "linetoolgannfixed.fanlines.7.y": number; /** Default value: `#2962FF` */ "linetoolgannfixed.fanlines.8.color": string; /** Default value: `false` */ "linetoolgannfixed.fanlines.8.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.8.width": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.8.x": number; /** Default value: `4` */ "linetoolgannfixed.fanlines.8.y": number; /** Default value: `#9575cd` */ "linetoolgannfixed.fanlines.9.color": string; /** Default value: `false` */ "linetoolgannfixed.fanlines.9.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.fanlines.9.width": number; /** Default value: `1` */ "linetoolgannfixed.fanlines.9.x": number; /** Default value: `5` */ "linetoolgannfixed.fanlines.9.y": number; /** Default value: `false` */ "linetoolgannfixed.fillBackground": boolean; /** Default value: `#808080` */ "linetoolgannfixed.levels.0.color": string; /** Default value: `true` */ "linetoolgannfixed.levels.0.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.levels.0.width": number; /** Default value: `#FF9800` */ "linetoolgannfixed.levels.1.color": string; /** Default value: `true` */ "linetoolgannfixed.levels.1.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.levels.1.width": number; /** Default value: `#00bcd4` */ "linetoolgannfixed.levels.2.color": string; /** Default value: `true` */ "linetoolgannfixed.levels.2.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.levels.2.width": number; /** Default value: `#4caf50` */ "linetoolgannfixed.levels.3.color": string; /** Default value: `true` */ "linetoolgannfixed.levels.3.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.levels.3.width": number; /** Default value: `#089981` */ "linetoolgannfixed.levels.4.color": string; /** Default value: `true` */ "linetoolgannfixed.levels.4.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.levels.4.width": number; /** Default value: `#808080` */ "linetoolgannfixed.levels.5.color": string; /** Default value: `true` */ "linetoolgannfixed.levels.5.visible": boolean; /** Default value: `2` */ "linetoolgannfixed.levels.5.width": number; /** Default value: `false` */ "linetoolgannfixed.reverse": boolean; } /** * Override properties for the Gannsquare drawing tool. */ export interface GannsquareLineToolOverrides { /** Default value: `rgba(21, 56, 153, 0.8)` */ "linetoolgannsquare.color": string; /** Default value: `#9C9C9C` */ "linetoolgannsquare.fans.color": string; /** Default value: `false` */ "linetoolgannsquare.fans.visible": boolean; /** Default value: `true` */ "linetoolgannsquare.fillHorzBackground": boolean; /** Default value: `true` */ "linetoolgannsquare.fillVertBackground": boolean; /** Default value: `0` */ "linetoolgannsquare.hlevel1.coeff": number; /** Default value: `#808080` */ "linetoolgannsquare.hlevel1.color": string; /** Default value: `true` */ "linetoolgannsquare.hlevel1.visible": boolean; /** Default value: `0.25` */ "linetoolgannsquare.hlevel2.coeff": number; /** Default value: `#FF9800` */ "linetoolgannsquare.hlevel2.color": string; /** Default value: `true` */ "linetoolgannsquare.hlevel2.visible": boolean; /** Default value: `0.382` */ "linetoolgannsquare.hlevel3.coeff": number; /** Default value: `#00bcd4` */ "linetoolgannsquare.hlevel3.color": string; /** Default value: `true` */ "linetoolgannsquare.hlevel3.visible": boolean; /** Default value: `0.5` */ "linetoolgannsquare.hlevel4.coeff": number; /** Default value: `#4caf50` */ "linetoolgannsquare.hlevel4.color": string; /** Default value: `true` */ "linetoolgannsquare.hlevel4.visible": boolean; /** Default value: `0.618` */ "linetoolgannsquare.hlevel5.coeff": number; /** Default value: `#089981` */ "linetoolgannsquare.hlevel5.color": string; /** Default value: `true` */ "linetoolgannsquare.hlevel5.visible": boolean; /** Default value: `0.75` */ "linetoolgannsquare.hlevel6.coeff": number; /** Default value: `#2962FF` */ "linetoolgannsquare.hlevel6.color": string; /** Default value: `true` */ "linetoolgannsquare.hlevel6.visible": boolean; /** Default value: `1` */ "linetoolgannsquare.hlevel7.coeff": number; /** Default value: `#808080` */ "linetoolgannsquare.hlevel7.color": string; /** Default value: `true` */ "linetoolgannsquare.hlevel7.visible": boolean; /** Default value: `80` */ "linetoolgannsquare.horzTransparency": number; /** Default value: `0` */ "linetoolgannsquare.linestyle": number; /** Default value: `2` */ "linetoolgannsquare.linewidth": number; /** Default value: `false` */ "linetoolgannsquare.reverse": boolean; /** Default value: `true` */ "linetoolgannsquare.showBottomLabels": boolean; /** Default value: `true` */ "linetoolgannsquare.showLeftLabels": boolean; /** Default value: `true` */ "linetoolgannsquare.showRightLabels": boolean; /** Default value: `true` */ "linetoolgannsquare.showTopLabels": boolean; /** Default value: `80` */ "linetoolgannsquare.vertTransparency": number; /** Default value: `0` */ "linetoolgannsquare.vlevel1.coeff": number; /** Default value: `#808080` */ "linetoolgannsquare.vlevel1.color": string; /** Default value: `true` */ "linetoolgannsquare.vlevel1.visible": boolean; /** Default value: `0.25` */ "linetoolgannsquare.vlevel2.coeff": number; /** Default value: `#FF9800` */ "linetoolgannsquare.vlevel2.color": string; /** Default value: `true` */ "linetoolgannsquare.vlevel2.visible": boolean; /** Default value: `0.382` */ "linetoolgannsquare.vlevel3.coeff": number; /** Default value: `#00bcd4` */ "linetoolgannsquare.vlevel3.color": string; /** Default value: `true` */ "linetoolgannsquare.vlevel3.visible": boolean; /** Default value: `0.5` */ "linetoolgannsquare.vlevel4.coeff": number; /** Default value: `#4caf50` */ "linetoolgannsquare.vlevel4.color": string; /** Default value: `true` */ "linetoolgannsquare.vlevel4.visible": boolean; /** Default value: `0.618` */ "linetoolgannsquare.vlevel5.coeff": number; /** Default value: `#089981` */ "linetoolgannsquare.vlevel5.color": string; /** Default value: `true` */ "linetoolgannsquare.vlevel5.visible": boolean; /** Default value: `0.75` */ "linetoolgannsquare.vlevel6.coeff": number; /** Default value: `#2962FF` */ "linetoolgannsquare.vlevel6.color": string; /** Default value: `true` */ "linetoolgannsquare.vlevel6.visible": boolean; /** Default value: `1` */ "linetoolgannsquare.vlevel7.coeff": number; /** Default value: `#808080` */ "linetoolgannsquare.vlevel7.color": string; /** Default value: `true` */ "linetoolgannsquare.vlevel7.visible": boolean; } export interface GetNewsResponse { /** Title */ title?: string; /** Retrieved news items */ newsItems: NewsItem[]; } /** * Override properties for the Ghostfeed drawing tool. */ export interface GhostfeedLineToolOverrides { /** Default value: `20` */ "linetoolghostfeed.averageHL": number; /** Default value: `#378658` */ "linetoolghostfeed.candleStyle.borderColor": string; /** Default value: `#F23645` */ "linetoolghostfeed.candleStyle.borderDownColor": string; /** Default value: `#089981` */ "linetoolghostfeed.candleStyle.borderUpColor": string; /** Default value: `#FAA1A4` */ "linetoolghostfeed.candleStyle.downColor": string; /** Default value: `true` */ "linetoolghostfeed.candleStyle.drawBorder": boolean; /** Default value: `true` */ "linetoolghostfeed.candleStyle.drawWick": boolean; /** Default value: `#ACE5DC` */ "linetoolghostfeed.candleStyle.upColor": string; /** Default value: `#808080` */ "linetoolghostfeed.candleStyle.wickColor": string; /** Default value: `50` */ "linetoolghostfeed.transparency": number; /** Default value: `50` */ "linetoolghostfeed.variance": number; } export interface GradientFillOptions extends CommonFillOptions { bottomColor: string; topColor: string; } export interface GrayedObject { /** Type for grayed object */ type: "drawing" | "study"; /** Name of grayed object */ name: string; } /** * Overrides for the 'Guppy Multiple Moving Average' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface GuppyMultipleMovingAverageIndicatorOverrides { /** Default value: `15` */ "trader ema 1.display": number; /** Default value: `#00FFFF` */ "trader ema 1.color": string; /** Default value: `0` */ "trader ema 1.linestyle": number; /** Default value: `1` */ "trader ema 1.linewidth": number; /** Default value: `line` */ "trader ema 1.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "trader ema 1.trackprice": boolean; /** Default value: `15` */ "trader ema 1.transparency": number; /** Default value: `15` */ "trader ema 2.display": number; /** Default value: `#00FFFF` */ "trader ema 2.color": string; /** Default value: `0` */ "trader ema 2.linestyle": number; /** Default value: `1` */ "trader ema 2.linewidth": number; /** Default value: `line` */ "trader ema 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "trader ema 2.trackprice": boolean; /** Default value: `12` */ "trader ema 2.transparency": number; /** Default value: `15` */ "trader ema 3.display": number; /** Default value: `#00FFFF` */ "trader ema 3.color": string; /** Default value: `0` */ "trader ema 3.linestyle": number; /** Default value: `1` */ "trader ema 3.linewidth": number; /** Default value: `line` */ "trader ema 3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "trader ema 3.trackprice": boolean; /** Default value: `9` */ "trader ema 3.transparency": number; /** Default value: `15` */ "trader ema 4.display": number; /** Default value: `#00FFFF` */ "trader ema 4.color": string; /** Default value: `0` */ "trader ema 4.linestyle": number; /** Default value: `1` */ "trader ema 4.linewidth": number; /** Default value: `line` */ "trader ema 4.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "trader ema 4.trackprice": boolean; /** Default value: `6` */ "trader ema 4.transparency": number; /** Default value: `15` */ "trader ema 5.display": number; /** Default value: `#00FFFF` */ "trader ema 5.color": string; /** Default value: `0` */ "trader ema 5.linestyle": number; /** Default value: `1` */ "trader ema 5.linewidth": number; /** Default value: `line` */ "trader ema 5.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "trader ema 5.trackprice": boolean; /** Default value: `3` */ "trader ema 5.transparency": number; /** Default value: `15` */ "trader ema 6.display": number; /** Default value: `#00FFFF` */ "trader ema 6.color": string; /** Default value: `0` */ "trader ema 6.linestyle": number; /** Default value: `1` */ "trader ema 6.linewidth": number; /** Default value: `line` */ "trader ema 6.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "trader ema 6.trackprice": boolean; /** Default value: `0` */ "trader ema 6.transparency": number; /** Default value: `15` */ "investor ema 1.display": number; /** Default value: `#FF0000` */ "investor ema 1.color": string; /** Default value: `0` */ "investor ema 1.linestyle": number; /** Default value: `1` */ "investor ema 1.linewidth": number; /** Default value: `line` */ "investor ema 1.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "investor ema 1.trackprice": boolean; /** Default value: `15` */ "investor ema 1.transparency": number; /** Default value: `15` */ "investor ema 2.display": number; /** Default value: `#FF0000` */ "investor ema 2.color": string; /** Default value: `0` */ "investor ema 2.linestyle": number; /** Default value: `1` */ "investor ema 2.linewidth": number; /** Default value: `line` */ "investor ema 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "investor ema 2.trackprice": boolean; /** Default value: `12` */ "investor ema 2.transparency": number; /** Default value: `15` */ "investor ema 3.display": number; /** Default value: `#FF0000` */ "investor ema 3.color": string; /** Default value: `0` */ "investor ema 3.linestyle": number; /** Default value: `1` */ "investor ema 3.linewidth": number; /** Default value: `line` */ "investor ema 3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "investor ema 3.trackprice": boolean; /** Default value: `9` */ "investor ema 3.transparency": number; /** Default value: `15` */ "investor ema 4.display": number; /** Default value: `#FF0000` */ "investor ema 4.color": string; /** Default value: `0` */ "investor ema 4.linestyle": number; /** Default value: `1` */ "investor ema 4.linewidth": number; /** Default value: `line` */ "investor ema 4.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "investor ema 4.trackprice": boolean; /** Default value: `6` */ "investor ema 4.transparency": number; /** Default value: `15` */ "investor ema 5.display": number; /** Default value: `#FF0000` */ "investor ema 5.color": string; /** Default value: `0` */ "investor ema 5.linestyle": number; /** Default value: `1` */ "investor ema 5.linewidth": number; /** Default value: `line` */ "investor ema 5.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "investor ema 5.trackprice": boolean; /** Default value: `3` */ "investor ema 5.transparency": number; /** Default value: `15` */ "investor ema 6.display": number; /** Default value: `#FF0000` */ "investor ema 6.color": string; /** Default value: `0` */ "investor ema 6.linestyle": number; /** Default value: `1` */ "investor ema 6.linewidth": number; /** Default value: `line` */ "investor ema 6.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "investor ema 6.trackprice": boolean; /** Default value: `0` */ "investor ema 6.transparency": number; [key: string]: StudyOverrideValueType; } /** 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 HLCAreaStylePreferences { highLineVisible: boolean; /** High line color */ highLineColor: string; /** High line style */ highLineStyle: number; /** High line width */ highLineWidth: number; lowLineVisible: boolean; /** Low line color */ lowLineColor: string; /** Low line style */ lowLineStyle: number; /** Low line width */ lowLineWidth: number; /** Close line color */ closeLineColor: string; /** Close line style */ closeLineStyle: number; /** Close line width */ closeLineWidth: number; /** Fill color of area between high and close lines */ highCloseFillColor: string; /** Fill color of area between close and low lines */ closeLowFillColor: string; } export interface HLCBarsStylePreferences { /** Bar color */ color: string; /** Draw thin bars. Default - `true` */ thinBars: boolean; } export interface HLine { id: string; } /** * Override properties for the Headandshoulders drawing tool. */ export interface HeadandshouldersLineToolOverrides { /** Default value: `#089981` */ "linetoolheadandshoulders.backgroundColor": string; /** Default value: `false` */ "linetoolheadandshoulders.bold": boolean; /** Default value: `#089981` */ "linetoolheadandshoulders.color": string; /** Default value: `true` */ "linetoolheadandshoulders.fillBackground": boolean; /** Default value: `12` */ "linetoolheadandshoulders.fontsize": number; /** Default value: `false` */ "linetoolheadandshoulders.italic": boolean; /** Default value: `2` */ "linetoolheadandshoulders.linewidth": number; /** Default value: `#ffffff` */ "linetoolheadandshoulders.textcolor": string; /** Default value: `85` */ "linetoolheadandshoulders.transparency": number; } 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; } /** * Override properties for the Highlighter drawing tool. */ export interface HighlighterLineToolOverrides { /** Default value: `rgba(242, 54, 69, 0.2)` */ "linetoolhighlighter.linecolor": string; /** Default value: `5` */ "linetoolhighlighter.smooth": number; /** Default value: `80` */ "linetoolhighlighter.transparency": number; /** Default value: `20` */ "linetoolhighlighter.width": number; } /** * Overrides for the 'Historical Volatility' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface HistoricalVolatilityIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * 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; /** * The time of the next available bar in history. The time value should be represented with a Unix timestamp in milliseconds. * * You can pass the `nextTime` value to the library if there is no data in the time range that the library requests. * Therefore, you notify the library about available data before the requested range and ensure that the next data request is for the right range. * For more information, refer to the [How nextTime works](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF#how-nexttime-works) section. */ nextTime?: number | null; } export interface HlineOptions { color: string; display: Extract; linestyle: LineStyles["hline"][keyof LineStyles["hline"]]; linewidth: number; title: string; } 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; } /** * Horizontal Line Preferences */ 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; } /** * Override properties for the Horzline drawing tool. */ export interface HorzlineLineToolOverrides { /** Default value: `false` */ "linetoolhorzline.bold": boolean; /** Default value: `12` */ "linetoolhorzline.fontsize": number; /** Default value: `center` */ "linetoolhorzline.horzLabelsAlign": string; /** Default value: `false` */ "linetoolhorzline.italic": boolean; /** Default value: `#2962FF` */ "linetoolhorzline.linecolor": string; /** Default value: `0` */ "linetoolhorzline.linestyle": number; /** Default value: `2` */ "linetoolhorzline.linewidth": number; /** Default value: `true` */ "linetoolhorzline.showPrice": boolean; /** Default value: `#2962FF` */ "linetoolhorzline.textcolor": string; /** Default value: `middle` */ "linetoolhorzline.vertLabelsAlign": string; } /** * Override properties for the Horzray drawing tool. */ export interface HorzrayLineToolOverrides { /** Default value: `false` */ "linetoolhorzray.bold": boolean; /** Default value: `12` */ "linetoolhorzray.fontsize": number; /** Default value: `center` */ "linetoolhorzray.horzLabelsAlign": string; /** Default value: `false` */ "linetoolhorzray.italic": boolean; /** Default value: `#2962FF` */ "linetoolhorzray.linecolor": string; /** Default value: `0` */ "linetoolhorzray.linestyle": number; /** Default value: `2` */ "linetoolhorzray.linewidth": number; /** Default value: `true` */ "linetoolhorzray.showPrice": boolean; /** Default value: `#2962FF` */ "linetoolhorzray.textcolor": string; /** Default value: `top` */ "linetoolhorzray.vertLabelsAlign": string; } /** * Overrides for the 'Hull Moving Average' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface HullMovingAverageIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } export interface HyperlinkInfo { text: string; url: string; } export interface IAction extends IMenuItem, IDestroyable { /** @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 IBrokerAccountInfo { /** * The library calls `accountsMetainfo` to get a list of accounts for a particular user. * The method should return an array that contains an ID and name for each account. * * Note that if `accountsMetainfo` returns an array containing more than one element, you should implement the {@link setCurrentAccount} method. * Refer to [Multiple accounts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/multiple-accounts) for more information. */ accountsMetainfo(): Promise; /** * The library calls `currentAccount` to get the current account's ID. */ currentAccount(): AccountId; /** * The library calls `setCurrentAccount` when users switch accounts using the drop-down menu in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager). * This method provides your backend server with the ID of the selected account. * * Note that `setCurrentAccount` is required if {@link accountsMetainfo} returns an array containing more than one element. * Refer to [Multiple accounts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/multiple-accounts) for more information. * @param {AccountId} id - The ID of the selected account. */ setCurrentAccount?(id: AccountId): void; } export interface IBrokerCommon { /** * The library calls `chartContextMenuActions` when users open the [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) on the chart. * This method also renders the *Trade* button 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 - A context object passed by the library. * @param {DefaultContextMenuActionsParams} [options] - Default options for the context menu action parameters. * @returns A promise that resolves to an array of {@link ActionMetaInfo}, which may be empty. In that case, the *Trade* button will * be removed from the context menu. */ chartContextMenuActions(context: TradeContext, options?: DefaultContextMenuActionsParams): Promise; /** * The library calls `isTradable` to check if a symbol can be traded. * If the method returns `false`, users will see the *Non-tradable symbol* message in the UI when creating orders. * You can also display a custom message with the reason why the symbol cannot be traded and the possible solution to resolve the issue. * To do this, return an `IsTradableResult` object. * @param {string} symbol - The symbol identifier. */ isTradable(symbol: string): Promise; /** * Defines a connection status for the Broker API. * If any other value than `1` ("Connected") is returned, the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager) will display an endless spinner instead of users' trading data. * If you want to handle other scenarios, for example when the status is disconnected, you need to manage this scenario within your implementation and use the {@link IBrokerConnectionAdapterHost.connectionStatusUpdate} method. * * If the method is not implemented or returns a value other than `1`, * the following error will appear in the console: *Method connectionStatus is not properly implemented*. */ connectionStatus(): ConnectionStatus; /** * The library calls `orders` to request data on the user's active orders. This data is displayed on the _Orders and Positions_ pages of the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#orders-and-positions). */ orders(): Promise; /** * The library calls `ordersHistory` to request orders history. * It is expected that returned orders will have a final status (`rejected`, `filled`, `cancelled`). * * This method is only required when you set the {@link BrokerConfigFlags.supportOrdersHistory} flag to `true`. * This flag adds the *History* page, where order history is displayed, to the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager). * Refer to the [History](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/account-manager#history) section for more information. */ ordersHistory?(): Promise; /** * Called by Trading Platform to request [positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions). * Required if the {@link BrokerConfigFlags.supportPositions} flag is set to `true`. */ positions?(): Promise; /** * Called by Trading Platform to request [individual positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions). * Required if the {@link BrokerConfigFlags.supportPositionNetting} flag is set to `true`. */ individualPositions?(): Promise; /** * The library calls `executions` to request executions for the specified symbol. * If you want executions to be displayed on the chart, set the {@link BrokerConfigFlags.supportExecutions} to `true`. * @param {string} symbol - The symbol identifier. */ executions(symbol: string): Promise; /** * The library calls `symbolInfo` to request symbol information for the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) and [Depth of Market widget](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market). * @param {string} symbol - The symbol identifier. */ symbolInfo(symbol: string): Promise; /** * The library calls `accountManagerInfo` to get information required for building the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/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 want to [add custom fields](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#add-custom-fields) to the standard Order Ticket. * * 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. * * Use the `symbol` parameter to return customization options for a particular symbol. * @param {string} symbol - symbol identifier */ getPositionDialogOptions?(symbol: string): Promise; /** * Implement this method if you want to have custom options available for different symbols. * @param {string} symbol - symbol identifier */ getSymbolSpecificTradingOptions?(symbol: string): Promise; } 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. For more information on fractional prices, refer to [Fractional format](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#fractional-format). * @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. For more information, refer to [Variable tick size](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#variable-tick-size). */ createPriceFormatter(priceScale?: number, minMove?: number, fractional?: boolean, minMove2?: number, variableMinTick?: string): IPriceFormatter; } /** * The Trading Host is an API for interaction between the Broker API and the library code related to trading. * Its main purpose is to receive information from your backend server where trading logic is implemented and provide updates to the library. * Refer to the [Core trading concepts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts) article for more information. */ export interface IBrokerConnectionAdapterHost { /** Broker Connection Adapter Factory object */ factory: IBrokerConnectionAdapterFactory; /** * Triggers a connection status update throughout the broker by reinvoking {@link IBrokerCommon.connectionStatus}. * @param {ConnectionStatus} status - new connection status to propagate internally to the host * @param {DisconnectionInfo} [info] - additional information to provide when entering a disconnected status */ connectionStatusUpdate(status: ConnectionStatus, info?: DisconnectionInfo): void; /** * 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 to clear the current cache for orders and notify the chart that it needs to request orders again. * Use this method only in cases such as ID mismatches. * For more details, see [Order and position IDs mismatch](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#order-and-position-ids-mismatch). */ ordersFullUpdate(): 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 to clear the current cache for positions and notify the chart that it needs to request positions again. * Use this method only in cases such as ID mismatches. * For more details, see [Order and position IDs mismatch](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#order-and-position-ids-mismatch). */ positionsFullUpdate(): 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 an individual position is added or changed. * @param {IndividualPosition} individualPosition - updated individual position * @param {boolean} [isHistoryUpdate] - whether the change is a history update */ individualPositionUpdate(individualPosition: IndividualPosition, isHistoryUpdate?: boolean): void; /** * Call this method to clear the current cache for individual positions and notify the chart that it needs to request individual positions again. * Use this method only in cases such as ID mismatches. * For more details, see [Order and position IDs mismatch](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#order-and-position-ids-mismatch). */ individualPositionsFullUpdate(): void; /** * Call this method when an individual position has not changed, but fields that you added to the individual position object to display in the Account Manager have changed. * @param {string} id - ID of the updated individual position * @param {Partial} changes - changes to the individual position object */ individualPositionPartialUpdate(id: string, changes: 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 [profit and loss](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss) update. * Use this method when the {@link BrokerConfigFlags.supportPLUpdate} flag is set to `true` in {@link SingleBrokerMetaInfo.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 IBrokerTerminal.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 an individual position [profit and loss](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss) update. * @param {string} individualPositionId - ID of the individual position * @param {number} pl - updated profit / loss for the individual position */ individualPositionPLUpdate(individualPositionId: string, pl: number): void; /** * Call this method when a broker connection has received an equity update. This method is required by the standard Order Ticket 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 Ticket to display the margin meter. * This method should be used when {@link BrokerConfigFlags.supportMargin} is set to `true` in {@link SingleBrokerMetaInfo.configFlags}. * The Trading Platform subscribes to margin available updates using {@link IBrokerTerminal.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 Ticket. * It should be implemented when the {@link BrokerConfigFlags.supportBalances} flag is set to `true` in {@link SingleBrokerMetaInfo.configFlags}. * @param {string} symbol - symbol ID * @param {CryptoBalance} balance - updated crypto balance */ cryptoBalanceUpdate(symbol: string, balance: CryptoBalance): void; /** * Update the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) data for a specified symbol. * @param {string} symbol - symbol identifier * @param {DOMData} equity - Depth of Market data */ domUpdate(symbol: string, equity: DOMData): void; /** * Sets the quantity for a given symbol. * Use this method only when you need to [override the user-specified quantity](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#symbol-quantity-is-overridden) with a new value. * * To specify the default quantity, use the {@link InstrumentInfo.qty} field instead. * @param {string} symbol - symbol * @param {number} quantity - quantity to update */ setQty(symbol: string, quantity: number): void; /** * Returns the quantity for a given symbol. * @param {string} symbol - symbol * @return {Promise} - quantity for the given symbol */ getQty(symbol: string): Promise; /** * Adds a callback to be executed whenever there's a change of quantity for a given symbol. * * Make sure to unsubscribe from these changes using the corresponding {@link unsubscribeSuggestedQtyChange} method. * * @param {string} symbol - symbol to which the callback will be linked to * @param {SuggestedQtyChangedListener} listener - callback */ subscribeSuggestedQtyChange(symbol: string, listener: SuggestedQtyChangedListener): void; /** * Remove a previously added callback from the list. * @param {string} symbol - symbol to remove the callback from * @param {SuggestedQtyChangedListener} listener - callback to be removed */ unsubscribeSuggestedQtyChange(symbol: string, listener: SuggestedQtyChangedListener): void; /** * Shows the Order Ticket * @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 Ticket 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 Ticket 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|IndividualPosition} position - position or individual position * @param {Brackets} brackets - brackets for the position or individual position * @param {OrderTicketFocusControl} focus - input control to focus on when dialog is opened */ showPositionBracketsDialog(position: Position | IndividualPosition, brackets: Brackets, focus: OrderTicketFocusControl): Promise; /** * @deprecated This method will be removed from the library in the next major version. Please use {@link setAccountManagerVisibilityMode} instead. * Activate bottom widget */ activateBottomWidget(): Promise; /** * Method to retrieve the current visibility mode of the Account Manager. */ getAccountManagerVisibilityMode(): IWatchedValueReadonly; /** * Method to set a new visibility mode for the Account Manager. */ setAccountManagerVisibilityMode(mode: BottomWidgetBarMode): void; /** * 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; /** * Retrieves the current value for a specified [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) setting in the ellipsis menu. * * @template K A key of the OrderTicketSettings type. * @param {K} settingName - The name of the Order Ticket setting. * @returns {Promise} A promise that resolves with the value of the specified setting. */ getOrderTicketSetting(settingName: K): Promise; /** * Updates the value of a specified [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) setting in the ellipsis menu. * * @template K A key of OrderTicketSettings type. * @param {K} settingName - The name of the Order Ticket setting to be updated. * @param {OrderTicketSettings[K]} value - The new value to be assigned to the setting. * @returns {Promise} A promise that resolves when the setting is successfully updated. */ setOrderTicketSetting(settingName: K, value: OrderTicketSettings[K]): Promise; } /** * The Broker API is a key component that enables trading. * Its main purpose is to connect TradingView charts with your trading logic. * Refer to the [Core trading concepts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts) article for more information. */ export interface IBrokerTerminal extends IBrokerCommon, IBrokerAccountInfo { /** * The library calls `placeOrder` to request placing an order pre-filled with partial or complete information. * You should handle this request on your backend side. For more information, refer to [Order creation](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts#1-order-creation). * * To display an order preview before placing it, set {@link BrokerConfigFlags.supportPlaceOrderPreview} to `true`. * Refer to [Enable order preview](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-order-preview) for more information. * @param {PreOrder} order - Order information. * @param {string} [confirmId] - The ID of the confirmed order. This parameter is passed if [`supportPlaceOrderPreview`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportplaceorderpreview) is `true`. * @returns {PlaceOrderResult} An object with the order ID. */ placeOrder(order: PreOrder, confirmId?: string): Promise; /** * The library calls `previewOrder` to show an order preview when a user clicks _Buy order_ or _Modify order_ in the Order Ticket. * To [enable order preview](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-order-preview), set the {@link BrokerConfigFlags.supportPlaceOrderPreview} or {@link BrokerConfigFlags.supportModifyOrderPreview} configuration flag to `true`. * * This method returns estimated commission, fees, margin, and other information for the order without it actually being placed. * @param {PreOrder} order - Order information. */ previewOrder?(order: PreOrder): Promise; /** * The library calls `modifyOrder` to request modifying an existing order. * You should handle this request on your backend side and provide the library with a new order state. To do this, call the {@link IBrokerConnectionAdapterHost.orderUpdate} method right afterwards. * Otherwise, the library will return a [timeout issue](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue). * * Note that [market orders](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders#order-types) cannot be modified. * * To enable an order preview before modification, set the {@link BrokerConfigFlags.supportModifyOrderPreview} configuration flag to `true`. * Refer to [Enable order preview](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-order-preview) for more information. * @param {Order} order - Order information. * @param {string} [confirmId] - The ID of the confirmed order. This parameter is passed if [`supportModifyOrderPreview`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportmodifyorderpreview) is `true`. */ modifyOrder(order: Order, confirmId?: string): Promise; /** * The library calls `cancelOrder` to request canceling an order. * You should handle this request on your backend side and provide the library with a new order state. To do this, call the {@link IBrokerConnectionAdapterHost.orderUpdate} method right afterwards. * @param {string} orderId - The ID of the order to cancel. */ cancelOrder(orderId: string): Promise; /** * The library calls `cancelOrders` to request canceling multiple orders for a symbol. * You should handle this request on your backend side and provide the library with a new order states. To do this, call the {@link IBrokerConnectionAdapterHost.orderUpdate} method right afterwards. * * `cancelOrders` is only called when users click the *CXL all* button in the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) widget. * @param {string} symbol - The symbol identifier. * @param {Side|undefined} side - An order side. * @param {string[]} ordersIds - IDs of the orders to cancel. The orders are selected based on the specified `symbol` and `side`. */ cancelOrders?(symbol: string, side: Side | undefined, ordersIds: string[]): Promise; /** * This method is called if the {@link BrokerConfigFlags.supportNativeReversePosition} configuration flag is on. * It allows reversing the position by ID. * * Note that the library expects you to call the {@link IBrokerConnectionAdapterHost.positionUpdate} method right afterwards. * Otherwise, the library will return a [timeout issue](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue). * @param {string} positionId - position */ reversePosition?(positionId: string): Promise; /** * The library calls `closePosition` to request [closing a position](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#close-positions) by ID. * You should handle this request on your backend side and provide the library with a new position state. To do this, call the {@link IBrokerConnectionAdapterHost.positionUpdate} method right afterwards. * Otherwise, the library will return a [timeout issue](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue). * * `closePosition` is only called if the {@link BrokerConfigFlags.supportClosePosition} or {@link BrokerConfigFlags.supportPartialClosePosition} configuration flag is `true`. * @param {string} positionId - The position ID. * @param {number} [amount] - The amount is specified if [`supportPartialClosePosition`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpartialcloseposition) is `true` and the user wants to close only [part of the position](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#partial-closing). * @param {string} [confirmId] - The ID of the confirmed close position preview. This parameter is passed if [`supportPreviewClosePosition`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpreviewcloseposition) is `true`. */ closePosition?(positionId: string, amount?: number, confirmId?: string): Promise; /** * The library calls `closeIndividualPosition` if the {@link BrokerConfigFlags.supportCloseIndividualPosition} or {@link BrokerConfigFlags.supportPartialCloseIndividualPosition} configuration flag is `true`. * `closeIndividualPosition` allows [closing an individual position](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#close-positions) by ID. * * Note that the library expects you to call the {@link IBrokerConnectionAdapterHost.positionUpdate} method right afterwards. * Otherwise, the library will return a [timeout issue](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue). * @param {string} individualPositionId - The individual position ID. * @param {number} [amount] - The amount is specified if `supportPartialCloseIndividualPosition` is `true` and the user wants to close only [part of the individual position](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#partial-closing). * @param {string} [confirmId] - The ID of the confirmed close position preview. This parameter is passed if [`supportPreviewClosePosition`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpreviewcloseposition) is `true`. */ closeIndividualPosition?(individualPositionId: string, amount?: number, confirmId?: string): Promise; /** * The library calls `editPositionBrackets` if the {@link BrokerConfigFlags.supportPositionBrackets} configuration flag is `true`. * It shows a dialog that enables take-profit and stop-loss editing. * * Note that the library expects you to call the {@link IBrokerConnectionAdapterHost.positionUpdate} method right afterwards. * @param {string} positionId - The ID of the 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 the {@link BrokerConfigFlags.supportIndividualPositionBrackets} configuration flag is on. * It displays a dialog that enables take-profit and stop-loss editing. * * Note that the library expects you to call the {@link IBrokerConnectionAdapterHost.positionUpdate} method right afterwards. * @param {string} individualPositionId - ID of existing individual position to be modified * @param {Brackets} brackets - new Brackets to be set for the individual position */ editIndividualPositionBrackets?(individualPositionId: 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 information 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; /** * The method should be implemented if you use the standard Order Ticket 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 Ticket 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; /** * Use this method to enable dynamic updates of the pip value defined in {@link InstrumentInfo.pipValue}. * The pip value is displayed in the *Order info* section of the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) and is used to calculate the trade value and risks. * Once `subscribePipValue` is called, your Broker API implementation should provide pip value updates through the {@link IBrokerConnectionAdapterHost.pipValueUpdate} method. * * If `subscribePipValue` is not implemented, the static value from {@link InstrumentInfo.pipValue} is displayed in the UI. * @param {string} symbol - symbol identifier */ subscribePipValue?(symbol: string): void; /** * The method should be implemented if you use a standard Order Ticket 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 Ticket 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; /** * The method should be implemented if you use the standard Order Ticket 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. * * **Example** * ```javascript * widget.activeChart().onDataLoaded().subscribe( * null, * () => console.log('New history bars are loaded'), * true * ); * ``` * @returns A subscription object for new data loaded for the chart. */ onDataLoaded(): ISubscription<() => void>; /** * Get a subscription object for the chart symbol changing. * * **Example** * ```javascript * widget.activeChart().onSymbolChanged().subscribe(null, () => console.log('The symbol is changed')); * ``` * @returns A subscription object for when a symbol is resolved (ie changing resolution, timeframe, currency, etc.) */ onSymbolChanged(): ISubscription<(symbol: LibrarySymbolInfo) => void>; /** * Get a subscription object for the chart resolution (interval) changing. This method also allows you to track whether the chart's [date range](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#date-range) is changed. * The `timeframe` argument represents if a user clicks on the [time frame toolbar](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale#time-frame-toolbar) or changes the date range manually. * If `timeframe` is `undefined`, you can change a date range before data loading starts. * To do this, you can specify a time frame value or a certain date range. * * **Examples** * * The following code sample specifies a time frame value: * * ```javascript * widget.activeChart().onIntervalChanged().subscribe(null, (interval, timeframeObj) => * timeframeObj.timeframe = { * value: "12M", * type: "period-back" * }); * ``` * * The following code sample specifies a certain date range: * * ```javascript * widget.activeChart().onIntervalChanged().subscribe(null, (interval, timeframeObj) => * timeframeObj.timeframe = { * from: new Date('2015-01-01').getTime() / 1000, * to: new Date('2017-01-01').getTime() / 1000, * type: "time-range" * }); * ``` * @returns A subscription object for the chart interval (resolution) changing. */ onIntervalChanged(): ISubscription<(interval: ResolutionString, timeFrameParameters: { timeframe?: TimeFrameValue; }) => void>; /** * Get a subscription object for the chart's visible range changing. * * **Example** * ```javascript * widget.activeChart().onVisibleRangeChanged().subscribe( * null, * ({ from, to }) => console.log(from, to) * ); * ``` * @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. * * **Example** * ```javascript * widget.activeChart().onChartTypeChanged().subscribe( * null, * (chartType) => console.log('The type of chart is changed') * ); * ``` * @returns A subscription object for the chart type changing. */ onChartTypeChanged(): ISubscription<(chartType: SeriesType) => 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, the callback is called immediately. * * **Example** * ```javascript * widget.activeChart().dataReady(() => { * // ... * } * ``` * * @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. * * **Example** * ```javascript * widget.activeChart().crossHairMoved().subscribe( * null, * ({ time, price }) => console.log(time, price) * ); * ``` * @returns A subscription object for the crosshair moving over the chart. */ crossHairMoved(): ISubscription<(params: CrossHairMovedEventParams) => void>; /** * Get a subscription object for the ID of the study or series hovered by the crosshair. * * @returns A subscription object for the ID of the study or series hovered by the crosshair. Subscribers will be called with `null` if there is no study or series hovered. */ onHoveredSourceChanged(): ISubscription<(sourceId: EntityId) => void>; /** * Allows you to display a certain time range on the chart. * * **Example** * ```javascript * widget.activeChart().setVisibleRange( * { from: 1420156800, to: 1451433600 }, * { percentRightMargin: 20 } * ) * ``` * If the library cannot fit the specified range within the canvas, which may happen on small screens, it will ignore the `from` parameter. For more information, refer to the [Time scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale#time-range) article. * * @param range A range that will be made visible. * @param options Options for the new visible range. * @returns A promise that resolves when the visible range is set. */ setVisibleRange(range: SetVisibleTimeRange, options?: SetVisibleRangeOptions): Promise; /** * Change the chart's symbol. * * **Example** * ```javascript * widget.activeChart().setSymbol('IBM'); * ``` * Note: if you are attempting to change multiple charts (multi-chart layouts) at the same time with * multiple `setSymbol` calls then you should set `doNotActivateChart` option to `true`. * * @param symbol A symbol. * @param options Optional object of options for the new symbol or optional callback that is called when the data for the new symbol has loaded. * @returns A promise that resolves with a boolean value. It's `true` when the symbol has been set and `false` when setting the symbol is not possible. */ setSymbol(symbol: string, options?: SetSymbolOptions | (() => void)): Promise; /** * Change the chart's interval (resolution). * * **Example** * ```javascript * widget.activeChart().setResolution('2M'); * ``` * Note: if you are attempting to change multiple charts (multi-chart layouts) at the same time with * multiple `setResolution` calls then you should set `doNotActivateChart` option to `true`. * * @param resolution A resolution. * @param options Optional object of options for the new resolution or optional callback that is called when the data for the new resolution has loaded. * @returns A promise that resolves with a boolean value. It's `true` when the resolution has been set and `false` when setting the resolution is not possible. */ setResolution(resolution: ResolutionString, options?: SetResolutionOptions | (() => void)): Promise; /** * Change the chart's type. * * **Example** * ```javascript * widget.activeChart().setChartType(12); // Specifies the High-low type * ``` * * @param type A chart type. * @param callback An optional callback function. Called when the chart type has changed and data has loaded. * @returns A promise that resolves with a boolean value. It's `true` when the chart type has been set and `false` when setting the chart type is not possible. */ setChartType(type: SeriesType, callback?: () => void): void; /** * Force the chart to re-request data, for example if there are [internet connection issues](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues#internet-connection-issues). * Before calling this function the {@link IChartWidgetApi.resetCache} method should be called. * * **Example** * ```javascript * widget.activeChart().resetData(); * ``` * */ resetData(): void; /** * Execute an action by ID. * See [Chart methods](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Chart#execute-action-by-id) for more information. * * **Example** * ```javascript * // Undoes the last applied action * widget.activeChart().executeActionById("undo"); * * // Opens or hides the drawing toolbar * widget.activeChart().executeActionById("drawingToolbarAction"); * ``` * * @param actionId An action ID. */ executeActionById(actionId: ChartActionId): void; /** * Get the state of a checkable action. * * **Example** * ```javascript * if (widget.activeChart().getCheckableActionState("drawingToolbarAction")) { * // ... * }; * ``` * * @param actionId An action ID. * @returns `null` if the action with specified id doesn't exist or is not checkable, `true` if the action is checked, `false` otherwise. */ getCheckableActionState(actionId: ChartActionId): boolean | null; /** * Force the chart to re-request all bar marks and timescale marks. * * **Example** * ```javascript * widget.activeChart().refreshMarks(); * ``` * */ refreshMarks(): void; /** * Remove marks from the chart. * * **Example** * ```javascript * widget.activeChart().clearMarks(); * ``` * * @param marksToClear type of marks to clear. If nothing is specified both bar & timescale marks will be removed. */ clearMarks(marksToClear?: ClearMarksMode): void; /** * Get an array of IDs and name for all drawings on the chart. * * **Example** * ```javascript * widget.activeChart().getAllShapes().forEach(({ name }) => console.log(name)); * ``` * * @returns An array of drawing information. */ getAllShapes(): EntityInfo[]; /** * Get an array of IDs and names for all studies on the chart. * * **Example** * ```javascript * widget.activeChart().getAllStudies().forEach(({ name }) => console.log(name)); * ``` * * @returns An array of study information. */ getAllStudies(): EntityInfo[]; /** * Get the chart's price to bar ratio. * * **Example** * ```javascript * console.log(widget.activeChart().getPriceToBarRatio()); * ``` * * @returns The ratio or `null` if no ratio is defined. */ getPriceToBarRatio(): number | null; /** * Set the chart's price to bar ratio. * * **Example** * ```javascript * widget.activeChart().setPriceToBarRatio(0.4567, { disableUndo: true }); * ``` * * @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. * * **Example** * ```javascript * console.log(widget.activeChart().isPriceToBarRatioLocked()); * ``` * */ isPriceToBarRatioLocked(): boolean; /** * Lock or unlock the chart's price to bar ratio. * * **Example** * ```javascript * widget.activeChart().setPriceToBarRatioLocked(true, { disableUndo: false }); * ``` * * @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. * * **Example** * ```javascript * console.log(widget.activeChart().getAllPanesHeight()); * ``` * * @returns An array of heights. */ getAllPanesHeight(): number[]; /** * Set the height for each pane in the order provided. * * **Example** * ```javascript * console.log(widget.activeChart().setAllPanesHeight([250, 400, 200])); * ``` * * @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; /** * Check if the chart is maximized or not. * * @returns `true` if maximized, `false` otherwise. */ isMaximized(): boolean; /** * 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. * * **Example** * ```javascript * widget.activeChart().availableZOrderOperations([id]); * ``` * * @param sources An array of entity IDs. */ availableZOrderOperations(sources: readonly EntityId[]): AvailableZOrderOperations; /** * Move the group to the bottom of the Z-order. * * **Example** * ```javascript * widget.activeChart().sendToBack([id]); * ``` * * @param entities An array of entity IDs. */ sendToBack(entities: readonly EntityId[]): void; /** * Move the sources to the top of the Z-order. * * **Example** * ```javascript * widget.activeChart().bringToFront([id]); * ``` * * @param sources An array of source IDs. */ bringToFront(sources: readonly EntityId[]): void; /** * Move the sources one level up in the Z-order. * * **Example** * ```javascript * widget.activeChart().bringForward([id]); * ``` * * @param sources An array of source IDs. */ bringForward(sources: readonly EntityId[]): void; /** * Move the sources one level down in the Z-order. * * **Example** * ```javascript * widget.activeChart().sendBackward([id]); * ``` * * @param sources An array of source IDs. */ sendBackward(sources: readonly EntityId[]): void; /** * Adds an indicator or a symbol for comparison to the chart. * For more information, refer to the [Indicators](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators/indicators) article. * * @param {string} name - name of an indicator as shown in the `Indicators` widget * @param {boolean} [forceOverlay] - forces the Charting Library to place the created indicator on the main pane * @param {boolean} [lock] - whether a user will be able to remove/change/hide the indicator or not * @param {Record>(name: string, forceOverlay?: boolean, lock?: boolean, inputs?: Record, overrides?: TOverrides, options?: CreateStudyOptions): Promise; /** * Get a study by ID. * * **Example** * ```javascript * widget.activeChart().getStudyById(id).setVisible(false); * ``` * * @param entityId The study ID. * @returns An API object for interacting with the study. */ getStudyById(entityId: EntityId): IStudyApi; /** * Get the main series. * * **Example** * ```javascript * widget.activeChart().getSeries().setVisible(false); * ``` * * @returns An API object for interacting with the main series. */ getSeries(): ISeriesApi; /** * Create a new single point drawing. * * **Example** * ```javascript * widget.activeChart().createShape({ time: 1514764800 }, { shape: 'vertical_line' }); * ``` * * For more information, refer to [Drawings API](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api#createshape). * * @param point A point. The location of the new drawing. * @param options An options object for the new drawing. * @returns Promise of the ID for the new drawing if it was created successfully. */ createShape(point: ShapePoint, options: CreateShapeOptions): Promise; /** * Create a new multi point drawing. * * **Example** * ```javascript * const from = Date.now() / 1000 - 500 * 24 * 3600; // 500 days ago * const to = Date.now() / 1000; * widget.activeChart().createMultipointShape( * [{ time: from, price: 150 }, { time: to, price: 150 }], * { * shape: "trend_line", * lock: true, * disableSelection: true, * disableSave: true, * disableUndo: true, * text: "text", * } * ); * ``` * * For more information, refer to [Drawings API](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api#createmultipointshape). * * @param points An array of points that define the drawing. * @param options An options object for the new drawing. * @returns Promise of the ID for the new drawing if it was created successfully. */ createMultipointShape(points: ShapePoint[], options: CreateMultipointShapeOptions): Promise; /** * Create a new anchored drawing. Anchored drawings maintain their position when the chart's visible range changes. * * **Example** * ```javascript * widget.createAnchoredShape({ x: 0.1, y: 0.9 }, { shape: 'anchored_text', text: 'Hello, charts!', overrides: { color: 'green' }}); * ``` * * For more information, refer to [Drawings API](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api#createanchoredshape). * * @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): Promise; /** * Get a drawing by ID. * * **Example** * ```javascript * widget.activeChart().getShapeById(id).bringToFront(); * ``` * * For more information, refer to [Drawings API](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api#manage-drawings). * * @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. * * **Example** * ```javascript * widget.activeChart().removeEntity(id); * ``` * * @param entityId The ID of the entity. * @param options Optional undo options. */ removeEntity(entityId: EntityId, options?: UndoOptions): void; /** * Remove all drawings from the chart. * * **Example** * ```javascript * widget.activeChart().removeAllShapes(); * ``` * */ removeAllShapes(): void; /** * Remove all studies from the chart. * * **Example** * ```javascript * widget.activeChart().removeAllStudies(); * ``` * */ removeAllStudies(): void; /** * Get an API object for interacting with the selection. * * **Example** * ```javascript * widget.activeChart().selection().clear(); * ``` * */ selection(): ISelectionApi; /** * Show the properties dialog for a study or drawing. * * **Example** * ```javascript * const chart = widget.activeChart(); * chart.showPropertiesDialog(chart.getAllShapes()[0].id);` * ``` * * @param studyId An ID of the study or drawing. */ showPropertiesDialog(studyId: EntityId): void; /** * Save the current study template to a object. * * **Example** * ```javascript * const options = { saveSymbol: true, saveInterval: true }; * const template = widget.activeChart().createStudyTemplate(options); * ``` * * @param options An object of study template options. * @returns A study template object. */ createStudyTemplate(options: CreateStudyTemplateOptions): object; /** * Apply a study template to the chart. * * **Example** * ```javascript * widget.activeChart().applyStudyTemplate(template); * ``` * * @param template A study template object. */ applyStudyTemplate(template: object): void; /** * Creates a new trading order on the chart. * For more information, refer to [Trading primitives](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Trading-Primitives). * * Starting from version 29, this method is only available in [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal). * * **Example** * ```javascript * const orderLine = await widget.activeChart().createOrderLine(); * orderLine * .setTooltip("Additional order information") * .setModifyTooltip("Modify order") * .setCancelTooltip("Cancel order") * .onMove(function() { * this.setText("onMove called"); * }) * .onModify("onModify called", function(text) { * this.setText(text); * }) * .onCancel("onCancel called", function(text) { * this.setText(text); * }) * .setText("STOP: 73.5 (5,64%)") * .setQuantity("2"); * ``` * * @returns An API object for interacting with the order. */ createOrderLine(): Promise; /** * Creates a new trading position on the chart. * For more information, refer to [Trading primitives](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Trading-Primitives). * * Starting from version 29, this method is only available in [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal). * * **Example** * ```javascript * const positionLine = await widget.chart().createPositionLine(); * positionLine * .onModify(function() { * this.setText("onModify called"); * }) * .onReverse("onReverse called", function(text) { * this.setText(text); * }) * .onClose("onClose called", function(text) { * this.setText(text); * }) * .setText("PROFIT: 71.1 (3.31%)") * .setTooltip("Additional position information") * .setProtectTooltip("Protect position") * .setCloseTooltip("Close position") * .setReverseTooltip("Reverse position") * .setQuantity("8.235") * .setPrice(160) * .setExtendLeft(false) * .setLineStyle(0) * .setLineLength(25); * ``` * * @returns An API object for interacting with the position. */ createPositionLine(): Promise; /** * Creates a new trade execution on the chart. * For more information, refer to [Trading primitives](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Trading-Primitives). * * Starting from version 29, this method is only available in [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal). * * **Example** * ```javascript * const executionLine = widget.activeChart().createExecutionShape(); * executionLine * .setText("@1,320.75 Limit Buy 1") * .setTooltip("@1,320.75 Limit Buy 1") * .setTextColor("rgba(0,255,0,0.5)") * .setArrowColor("#0F0") * .setDirection("buy") * .setTime(widget.activeChart().getVisibleRange().from) * .setPrice(160); * ``` * * @returns An API object for interacting with the execution. */ createExecutionShape(): Promise; /** * Get the name of the current symbol. * * **Example** * ```javascript * console.log(widget.activeChart().symbol()); * ``` * */ symbol(): string; /** * Get an extended information object for the current symbol. * * **Example** * ```javascript * console.log(widget.activeChart().symbolExt().name); * ``` * */ symbolExt(): SymbolExt | null; /** * Get the current resolution (interval). * * **Example** * ```javascript * console.log(widget.activeChart().resolution()); * ``` * */ resolution(): ResolutionString; /** * Get the current visible time range. * * **Example** * ```javascript * console.log(widget.activeChart().getVisibleRange()); * ``` * */ getVisibleRange(): VisibleTimeRange; /** * 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(): SeriesType; /** * Get an API object for interacting with the chart timezone. */ getTimezoneApi(): ITimezoneApi; /** * Get an array of API objects for interacting with the chart panes. * * **Example** * ```javascript * widget.activeChart().getPanes()[1].moveTo(0); * ``` * */ getPanes(): IPaneApi[]; /** * Export the current data from the chart. * * **Example** * ```javascript * // Exports series' data only * widget.activeChart().exportData({ includeTime: false, includedStudies: [] }); * // Exports series' data with times * widget.activeChart().exportData({ includedStudies: [] }); * // Exports series' data with with user time * widget.activeChart().exportData({ includeTime: false, includeUserTime: true, includedStudies: [] }); * // Exports data for the indicator which ID is STUDY_ID * widget.activeChart().exportData({ includeTime: false, includeSeries: false, includedStudies: ['STUDY_ID'] }); * // Exports all available data from the chart * widget.activeChart().exportData({ includeUserTime: true }); * // Exports series' data before 2018-01-01 * widget.activeChart().exportData({ includeTime: false, to: Date.UTC(2018, 0, 1) / 1000 }); * // Exports series' data after 2018-01-01 * widget.activeChart().exportData({ includeTime: false, from: Date.UTC(2018, 0, 1) / 1000 }); * // Exports series' data in the range between 2018-01-01 and 2018-02-01 * widget.activeChart().exportData({ includeTime: false, from: Date.UTC(2018, 0, 1) / 1000, to: Date.UTC(2018, 1, 1) / 1000 }); * // Exports all displayed data on the chart * widget.activeChart().exportData({ includeDisplayedValues: true }); * ``` * * @param options Optional object of options to control the exported data. * @returns A promise that resolves with the exported data. */ exportData(options?: Partial): Promise; /** * Enable or disable drag-to-export feature. * * **Example** * ```javascript * // Enable drag-to-export, disable default chart drag to scroll * widget.activeChart().setDragExportEnabled(true); * widget.subscribe('dragstart', (params) => { * // create a HTML element for drag image * const dragImage = createDragImage(); * // set drag image * params.setDragImage(dragImage, 0, 0); * const exportData = widget.activeChart().exportData(); * // transform export data to csv * const csvData = transformExportDataToCsv(exportData); * params.setData('text/plain', csvData); * }); * ``` * To implement drag-to-export, you need to handle the `dragstart` event in your application and set the data to the `dataTransfer` object. * @param enabled `true` to enable drag-to-export, `false` to disable. */ setDragExportEnabled(enabled: boolean): void; /** * Check if the chart can be zoomed out using the {@link zoomOut} method. * * **Example** * ```javascript * if(widget.activeChart().canZoomOut()) { * widget.activeChart().zoomOut(); * }; * ``` * * @returns `true` if the chart can be zoomed out. */ canZoomOut(): boolean; /** * Subscription if the chart can be zoomed out using the {@link zoomOut} method. */ canZoomOutWV(): IWatchedValueReadonly; /** * Zoom out. The method has the same effect as clicking on the "Zoom out" button. */ zoomOut(): void; /** * Enable or disable zooming of the chart. * * **Example** * ```javascript * widget.activeChart().setZoomEnabled(false); * ``` * * @param enabled `true` to enable zooming, `false` to disable. */ setZoomEnabled(enabled: boolean): void; /** * Enable or disable scrolling of the chart. * * **Example** * ```javascript * widget.activeChart().setScrollEnabled(false); * ``` * * @param enabled `true` to enable scrolling, `false` to disable. */ setScrollEnabled(enabled: boolean): void; /** * Get an API object for interacting with groups of drawings. * Refer to the [Drawings API](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api#drawing-groups-api) article for more information. * * **Example** * ```javascript * widget.activeChart().shapesGroupController().createGroupFromSelection(); * ``` * */ 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. * * **Example** * ```javascript * var time = widget.activeChart().getTimeScale().coordinateToTime(100); * ``` * */ getTimeScale(): ITimeScaleApi; /** * Check if bar selection mode is active or not. * * **Example** * ```javascript * var isRequested = widget.activeChart().isSelectBarRequested(); * ``` * * @returns `true` if active, `false` otherwise. */ isSelectBarRequested(): boolean; /** * Switch the chart to bar selection mode. * * **Example** * ```javascript * widget.activeChart().requestSelectBar() * .then(function(time) { * console.log('user selects bar with time', time); * }) * .catch(function() { * console.log('bar selection was rejected'); * }); * ``` * * @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. * * **Example** * ```javascript * widget.activeChart().cancelSelectBar(); * ``` * */ cancelSelectBar(): void; /** * Load and apply a chart template. * * @param templateName The name of the template to load. */ loadChartTemplate(templateName: string): Promise; /** * Get a readonly watched value that can be used to read/subscribe to the state of the chart's market status. */ marketStatus(): IWatchedValueReadonly; /** * Set the time frame for this chart. * * **Note:** This action will set this chart as active in a multi-chart layout. * * **Example** * To apply the '1Y' timeframe: * ```js * tvWidget.setTimeFrame({ * val: { type: 'period-back', value: '12M' }, * res: '1W', * }); * ``` * * @param timeFrame Object specifying the range and resolution to be applied */ setTimeFrame(timeFrame: RangeOptions): void; /** * Get the line tools state containing the drawings on the active chart. * * This method requires that the [`saveload_separate_drawings_storage`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#saveload_separate_drawings_storage) featureset is enabled. */ getLineToolsState(): LineToolsAndGroupsState; /** * Apply line tools state to the chart which will restore the drawings from the saved content. * * This method requires that the [`saveload_separate_drawings_storage`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#saveload_separate_drawings_storage) featureset is enabled. */ applyLineToolsState(state: LineToolsAndGroupsState): Promise; /** * Manually trigger the chart to request the linetools again from the {@link IExternalSaveLoadAdapter.loadLineToolsAndGroups} method * or the 'load_line_tools' endpoint of the [Save and load REST API](https://www.tradingview.com/charting-library-docs/latest/api/save-load-rest-api). * * This method requires that the [`saveload_separate_drawings_storage`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#saveload_separate_drawings_storage) featureset is enabled. */ reloadLineToolsFromServer(): void; /** * The visibility of inactivity gaps on intraday and DWM (daily, weekly, monthly) charts. * * The [`inactivity_gaps`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#inactivity_gaps) featureset should be enabled to use this option. * * When enabled (`true`), the chart displays gaps during trading sessions where there is missing data due to market inactivity. * Otherwise, these gaps are hidden and the chart appears continuous. */ inactivityGaps(): IWatchedValue; } /** * The main interface for interacting with the library, returned by {@link ChartingLibraryWidgetConstructor}. * For more information, refer to the [Widget methods](https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methods) article. */ 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; /** * This method specifies an action that happens when a user presses certain keys. * It allows you to override the built‑in shortcuts or specify custom ones. * * To do this, pass a keyboard shortcut and a callback function as parameters. * The library invokes the callback when the `shortCut` keys are pressed. * * Note that the `shortCut` argument depends on the key types. Refer to the [Manage shortcuts](https://www.tradingview.com/charting-library-docs/latest/getting_started/Shortcuts#manage-shortcuts) section for more information and examples. * * @param shortCut A number, a string, or an array of numbers and strings. * @param callback A function that is called when the `shortCut` keys are pressed. */ 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): Promise; /** * 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>): Promise; /** * Select the Icon line tool. It's the same as clicking on the corresponding button in the left toolbar. * * @param linetool Icon line tool. * @param options An optional object with options. Currently only used for the 'icon' drawing. */ selectLineTool(linetool: "icon", options?: IconOptions): Promise; /** * Select the Emoji line tool. It's the same as clicking on the corresponding button in the left toolbar. * * @param linetool Emoji line tool. * @param options Options for the Emoji line tool */ selectLineTool(linetool: "emoji", options?: EmojiOptions): Promise; /** * 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. */ selectLineTool(linetool: SupportedLineTools, options?: IconOptions | EmojiOptions): Promise; /** * 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. * @param options Options for customising the saved data. */ save(callback: (state: object) => void, options?: SaveChartOptions): 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): Promise; /** * 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): Promise; /** * 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?: (error: SaveChartErrorInfo) => void, 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 | number, 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}. * * **Example** * ```javascript * widget.onChartReady(function() { * widget.onContextMenu(function(unixtime, price) { * return [{ * position: "top", * text: "First top menu item, time: " + unixtime + ", price: " + price, * click: function() { alert("First clicked."); } * }, * { text: "-", position: "top" }, // Adds a separator between buttons * { text: "-Paste" }, // Removes the existing item from the menu * { * position: "top", * text: "Second top menu item 2", * click: function() { alert("Second clicked."); } * }, { * position: "bottom", * text: "Bottom menu item", * click: function() { alert("Third clicked."); } * }]; * }); * }); * ``` * * @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. * * **Example** * ```javascript * widget.headerReady().then(function() { * var button = widget.createButton(); * button.setAttribute('title', 'My custom button tooltip'); * button.addEventListener('click', function() { alert("My custom button pressed!"); }); * button.textContent = 'My custom button caption'; * }); * ``` * * @param options A optional object of options for the button. * @returns A `HTMLElement` you can customize. */ 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 object of options for the button. * @returns A `string` button id */ createButton(options: CreateTradingViewStyledButtonOptions): string; /** * 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 is `false` or undefined. `string`(button id) if `useTradingViewStyle` is `true`. */ createButton(options?: CreateButtonOptions): HTMLElement | string; /** * Remove a button from the top toolbar. This should be called after {@link headerReady} has resolved. * * **Example** * ```javascript * widget.headerReady().then(function() { * var button = widget.createButton(); * widget.removeButton(button) * }); * ``` * * @param buttonIdOrHtmlElement The button link or id that you receive from createButton method. */ removeButton(buttonIdOrHtmlElement: HTMLElement | string): void; /** * Add a custom dropdown menu to the top toolbar. * * **Example** * ```javascript * widget.createDropdown( * { * title: 'dropdown', * tooltip: 'tooltip for this dropdown', * items: [ * { * title: 'item#1', * onSelect: () => {console.log('1');}, * }, * { * title: 'item#2', * onSelect: () => {widget.setSymbol('IBM', '1D');}, * }, * { * title: 'item#3', * onSelect: () => { * widget.activeChart().createStudy( * 'MACD', * false, * false, * { * in_0: 14, * in_1: 30, * in_3: 'close', * in_2: 9 * } * ); * }, * } * ], * icon: ``, * } * ).then(myDropdownApi => { * // Use myDropdownApi if you need to update the dropdown: * // myDropdownApi.applyOptions({ * // title: 'a new title!' * // }); * * // Or remove the dropdown: * // myDropdownApi.remove(); * }); * ``` * @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 IChartWidgetApi.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 indicator inputs, including their names. * You need to know an input name to refer to this property in the code. * For example, when you change an input value using the [overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides). * Consider the [Input property](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides#input-property) section for more information. * * @param studyName The name of a study. */ getStudyInputs(studyName: string): StudyInputInformation[]; /** * Get information about indicator properties. * You can use this information to refer to the properties in the code. * For example, when you change property values using the [overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides). * * Note that `getStudyStyles` does not return actual property names but the indicator's [metadata](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/metainfo). * Consider the [Property path](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides#property-path) section for more information on how to refer to the properties. * * @param studyName The name of a indicator. */ 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 indicator styles and inputs without reloading. * Refer to [Indicator Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides#change-default-properties-on-the-fly) for more information. * Overrides for built-in indicators are listed in {@link StudyOverrides}. * * @param overrides An object of overrides to apply to the studies. */ applyStudiesOverrides(overrides: object): void; /** * Apply overrides to the order and position lines created either using the [Broker API](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts#broker-api) or [trading primitives](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Trading-Primitives) methods. */ applyTradingCustomization(tradingCustomization: TradingCustomization): Promise; /** * Trading Platform only. Get a promise that resolves with an API object for interacting with the widgetbar (right sidebar) watchlist. * * **Example** * ```javascript * const watchlistApi = await widget.watchList(); * const activeListId = watchlistApi.getActiveListId(); * const currentListItems = watchlistApi.getList(activeListId); * // append new section and item to the current watchlist * watchlistApi.updateList(activeListId, [...currentListItems, '###NEW SECTION', 'AMZN']); * ``` * * @returns An API object for interacting with the widgetbar (right sidebar) watchlist. */ watchList(): Promise; /** * Trading Platform 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 Platform 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. * For example, you can subscribe to events on the active chart, such as {@link IChartWidgetApi.onIntervalChanged}. * Note that the library does not manage the event subscriptions when users switch between the charts on the [multiple-chart layout](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#multiple-chart-layout). * If necessary, you should manually unsubscribe from the previous chart and subscribe to the newly selected one. * To track the currently active chart, use the {@link SubscribeEventsMap.activeChartChanged} event. * * @returns An API object for interacting with the chart. */ activeChart(): IChartWidgetApi; /** * Get the index of the active chart in the layout. * * @returns number. */ activeChartIndex(): number; /** * Set which chart is currently active. * It is recommended that this method is only used when linked to a user action * which should change the active chart. * * Use {@link chartsCount} to determine the number of charts currently available. * If an invalid index is supplied (less than zero, or greater than the number of charts minus 1) * then this method will not change the active chart. * @param index - index of chart to set as the active chart. Index is zero-based. */ setActiveChart(index: number): void; /** * Get the number of charts in the current layout. * * @returns A count of the charts in the current layout. */ chartsCount(): number; /** * This method deletes non-visible charts from a multiple-chart layout. * * When a user transitions from a layout with a larger number of charts * to one with fewer charts, the unused chart APIs still exist behind the scenes. * This inherent behavior allows the library to restore previously displayed charts. * * If you prefer that additional charts are displayed as new, with no record of previous * charts at the same position, you can use this method to delete all non-visible charts. * It is most effective to run this method right after a layout change (one can subscribe to * {@link SubscribeEventsMap.layout_changed} to know when this occurs). * * Please ensure that any subscriptions or event listeners associated with the * hidden charts are removed prior to invoking this method. * * @returns void */ unloadUnusedCharts(): void; /** * 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; /** * Resets the sizes of all charts within a multiple-chart layout back to their initial default values. * This action redistributes the space equally among all charts to ensure consistency in layout design. * * @param disableUndo When set to true, the reset action is not added to the undo stack. Hence, the user cannot undo the reset operation. */ resetLayoutSizes(disableUndo?: boolean): void; /** * Set the sizes of charts within a multiple-chart layout. * * @param sizes An object of sizes to set for the charts. * @param disableUndo When set to `true`, the set action is not added to the undo stack. Hence, a user cannot undo the size changes. */ setLayoutSizes(sizes: Partial, disableUndo?: boolean): void; /** * 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. * * **Example** * ```javascript * console.log(widget.getTheme()); * ``` * * @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 snapshot of the chart and return it as a canvas. * Use this method to [implement your logic](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Snapshots#implement-your-logic) for taking snapshots. * * @param options An optional object that customizes 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 Platform. Get a watched value that can be used to read/write/subscribe to the state of the symbol sync between charts. * * **Example** * ```javascript * if (widget.symbolSync().value()) { * // ... * } * ``` * * @returns A watched value of the state of the symbol sync. */ symbolSync(): IWatchedValue; /** * Only available in Trading Platform. Get a watched value that can be used to read/write/subscribe to the state of the interval sync between charts. * * **Example** * ```javascript * widget.intervalSync().setValue(true); * ``` * * @returns A watched value of the state of the interval sync. */ intervalSync(): IWatchedValue; /** * Only available in Trading Platform. Get a watched value that can be used to read/write/subscribe to the state of the crosshair sync between charts. * * **Example** * ```javascript * widget.crosshairSync().setValue(true); * ``` * * @returns A watched value of the state of the crosshair sync. */ crosshairSync(): IWatchedValue; /** * Only available in Trading Platform. Get a watched value that can be used to read/write/subscribe to the state of the time sync between charts. * * **Example** * ```javascript * widget.timeSync().setValue(true); * ``` * * @returns A watched value of the state of the time sync. */ timeSync(): IWatchedValue; /** * Only available in Trading Platform. Get a watched value that can be used to read/write/subscribe to the state of the date range sync between charts. * * **Example** * ```javascript * widget.dateRangeSync().setValue(true); * ``` * * @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 writing detailed [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api) logs into the browser console. * * @param enabled A boolean flag. `true` to enable debug mode, `false` to disable. */ setDebugMode(enabled: boolean): void; /** * Get a watched value that read/write/subscribe to the state of the 'draw on all charts' mode. * * When enabled new drawings will be replicated to all charts in the layout * and shown when the same ticker is selected. */ drawOnAllChartsEnabled(): IWatchedValue; /** * 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 SeriesType}) 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/Overrides) * documentation for `mainSeriesProperties.style`. */ supportedChartTypes(): IWatchedValueReadonly; /** * Get an API object for adjusting the watermarks present on the charts. * This can only be accessed when the chart is ready to be used. ({@link onChartReady}) * * @returns An API object for adjusting the watermark settings. */ watermark(): IWatermarkApi; /** * Get an API object for creating, and adjusting, custom status items to * be displayed within the legend for the main series of each chart. * * This can only be accessed when the chart has been created. ({@link headerReady}) * * @returns An API object for controlling additional custom status items within the legend area. */ customSymbolStatus(): ICustomSymbolStatusApi; /** * Sets the value for a CSS custom property. * * **Example:** * ```js * widget.setCSSCustomProperty('--my-theme-color', '#123AAA'); * ``` * * @param customPropertyName A string representing the CSS custom property name. It is expected that the name should start with a double hyphen ('--'). * @param value A string containing the new property value. */ setCSSCustomProperty(customPropertyName: string, value: string): void; /** * Returns the current value for a CSS custom property. * * **Example:** * ```js * const currentValue = widget.getCSSCustomPropertyValue('--my-theme-color'); * ``` * * @param customPropertyName A string representing the CSS custom property name to be checked. It is expected that the name should start with a double hyphen ('--'). * @returns A string containing the value of the property. If not set, returns the empty string. */ getCSSCustomPropertyValue(customPropertyName: string): string; /** * Get a promise that resolves with an API object for interacting with the custom themes. For more information on custom themes, refer to the [Custom themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes) article. * * @returns An API object for interacting with the custom themes. */ customThemes(): Promise; /** * Reset cached bar data from the datafeed, for all symbols. * * This has the same effect as calling [`onResetCacheNeededCallback`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#subscribebars) for all symbol and resolution combinations at once. */ resetCache(): void; } /** * PineJS execution context. */ 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 * @param {string} [subsessionId] - Subsession ID */ new_sym(tickerid: string, period: string, currencyCode?: string, unitId?: string, subsessionId?: 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; /** * Allows you to specify how many data points beyond the [visible range](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale#time-range) the library should request. * You should use this method only in **exceptional** cases. * * By default, the library request data for the visible range and some additional data points required for calculations. * For example, if you calculate 10-period Moving Average with the {@link PineJSStd.sma} function, the library will request at least 10 extra bars of historical data. * * However, the library cannot determine the number of extra bars when your indicator depends on another indicator (chained calculations). * In this exceptional case, you can specify this number using the `setMinimumAdditionalDepth` method. * Consider the [Custom Moving Average](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator/constructor-implementation#2-call-setminimumadditionaldepth) example, where a series is calculated and then used as an input for the second calculation. * @param {number} value - minimum number of bars to request */ setMinimumAdditionalDepth(value: number): void; } 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; } /** * Adapter API for reading and setting the state of a * custom symbol status item. * * The 'set' methods return the same adapter so that you can * chain multiple set functions together. * * **Example** * ```js * const adapter = widget.customSymbolStatus().symbol('ABC'); * adapter.setVisible(true).setColor('#336699').setTooltip('Custom Status') * ``` */ export interface ICustomSymbolStatusAdapter { /** * Get the current visibility of the status item. * @returns the current visibility */ getVisible(): boolean; /** * Set the visibility for the status item. @default false * * @param visible - visibility for the status item, where * `true` makes the item visible. * @returns the current symbol status adapter so you can * chain 'set' functions together. */ setVisible(visible: boolean): ICustomSymbolStatusAdapter; /** * Get the current icon for the status item. * @returns the current icon SVG string */ getIcon(): string | null; /** * Set the icon for the status item. @default blank * The icon should be provided as an svg markup. It is * recommended that the icon works well at small sizes. * * **Example** * ```svg * * * * * ``` * * @param icon - svg markup string to be used as the icon, or `null` to display no icon * @returns the current symbol status adapter so you can * chain 'set' functions together. */ setIcon(icon: string | null): ICustomSymbolStatusAdapter; /** * Get the current color of the status item. * @returns the current color */ getColor(): string; /** * Set the color for the status item. @default '#9598a1' * * @param color - color to be used for the status item. * It is recommended that you test that the color works well * for both light and dark themes. * @returns the current symbol status adapter so you can * chain 'set' functions together. */ setColor(color: string): ICustomSymbolStatusAdapter; /** * Get the current tooltip text for the status item. * @returns the current tooltip text */ getTooltip(): string | null; /** * Set the text to be displayed within the tooltip displayed * when hovering over the statuses for the symbol. * @default '' * * @param tooltip - text to be displayed within the tooltip. * @returns the current symbol status adapter so you can * chain 'set' functions together. */ setTooltip(tooltip: string | null): ICustomSymbolStatusAdapter; /** * Get the current content of the status item displayed within * the pop-up tooltip. * @returns the current pop-up content */ getDropDownContent(): CustomStatusDropDownContent[] | null; /** * Set the content to be displayed within the pop-up which appears * when the user clicks on the symbol statuses. * @default null * * @param content - content to be displayed, set to `null` to display * nothing. More than one section can be specified. * @returns the current symbol status adapter so you can * chain 'set' functions together. */ setDropDownContent(content: CustomStatusDropDownContent[] | null): ICustomSymbolStatusAdapter; } /** * This API allows you to create custom sections in the [Market Status](https://www.tradingview.com/charting-library-docs/latest/ui_elements/market-status) popup to display additional information on a symbol, such as warnings. * You can also customize the icon, color, tooltip, and content. * * The API is designed to specify sections for a certain symbol. To do this, you should pass `symbolId` to the `symbol` method. * Note that `symbolId` should match the ID of the resolved symbol that you can retrieve using the {@link IChartWidgetApi.symbol} method. * * **Example** * ```js * widget * .customSymbolStatus() * .symbol('NASDAQNM:AAPL') // select the symbol * .setVisible(true) // make the status visible * .setColor('rgb(255, 40, 60)') // set the color * .setIcon(myCustomIconSvgString) // string for an svg icon, i.e. ' ... ' * .setTooltip('Tooltip') // text to be displayed within the hover tooltip * .setDropDownContent([ // content to be displayed within the large pop-up tooltip * { * title: 'Title', // title to be displayed within the pop-up * color: 'rgb(255, 60, 70)', // optional, if you want it to be different to above * content: [ * 'Explanation of status', * '

', * 'More details...', * ], * action: { // Optional action to be displayed * text: 'Read more here', * tooltip: 'opens in a new window', * onClick: () => { * window.open('https://www.tradingview.com/', '_blank'); * }, * }, * }, * ]); * ``` */ export interface ICustomSymbolStatusApi { /** * Get the custom symbol status adapter for a specific symbolId. The * symbolId should exactly match the resolved symbolId. This id can * be retrieved for a chart via the {@link IChartWidgetApi.symbol} method. * * @param symbolId - symbol id for which you would like to create / adjust * the custom status */ symbol(symbolId: string): ICustomSymbolStatusAdapter; /** * Hide all the custom status items. This is equivalent to using * `setVisible(false)` on all of the current custom symbol status items. */ hideAll(): void; } /** * An API for controlling custom themes. To retrieve this interface, call the {@link IChartingLibraryWidget.customThemes} method. * For more information on custom themes, refer to the [Custom Themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes) article. */ export interface ICustomThemesApi { /** * Apply custom theme color definitions to the library widget after the widget is created. * * You can also specify a custom theme using the {@link ChartingLibraryWidgetOptions.custom_themes} property in the Widget Constructor. * * @param customThemes Custom theme color definitions */ applyCustomThemes(customThemes: CustomThemes): Promise; /** * Reset the widget's color theme colors back to the default values. */ resetCustomThemes(): Promise; } 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 the `supports_time` configuration flag is `true` when the chart needs to know the server time. * The library expects a callback to be called once. * The time is provided without milliseconds. Example: `1445324591`. * * `getServerTime` is used to display countdown on the price scale. * Note that the countdown can be displayed only for [intraday](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-minutes-intraday) resolutions. */ 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 * @param searchSource The source of the search ({@link SearchInitiationPoint}). */ searchSymbols(userInput: string, exchange: string, symbolType: string, onResult: SearchSymbolsCallback, searchSource?: SearchInitiationPoint): 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: DatafeedErrorCallback, 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. If using special characters, please consider `encodeURIComponent`. */ getBars(symbolInfo: LibrarySymbolInfo, resolution: ResolutionString, periodParams: PeriodParams, onResult: HistoryCallback, onError: DatafeedErrorCallback): void; /** * The 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; /** * The library calls this function when it wants to receive real-time symbol data in the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) (DOM) widget. * Note that you should set the {@link BrokerConfigFlags.supportLevel2Data} configuration flag to `true`. * * @param symbol A SymbolInfo object * @param callback A function returning an object to update DOM data * @returns A unique identifier that will be used to unsubscribe from the data */ subscribeDepth?(symbol: string, callback: DOMCallback): string; /** * The library calls this function to stop receiving real-time updates for the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) listener. * Note that you should set the {@link BrokerConfigFlags.supportLevel2Data} configuration flag to `true`. * * @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 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 Platform 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 Platform 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; } 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. * Note that this method does not affect the menu's alignment. To change the alignment, you should remove and recreate the menu as follows: * * ```javascript * myCustomDropdownApi.remove(); * widget.createDropdown(optionsWithDifferentAlignment); * ``` * * @param {DropdownUpdateParams} options - Partial options for the dropdown menu */ applyOptions(options: DropdownUpdateParams): void; /** * Remove the dropdown menu. */ remove(): void; } /** * An API object that controls execution lines created with {@link IChartWidgetApi.createExecutionShape}. * For more information, refer to [Trading primitives](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Trading-Primitives). */ 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. * The lib 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: string | number): 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 | string} 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 | string): 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; /** * Load a chart template from the server * * @param templateName The name of the template. * * @returns The chart template content. */ getChartTemplateContent(templateName: string): Promise; /** * Get names of all saved chart templates. * * @returns An array of names. */ getAllChartTemplates(): Promise; /** * Save a chart template. * * @param newName The name of the template. * @param theme The template content. */ saveChartTemplate(newName: string, theme: ChartTemplateContent): Promise; /** * Remove a chart template. * * @param templateName The name of the template. */ removeChartTemplate(templateName: string): Promise; /** * Save drawings and drawing groups associated with a chart layout. * * @param layoutId The chart layout ID * @param chartId The chart ID * @param state The drawings and drawing groups state */ saveLineToolsAndGroups(layoutId: string | undefined, chartId: string | number, state: LineToolsAndGroupsState): Promise; /** * Load drawings and drawing groups associated with a chart layout. * * @param layoutId The chart layout ID * @param chartId The chart ID * @param requestType Type of load request * @param requestContext Additional information for the request * * @returns The drawings and drawing groups state */ loadLineToolsAndGroups(layoutId: string | undefined, chartId: string | number, requestType: LineToolsAndGroupsLoadRequestType, requestContext: LineToolsAndGroupsLoadRequestContext): Promise | null>; } /** 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, options?: FormatterFormatOptions): string; /** Check if the input value satisfies the logic and return either an error or the result of the parsing */ parse?(value: string, options?: FormatterParseOptions): ErrorFormatterParseResult | SuccessFormatterParseResult; } export interface IImageStorageAdapter { /** * Return the maximum allowed image size in bytes that will be allowed by the image drawing tool. */ getMaxImageSizeInBytes(): number; } /** * 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. * @param {PropertyKeyType} optionally specifies subset of properties to return. * @nopack some shapes line fib retracement could provide properties in a packed format (using arrays instead of objects). This flag allows controlling this. * @returns properties of the drawing */ getProperties

= Record>(target?: PropertyKeyType, nopack?: boolean): P; /** * 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. * @param {boolean} saveDefaults - If `true`, the properties will be saved as defaults for the drawing. Defaults are used when the drawing is created. */ setProperties

= Record>(newProperties: P, saveDefaults?: boolean): 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 { type: "non_series_bars"; /** * Non series bars */ bars: IBarArray[]; } export interface INonSeriesStudyResult { /** Type is `non_series_data` */ type: "non_series_data"; /** Always true */ nonseries: true; /** Data */ data: object; } /** Specific formatter for number */ export interface INumberFormatter extends IFormatter { /** Formatter for a number */ format(value?: number, options?: NumberFormatterFormatOptions): string; /** * Formatter for a price change * @param currentPrice - current price * @param prevPrice - previous price * @param options - format options */ formatChange?(currentPrice: number, prevPrice: number, options?: NumberFormatterFormatOptions): string; } export interface IObservable { /** * Subscribe to changes * @param {(value:T)=>void} callback - callback function to be evoked when observed value changes */ subscribe(callback: ObservableCallback): void; /** * Unsubscribe from changes * @param {(value:T)=>void} callback - callback function to be unsubscribed */ unsubscribe(callback: ObservableCallback): void; } export interface IObservableValue extends IBoxedValue, IObservable { } export interface IObservableValueReadOnly extends IBoxedValueReadOnly, IObservable { } /** * An API object that controls order lines created with {@link IChartWidgetApi.createOrderLine}. * For more information, refer to [Trading primitives](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Trading-Primitives). */ 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 while the order line is being moved. * * @param callback Callback to be executed while the order line is being moved. */ onMoving(callback: () => void): this; /** * Attach a callback to be executed while the order line is being moved. * * @param data Data to be passed to the callback. * @param callback Callback to be executed while the order line is being moved. */ onMoving(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; /** * Get the unit of length specified for the line length of the order line. */ getLineLengthUnit(): OrderLineLengthUnit; /** * Set the line length of the order line. * * If negative number is provided for the value and the unit is 'pixel' then * the position will be relative to the left edge of the chart. * * @param value The new line length. * @param [unit] - unit for the line length, defaults to 'percentage'. */ setLineLength(value: number, unit?: OrderLineLengthUnit): 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. * * **Example** * ```javascript * orderLine.setPrice(170).setBodyFont("bold 12px Verdana") * ``` * * @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. * * **Example** * ```javascript * orderLine.setPrice(170).setQuantityFont("bold 12px Verdana") * ``` * * @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 A color string in RGBA format for the body background color (e.g., `"rgba(255, 0, 0, 0.5)"`). */ 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 A simple color string for the body text (e.g., `"red"`, `"#FF0000"`). */ 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 A color string in RGBA format (e.g., `"rgba(255, 0, 0, 0.5)"`). */ 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 A color string in RGBA format for the cancel button background color (e.g., `"rgba(255, 0, 0, 0.5)"`). */ 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 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) */ getPriceScaleById(priceScaleId: string): 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; /** Returns the pane's collapsed state */ isCollapsed(): boolean; /** Change the maximized state of the pane */ setMaximized(value: boolean): void; /** Returns the maximized state of the pane */ isMaximized(): boolean; } 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; /** * Map some values from one time scale to another. * * @param source Source times. * @param destination Destination times. * @param mode Adopt mode. `0` for continuous, `1` for precise. * * In continuous mode (`0`) every source time will be mapped to a destination time if one exists. Multiple source times may be mapped to the same destination time. * * In precise mode (`1`) every source time will be mapped to a destination time AT MOST ONCE if one exists. Some source times may not be mapped. * * @example * ```javascript * // A pine series with values [5, 5] * const sourceTimes = ctx.new_var(); * // A pine series with values [4, 5] * const destinationTimes = ctx.new_var(); * // A pine series with values [1, 2] * const values = ctx.new_var(); * * // Creates a pine series with values [2, 2] * const adopted1 = values.adopt(sourceTimes, destinationTimes, 0); * * // Creates a pine series with values [NaN, 2] * const adopted2 = values.adopt(sourceTimes, destinationTimes, 1); * ``` * * @example * * Pseudocode of the adopt algorithm: * * ``` * adopt(sourceSeries, destinationSeries, mode) = * destinationValue = most recent value in destinationSeries * sourceIndex = index of destinationValue in sourceSeries * * if mode equals 1 then * previousDestinationValue = second most recent value in destinationSeries * previousSourceIndex = index of previousDestinationValue in sourceSeries * * if sourceIndex equals previousSourceIndex * return NaN * * return value at sourceIndex * ``` */ adopt(source: IPineSeries, destination: IPineSeries, mode: 0 | 1): number; } /** * An API object that controls position lines created with {@link IChartWidgetApi.createPositionLine}. * For more information, refer to [Trading primitives](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Trading-Primitives). */ 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 unit of length specified for the line length of the position line. */ getLineLengthUnit(): PositionLineLengthUnit; /** * Get the line length of the position line. */ getLineLength(): number; /** * Set the line length of the position line. * * If negative number is provided for the value and the unit is 'pixel' then * the position will be relative to the left edge of the chart. * * @param value The new line length. * @param [unit] - unit for the line length, defaults to 'percentage'. */ setLineLength(value: number, unit?: PositionLineLengthUnit): 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. * * **Example** * ```javascript * positionLine.setPrice(170).setBodyFont("bold 12px Verdana") * ``` * * @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. * * **Example** * ```javascript * positionLine.setPrice(170).setQuantityFont("bold 12px Verdana") * ``` * * @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 background color of the position line. */ getBodyBackgroundColor(): string; /** * Set the body background color of the position line. * @param value A color string in RGBA format for the body background color (e.g., `"rgba(255, 0, 0, 0.5)"`). */ 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 A simple color string for the body text (e.g., `"red"`, `"#FF0000"`). */ 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 A color string in RGBA format (e.g., `"rgba(255, 0, 0, 0.5)"`). */ 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 A color string in RGBA format for the reverse button background color (e.g., `"rgba(255, 0, 0, 0.5)"`). */ 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 */ format(price: number, options?: PriceFormatterFormatOptions): string; /** Price change formatter */ formatChange?(price: number, prevPrice: number, options?: PriceFormatterFormatOptions): string; } /** * The Price Scale API allows interacting with the [price scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale). * 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[]; /** Returns the current currency set on the [price scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale). Returns `null` if no currency is specified. */ currency(): CurrencyInfo | null; /** * Sets a currency on the price scale. * @param {string|null} currency - currency supported by your backend (for example 'EUR', 'USD'). A null value will reset the currency to default. */ setCurrency(currency: string | null): void; /** Returns the current unit set on the [price scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale). Returns `null` if no unit is specified. */ unit(): UnitInfo | null; /** * Sets a unit on the price scale. * @param {string|null} unit - unit supported by your backend (for example 'weight', 'energy'). A null value will reset the unit to default. */ setUnit(unit: string | null): void; } 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; projectionTime?: number; } /** * Allows you to select entities ([drawings](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings) and [indicators](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators/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: DeepPartial): void; } /** * Properties of the {@link ChartingLibraryWidgetOptions.settings_adapter} property that allows saving [user settings](https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings) to your preferred storage, including server-side. */ export interface ISettingsAdapter { /** Initial settings the chart should be initiated with. */ 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. Refer to the [Drawings API](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api#drawing-groups-api) article for more information. */ 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; /** * Get the index of the pane that the study is attached to. * * @returns The pane index. */ paneIndex(): number; /** * 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 indicator's properties. * Refer to [Indicator Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides#change-the-existing-indicator) for more information. * Overrides for built-in indicators are listed in {@link SingleIndicatorOverrides}. * * @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 Platform). */ applyToEntireLayout(): Promise; /** * 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; } /** * PineJS execution context symbol information. */ export interface ISymbolInstrument { /** Period Base */ periodBase: string; /** Ticker ID */ tickerid: string; /** Currency Code */ currencyCode?: string | null; /** Unit ID */ unitId?: string | null; /** Bar resolution */ period: ResolutionString; /** 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; /** 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; /** * Time of the bar. * * @returns the timestamp in milliseconds */ bartime(): number; /** * @returns true if the bar resolution is day/week/month, false if it is intraday */ isdwm(): boolean; } export interface ISymbolValueFormatter extends INumberFormatter { /** Default formatter function used to assign the correct sign (+ or -) to a number */ format(price: number, options?: SymbolValueFormatterFormatOptions): string; /** * Formatter for a price change * @param currentPrice - current price * @param prevPrice - previous price * @param options - format options */ formatChange?(currentPrice: number, prevPrice: number, options?: SymbolValueFormatterFormatOptions): string; } /** * API object for interacting with the [time scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale). * * 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; /** Sets a new [bar spacing](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#bar-spacing). You can call {@link barSpacing} to get the current value. */ setBarSpacing(newBarSpacing: number): void; /** Returns the current [bar spacing](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#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>; } /** * An API object for interacting with the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) widget. * The Watchlist is a widget that allows users to track price movements and volume of specific financial instruments in real-time. * Watchlists also allow users to quickly switch between the symbols. * The Watchlist widget is displayed on the widget panel on the right side of the chart. * * **Notes about watchlist contents** * * Watchlist items should be symbol names which your datafeed [`resolveSymbol`](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol) method can resolve. This * means that generally shorter names such as `AAPL` can be used if your datafeed understands it. However, * it is recommend that you provide the symbol names as they appear within the `LibrarySymbolInfo` object, for * example, `NASDAQ:AAPL`. */ 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, the current list will be returned. If there is no watchList, `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. Any list item that has the `###` prefix is considered a section divider in 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. Any list item that has the `###` prefix is considered a section divider in 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, `false` will be returned. Otherwise, `true` will be 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; } /** * An API object used to change the settings of the [watermark](https://www.tradingview.com/charting-library-docs/latest/ui_elements/watermarks). */ export interface IWatermarkApi { /** * Object that can be used to read/set/watch the color of the watermark text. */ color(): IWatchedValue; /** * Object that can be used to read/set/watch the visibility of the watermark. * @deprecated use ticker/resolution/description visibility instead */ visibility(): IWatchedValue; /** * Object that can be used to read/set/watch the visibility of the watermark's ticker part. */ tickerVisibility(): IWatchedValue; /** * Object that can be used to read/set/watch the visibility of the watermark's interval part. */ intervalVisibility(): IWatchedValue; /** * Object that can be used to read/set/watch the visibility of the watermark's description part. */ descriptionVisibility(): IWatchedValue; /** * Object that can be used to read/set/watch the visibility of the watermark provider by WatermarkContentProvider. */ customVisibility(): IWatchedValue; /** * Set a custom content provider for the watermark content. * Set any part visible to turn custom watermark visibility on. * * @param provider - Custom watermark content provider, use `null` if you would like to revert back to the default content for the watermark. */ setContentProvider(provider: WatermarkContentProvider | null): void; /** * Returns the current watermark content provider. */ provider(): IWatchedValueReadonly; } /** * 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; /** * Change the visibility of the right toolbar * @param {boolean} visible - true to display the toolbar, false to hide */ changeWidgetBarVisibility(visible: boolean): void; } /** * Overrides for the 'Ichimoku Cloud' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface IchimokuCloudIndicatorOverrides { /** Default value: `#000080` */ "plots background.color": string; /** Default value: `90` */ "plots background.transparency": number; /** Default value: `true` */ "plots background.visible": boolean; /** Default value: `15` */ "conversion line.display": number; /** Default value: `0` */ "conversion line.linestyle": number; /** Default value: `1` */ "conversion line.linewidth": number; /** Default value: `line` */ "conversion line.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "conversion line.trackprice": boolean; /** Default value: `0` */ "conversion line.transparency": number; /** Default value: `#2196F3` */ "conversion line.color": string; /** Default value: `15` */ "base line.display": number; /** Default value: `0` */ "base line.linestyle": number; /** Default value: `1` */ "base line.linewidth": number; /** Default value: `line` */ "base line.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "base line.trackprice": boolean; /** Default value: `0` */ "base line.transparency": number; /** Default value: `#801922` */ "base line.color": string; /** Default value: `15` */ "lagging span.display": number; /** Default value: `0` */ "lagging span.linestyle": number; /** Default value: `1` */ "lagging span.linewidth": number; /** Default value: `line` */ "lagging span.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lagging span.trackprice": boolean; /** Default value: `0` */ "lagging span.transparency": number; /** Default value: `#43A047` */ "lagging span.color": string; /** Default value: `15` */ "leading span a.display": number; /** Default value: `0` */ "leading span a.linestyle": number; /** Default value: `1` */ "leading span a.linewidth": number; /** Default value: `line` */ "leading span a.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "leading span a.trackprice": boolean; /** Default value: `0` */ "leading span a.transparency": number; /** Default value: `#A5D6A7` */ "leading span a.color": string; /** Default value: `15` */ "leading span b.display": number; /** Default value: `0` */ "leading span b.linestyle": number; /** Default value: `1` */ "leading span b.linewidth": number; /** Default value: `line` */ "leading span b.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "leading span b.trackprice": boolean; /** Default value: `0` */ "leading span b.transparency": number; /** Default value: `#FAA1A4` */ "leading span b.color": string; [key: string]: StudyOverrideValueType; } /** * Override properties for the Icon drawing tool. */ export interface IconLineToolOverrides { /** Default value: `1.5707963267948966` */ "linetoolicon.angle": number; /** Default value: `#2962FF` */ "linetoolicon.color": string; /** * Default value: `61720` * * Refer to [Drawings list](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/Drawings-List#icons) for a list of icons and thier hex codes. */ /** Default value: `40` */ "linetoolicon.size": number; } export interface IconOptions { /** Icon number */ icon: number; } /** * Override properties for the Image drawing tool. */ export interface ImageLineToolOverrides { /** Default value: `0` */ "linetoolimage.angle": number; /** Default value: `0` */ "linetoolimage.cssHeight": number; /** Default value: `0` */ "linetoolimage.cssWidth": number; /** Default value: `0` */ "linetoolimage.transparency": number; } export interface IndicatorOptions { title: string; shortTitle: string; overlay: boolean; format: "price" | "volume" | "percent"; precision: number; } export interface IndividualPosition extends IndividualPositionBase, CustomFields { } /** * Describes an individual position. */ export interface IndividualPositionBase { /** Individual position ID. Usually id should be equal to brokerSymbol */ id: string; /** Individual position open date (UNIX timestamp in milliseconds) */ date: number; /** Symbol name */ symbol: string; /** Individual position Quantity */ qty: number; /** Individual position Side */ side: Side; /** Individual position price */ price: number; /** Determines whether individual position can be closed */ canBeClosed?: boolean; } /** * Override properties for the Infoline drawing tool. */ export interface InfolineLineToolOverrides { /** Default value: `true` */ "linetoolinfoline.alwaysShowStats": boolean; /** Default value: `false` */ "linetoolinfoline.bold": boolean; /** Default value: `false` */ "linetoolinfoline.extendLeft": boolean; /** Default value: `false` */ "linetoolinfoline.extendRight": boolean; /** Default value: `14` */ "linetoolinfoline.fontsize": number; /** Default value: `center` */ "linetoolinfoline.horzLabelsAlign": string; /** Default value: `false` */ "linetoolinfoline.italic": boolean; /** Default value: `0` */ "linetoolinfoline.leftEnd": number; /** Default value: `#2962FF` */ "linetoolinfoline.linecolor": string; /** Default value: `0` */ "linetoolinfoline.linestyle": number; /** Default value: `2` */ "linetoolinfoline.linewidth": number; /** Default value: `0` */ "linetoolinfoline.rightEnd": number; /** Default value: `true` */ "linetoolinfoline.showAngle": boolean; /** Default value: `true` */ "linetoolinfoline.showBarsRange": boolean; /** Default value: `true` */ "linetoolinfoline.showDateTimeRange": boolean; /** Default value: `true` */ "linetoolinfoline.showDistance": boolean; /** Default value: `false` */ "linetoolinfoline.showMiddlePoint": boolean; /** Default value: `true` */ "linetoolinfoline.showPercentPriceRange": boolean; /** Default value: `true` */ "linetoolinfoline.showPipsPriceRange": boolean; /** Default value: `false` */ "linetoolinfoline.showPriceLabels": boolean; /** Default value: `true` */ "linetoolinfoline.showPriceRange": boolean; /** Default value: `1` */ "linetoolinfoline.statsPosition": number; /** Default value: `#2962FF` */ "linetoolinfoline.textcolor": string; /** Default value: `bottom` */ "linetoolinfoline.vertLabelsAlign": string; } export interface InitialSettingsMap { /** Initial Setting */ [key: string]: string; } export interface InputFunctions { bool(defaultValue: boolean, title: string, options?: Partial): boolean; int(defaultValue: number, title: string, options?: Partial): number; source(defaultValue: StudyPriceSource, title: string, options?: Partial): IPineSeries; string(defaultValue: string, title: string, options?: Partial>): TOptions[number]; symbol(defaultValue: string, title: string, options?: Partial): string; } /** * Override properties for the Insidepitchfork drawing tool. */ export interface InsidepitchforkLineToolOverrides { /** Default value: `false` */ "linetoolinsidepitchfork.extendLines": boolean; /** Default value: `true` */ "linetoolinsidepitchfork.fillBackground": boolean; /** Default value: `0.25` */ "linetoolinsidepitchfork.level0.coeff": number; /** Default value: `#ffb74d` */ "linetoolinsidepitchfork.level0.color": string; /** Default value: `0` */ "linetoolinsidepitchfork.level0.linestyle": number; /** Default value: `2` */ "linetoolinsidepitchfork.level0.linewidth": number; /** Default value: `false` */ "linetoolinsidepitchfork.level0.visible": boolean; /** Default value: `0.382` */ "linetoolinsidepitchfork.level1.coeff": number; /** Default value: `#81c784` */ "linetoolinsidepitchfork.level1.color": string; /** Default value: `0` */ "linetoolinsidepitchfork.level1.linestyle": number; /** Default value: `2` */ "linetoolinsidepitchfork.level1.linewidth": number; /** Default value: `false` */ "linetoolinsidepitchfork.level1.visible": boolean; /** Default value: `0.5` */ "linetoolinsidepitchfork.level2.coeff": number; /** Default value: `#089981` */ "linetoolinsidepitchfork.level2.color": string; /** Default value: `0` */ "linetoolinsidepitchfork.level2.linestyle": number; /** Default value: `2` */ "linetoolinsidepitchfork.level2.linewidth": number; /** Default value: `true` */ "linetoolinsidepitchfork.level2.visible": boolean; /** Default value: `0.618` */ "linetoolinsidepitchfork.level3.coeff": number; /** Default value: `#089981` */ "linetoolinsidepitchfork.level3.color": string; /** Default value: `0` */ "linetoolinsidepitchfork.level3.linestyle": number; /** Default value: `2` */ "linetoolinsidepitchfork.level3.linewidth": number; /** Default value: `false` */ "linetoolinsidepitchfork.level3.visible": boolean; /** Default value: `0.75` */ "linetoolinsidepitchfork.level4.coeff": number; /** Default value: `#00bcd4` */ "linetoolinsidepitchfork.level4.color": string; /** Default value: `0` */ "linetoolinsidepitchfork.level4.linestyle": number; /** Default value: `2` */ "linetoolinsidepitchfork.level4.linewidth": number; /** Default value: `false` */ "linetoolinsidepitchfork.level4.visible": boolean; /** Default value: `1` */ "linetoolinsidepitchfork.level5.coeff": number; /** Default value: `#2962FF` */ "linetoolinsidepitchfork.level5.color": string; /** Default value: `0` */ "linetoolinsidepitchfork.level5.linestyle": number; /** Default value: `2` */ "linetoolinsidepitchfork.level5.linewidth": number; /** Default value: `true` */ "linetoolinsidepitchfork.level5.visible": boolean; /** Default value: `1.5` */ "linetoolinsidepitchfork.level6.coeff": number; /** Default value: `#9c27b0` */ "linetoolinsidepitchfork.level6.color": string; /** Default value: `0` */ "linetoolinsidepitchfork.level6.linestyle": number; /** Default value: `2` */ "linetoolinsidepitchfork.level6.linewidth": number; /** Default value: `false` */ "linetoolinsidepitchfork.level6.visible": boolean; /** Default value: `1.75` */ "linetoolinsidepitchfork.level7.coeff": number; /** Default value: `#e91e63` */ "linetoolinsidepitchfork.level7.color": string; /** Default value: `0` */ "linetoolinsidepitchfork.level7.linestyle": number; /** Default value: `2` */ "linetoolinsidepitchfork.level7.linewidth": number; /** Default value: `false` */ "linetoolinsidepitchfork.level7.visible": boolean; /** Default value: `2` */ "linetoolinsidepitchfork.level8.coeff": number; /** Default value: `#F77C80` */ "linetoolinsidepitchfork.level8.color": string; /** Default value: `0` */ "linetoolinsidepitchfork.level8.linestyle": number; /** Default value: `2` */ "linetoolinsidepitchfork.level8.linewidth": number; /** Default value: `false` */ "linetoolinsidepitchfork.level8.visible": boolean; /** Default value: `#F23645` */ "linetoolinsidepitchfork.median.color": string; /** Default value: `0` */ "linetoolinsidepitchfork.median.linestyle": number; /** Default value: `2` */ "linetoolinsidepitchfork.median.linewidth": number; /** Default value: `true` */ "linetoolinsidepitchfork.median.visible": boolean; /** Default value: `2` */ "linetoolinsidepitchfork.style": number; /** Default value: `80` */ "linetoolinsidepitchfork.transparency": number; } export interface InstrumentInfo { /** The default quantity parameters for a symbol. */ qty: QuantityMetainfo; /** * The value of one pip for the instrument, expressed in the account currency. * This value is displayed in the *Order info* section of the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket). * * If set to `0`, the *Order info* section will not be displayed, and there will be no way to show it programmatically. * To ensure the section and the value appears in the UI, set this property to a non-zero value. * * If you implement [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal), use {@link IBrokerTerminal.subscribePipValue} to enable dynamic value updates. */ 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 Order Ticket. */ 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; /** Leverage */ leverage?: string; /** * The margin requirement for the instrument. A 3% margin rate should be represented as 0.03. */ 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 Order Ticket. */ 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 Order Ticket */ 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; /** Supported order types for the instrument */ allowedOrderTypes?: OrderType[]; } export interface IntInputOptions extends CommonInputOptions { minVal: number; maxVal: number; step: 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 Order Ticket */ reason?: string; /** Reason heading */ reasonHeading?: 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; } /** * Overrides for the 'Keltner Channels' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface KeltnerChannelsIndicatorOverrides { /** Default value: `#2196F3` */ "plots background.color": string; /** Default value: `95` */ "plots background.transparency": number; /** Default value: `true` */ "plots background.visible": boolean; /** Default value: `15` */ "upper.display": number; /** Default value: `0` */ "upper.linestyle": number; /** Default value: `1` */ "upper.linewidth": number; /** Default value: `line` */ "upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "upper.trackprice": boolean; /** Default value: `0` */ "upper.transparency": number; /** Default value: `#2196F3` */ "upper.color": string; /** Default value: `15` */ "middle.display": number; /** Default value: `0` */ "middle.linestyle": number; /** Default value: `1` */ "middle.linewidth": number; /** Default value: `line` */ "middle.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "middle.trackprice": boolean; /** Default value: `0` */ "middle.transparency": number; /** Default value: `#2196F3` */ "middle.color": string; /** Default value: `15` */ "lower.display": number; /** Default value: `0` */ "lower.linestyle": number; /** Default value: `1` */ "lower.linewidth": number; /** Default value: `line` */ "lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lower.trackprice": boolean; /** Default value: `0` */ "lower.transparency": number; /** Default value: `#2196F3` */ "lower.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Klinger Oscillator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface KlingerOscillatorIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; /** Default value: `15` */ "signal.display": number; /** Default value: `0` */ "signal.linestyle": number; /** Default value: `1` */ "signal.linewidth": number; /** Default value: `line` */ "signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "signal.trackprice": boolean; /** Default value: `0` */ "signal.transparency": number; /** Default value: `#43A047` */ "signal.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Know Sure Thing' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface KnowSureThingIndicatorOverrides { /** Default value: `#787B86` */ "zero.color": string; /** Default value: `2` */ "zero.linestyle": number; /** Default value: `1` */ "zero.linewidth": number; /** Default value: `true` */ "zero.visible": boolean; /** Default value: `0` */ "zero.value": number; /** Default value: `15` */ "kst.display": number; /** Default value: `0` */ "kst.linestyle": number; /** Default value: `1` */ "kst.linewidth": number; /** Default value: `line` */ "kst.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "kst.trackprice": boolean; /** Default value: `0` */ "kst.transparency": number; /** Default value: `#089981` */ "kst.color": string; /** Default value: `15` */ "signal.display": number; /** Default value: `0` */ "signal.linestyle": number; /** Default value: `1` */ "signal.linewidth": number; /** Default value: `line` */ "signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "signal.trackprice": boolean; /** Default value: `0` */ "signal.transparency": number; /** Default value: `#F23645` */ "signal.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Least Squares Moving Average' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface LeastSquaresMovingAverageIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * 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 { /** * The method is designed to get additional information for an indicator and allows you to initialize variables needed for your data calculations. * For example, you can reset a counter with this method. The library calls `init` when the indicator should be calculated from scratch. * For more information, refer to the [Constructor](https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom-indicator-constructor#init) article. * * Example: * ``` * this.init = function(context, inputCallback) { * var symbol = '#EQUITY'; * var period = PineJS.Std.period(this._context); * context.new_sym(symbol, period); * }; * ``` * @param 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 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 // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; } export interface LibraryPineStudyConstructor { /** * Custom Study constructor */ 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; /** * Session to display. See {@link LibrarySymbolInfo.session_display}. */ "session-display"?: string; } export interface LibrarySymbolInfo { /** * It is a symbol name within an exchange, such as `AAPL` or `9988` (Hong Kong). * Note that it should not contain the exchange name. * This symbol name is visible to users and can be repeated. * * By default, `name` is used to resolve symbols in the [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api). * If you use {@link LibrarySymbolInfo.ticker}, the library will use the ticker for Datafeed API requests. */ name: string; /** * Array of base symbols * Example: for `AAPL*MSFT` it is `['NASDAQ:AAPL', 'NASDAQ:MSFT']` */ base_name?: string[]; /** * It is an unique identifier for a particular symbol in your [symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology). * If you specify this property, 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. * * You should avoid using colons (":") in ticker values unless you are following the TradingView format: "NYSE:IBM". Using colons may cause unexpected behaviour and display bugs. */ 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 the symbol. The time should be in the **exchange** time zone specified in the {@link LibrarySymbolInfo.timezone} property. Refer to the [Trading sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessions) article for more information. * @example "1700-0200" */ session: string; /** * The session value to display in the UI. If not specified, then `session` is used. */ session_display?: string; /** * A string that contains a list of non-trading holidays for the symbol. * Holiday dates should be in the `YYYYMMDD` format. * These dates are not displayed on the chart. * * You can specify a correction for a holiday using {@link LibrarySymbolInfo.corrections}. * @example "20181105,20181107,20181112" */ session_holidays?: string; /** * List of corrections for a symbol. The corrections are days when the trading session differs from the default one set in {@link LibrarySymbolInfo.session}. * The `corrections` value is a string in the following format: `SESSION:YYYYMMDD`. * For more information, refer to [corrections](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#corrections). * * The string below specifies corrections for two trading days: * * - November 13, 2018. This trading day is split into two sessions. The first session starts at 19:00 four days before (November 9, 2018) and ends at 23:50 four days before. The second session starts at 10:00 and ends at 18:45. * - November 14, 2018. The session starts at 10:00 and ends at 14:00. * * @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; /** * The time zone of the **exchange** where the symbol is listed. The time zone value should be in the OlsonDB format. * Refer to [Time zones](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezones) for a full list of supported time zones. */ 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 format](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; /** * A number of decimal places or fractions that the price has. * * The `pricescale` value depends on the [price format](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#price-format). * If you want to display the price in the decimal format, `pricescale` should be `10^n`, where `n` is the number of decimal places. * **Examples:** `1`, `10`, `10000000`. * * If you want to display the price in the fractional format, `pricescale` should be `2^n`. * This value represents the number of fractions. * **Examples:** `8`, `16`, `256`. */ pricescale: number; /** * The number of units that make up one tick. * For example, U.S. equities are quotes in decimals, and tick in decimals, and can go up +/- `.01`. * Therefore, the tick increment is 1 and `minmov = 1`. But the e-mini S&P futures contract, though quoted in decimals, goes up in `.25` increments, so the tick increment is 25 and `minmov = 25`. * Refer to [Price format](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#price-format) for more information. */ 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; /** * This property is used to display prices in the [fraction of a fraction](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#fraction-of-a-fraction-format) format. * For example, the ZBM2023 tick size is 1/4 of a 32nd. To display this security, set `minmov = 1`, `pricescale = 128`, `minmove2 = 4`. * * For common prices, `minmove2` can be skipped or set to `0`. */ minmove2?: number; /** * 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 the tick size is 0.01 for a price less than 10, the tick size is 0.02 for a price less than 25, the tick size is 0.05 for a price greater than or equal to 25. */ variable_tick_size?: string; /** * A flag indicating whether your datafeed contains intraday (minutes) data for this symbol. * If `true`, the library requests this data when an intraday resolution is selected. If `false`, _No data here_ is displayed on the chart. * * This property is required to enable intraday resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-minutes-intraday) article for more information. * @default false */ has_intraday?: boolean; /** * An array of [resolutions](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution) which should be enabled in the _Resolution_ drop-down menu for this symbol. * Each item of the array is expected to be a string that has a specific [format](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-format). * * If one changes the symbol and the new symbol does not support the selected resolution, an error message will be shown on the chart. * * **Resolution availability logic (pseudocode):** * ``` * resolutionAvailable = * resolution.isIntraday * ? symbol.has_intraday && symbol.supported_resolutions(resolution) * : symbol.supported_resolutions(resolution); * ``` * * If `supported_resolutions` is `[]` (empty array), all resolutions are disabled in the _Resolution_ drop-down menu. * * If `supported_resolutions` is `undefined`, all resolutions that the chart support ({@link DatafeedConfiguration.supported_resolutions}) and custom resolutions are enabled. * * Note that the list of available time frames depends on supported resolutions. * Time frames that require resolutions that are unavailable for a particular symbol will be hidden. * Refer to [Time frame toolbar](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale#time-frame-toolbar) for more information. */ supported_resolutions?: ResolutionString[]; /** * An array of intraday (minutes) resolutions that your datafeed supports. Items in the array should be listed in ascending order, for example: `["1", "2"]`. * * This property is required to enable intraday resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-minutes-intraday) article for more information. * Note that each resolution in `intraday_multipliers` should be handled in the {@link IDatafeedChartApi.getBars} implementation. * Consider the [example](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#example). * * The library also uses resolutions listed in `intraday_multipliers` to display higher resolution that your datafeed does not explicitly support. If `intraday_multipliers` is not specified, the library cannot build additional resolutions. * * Note that the library **cannot** build daily, weekly, or monthly resolutions using intraday data. * @default [] — specifies that the datafeed can provide data for any requested resolution. */ intraday_multipliers?: string[]; /** * A flag indicating whether your datafeed contains seconds data for this symbol. * If `true`, the library requests this data when a seconds resolution is selected. If `false`, _No data here_ is displayed on the chart. * * You should set `has_seconds` to `true` to enable seconds resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-seconds) article for more information. * @default false */ has_seconds?: boolean; /** * A flag indicating whether your datafeed contains ticks data for this symbol. * If `true`, the library requests this data when a resolution in ticks is selected. If `false`, _No data here_ is displayed on the chart. * * You should set `has_ticks` to `true` to enable ticks resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-ticks) article for more information. * @default false */ has_ticks?: boolean; /** * An array of seconds resolutions that your datafeed supports. Items in the array should be listed in ascending order and **should not** include letters, for example: `["1", "2"]`. * This property is required to enable seconds resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-seconds) article for more information. * * The library also uses resolutions listed in `seconds_multipliers` to display higher resolution that your datafeed does not explicitly support. If `seconds_multipliers` is not specified, the library cannot build additional resolutions. * Consider the example. You need to enable one-second and five-second resolutions but your datafeed contains only one-second data. In this case, you should set `seconds_multipliers` to `["1"]`. * The library will build the five-second resolution from one-second data. */ seconds_multipliers?: string[]; /** * The boolean value showing whether or not seconds bars for this symbol can be built from ticks. Only available in Trading Platform. * * * {@link LibrarySymbolInfo.has_seconds} must also be `true` * * {@link LibrarySymbolInfo.has_ticks} must also be `true` * * {@link LibrarySymbolInfo.seconds_multipliers} must be an empty array or only contain multipliers that the datafeed provides itself * * The library builds resolutions from ticks only if there are no seconds resolutions from the datafeed or the provided resolutions are larger then the required one. For example, the datafeed provides `3S` resolution. In this case, the library can build only `1S` or `2S` resolutions from ticks. Resolutions such as `15S` will be build with seconds bars. * @default false */ build_seconds_from_ticks?: boolean; /** * A flag indicating whether your datafeed contains daily data for this symbol. * If `true`, the library requests this data when a daily resolution is selected. If `false`, _No data here_ is displayed on the chart. * * `has_daily` is set to `true` by default. However, you should also specify {@link daily_multipliers} to enable daily resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-days) article for more information. * @default true */ has_daily?: boolean; /** * An array of daily resolutions that your datafeed supports. Items in the array should be listed in ascending order and **should not** include letters, for example: `["1", "2"]`. * This property is required to enable daily resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-days) article for more information. * * The library also uses resolutions listed in `daily_multipliers` to display higher resolution that your datafeed does not explicitly support. If `daily_multipliers` is not specified, the library cannot build additional resolutions. * @default ["1"] */ daily_multipliers?: string[]; /** * A flag indicating whether your datafeed contains weekly or monthly data for this symbol. If `true`, the library requests this data when the corresponding resolution is selected. * To enable weekly or monthly resolutions, you should also specify the {@link weekly_multipliers} or {@link monthly_multipliers} properties. * Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-weeks--months) article for more information. * * If `has_weekly_and_monthly` is set to `false`, the library attempts to build the resolutions using daily bars. Note that building bars requires a large number of requests to your datafeed. * If the library fails to build bars, _No data here_ is displayed on the chart. * @default false */ has_weekly_and_monthly?: boolean; /** * An array of weekly resolutions that your datafeed supports. Items in the array should be listed in ascending order and **should not** include letters, for example: `["1", "3"]`. * This property is required to enable weekly resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-weeks--months) article for more information. * * The library also uses resolutions listed in `weekly_multipliers` to display higher resolution that your datafeed does not explicitly support. If `weekly_multipliers` is not specified, the library cannot build additional resolutions. * @default ['1'] */ weekly_multipliers?: string[]; /** * An array of monthly resolutions that your datafeed supports. Items in the array should be listed in ascending order and **should not** include letters, for example: `["1", "3", "6", "12"]`. * This property is required to enable monthly resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-weeks--months) article for more information. * * The library also uses resolutions listed in `monthly_multipliers` to display higher resolution that your datafeed does not explicitly support. If `monthly_multipliers` is not specified, the library cannot build additional resolutions. * @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; /** * Represents what values are supported by the symbol. Possible values: * * - `ohlcv` — the symbol supports open, high, low, close prices and has volume. * - `ohlc` — the symbol supports open, high, low, close, prices but doesn't have volume. * - `c` — the symbol supports only close price. This makes the chart show the symbol data using only line-based styles. * @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. * For `delayed_streaming` and `endofday` type of data, the status is displayed as an icon and the *Data is delayed* section in the [_Legend_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#display-delayed-data-information), next to the market status icon. * Note that you should also enable the [`display_data_mode`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#display_data_mode) featureset. * * When declaring `delayed_streaming` you also have to specify its {@link LibrarySymbolInfo.delay} in seconds. */ data_status?: "streaming" | "endofday" | "delayed_streaming"; /** * Type of delay that is associated to the data or real delay for real time data. * - `0` for realtime * - `-1` for endofday * - or delay in seconds (for delayed realtime) */ delay?: number; /** * 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`. * The library will request data for this symbol starting from that time point. */ expiration_date?: number; /** Sector for stocks to be displayed in the Security Info. */ sector?: string; /** Industry for stocks to be displayed in the Security 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 Security 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[]; /** * An ID of a subsession specified in {@link subsessions}. The value must match the subsession that is currently displayed on the chart. * For more information, refer to the [Extended sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#extended-sessions) section. */ subsession_id?: string; /** * An array of objects that contain information about certain subsessions within the extended session. * For more information, refer to the [Extended sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#extended-sessions) section. */ subsessions?: LibrarySubsessionInfo[]; /** * Optional ID of a price source for a symbol. Should match one of the price sources from the {@link price_sources} array. * * Note that you should set the [`symbol_info_price_source`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#symbol_info_price_source) featureset to `true` to display the symbol price source in the main series legend. */ price_source_id?: string; /** * Supported price sources for the symbol. * Price sources appear in the series legend and indicate the origin of values represented by symbol bars. * Example price sources: "Spot Price", "Ask", "Bid", etc. * The price source information is valuable when viewing non-OHLC series types. * * Note that you should set the [`symbol_info_price_source`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#symbol_info_price_source) featureset to `true` to display the symbol price source in the main series legend. * @example [{ id: '1', name: 'Spot Price' }, { id: '321', name: 'Bid' }] */ price_sources?: SymbolInfoPriceSource[]; /** * URL of image/s to be displayed as the logo/s for the symbol. The `show_symbol_logos` featureset needs to be enabled for this to be visible in the UI. * * - If a single url is returned then that url will solely be used to display the symbol logo. * - If two urls are provided then the images will be displayed as two partially overlapping * circles with the first url appearing on top. This is typically used for FOREX where you would * like to display two country flags are the symbol logo. * * The image/s should ideally be square in dimension. You can use any image type which * the browser supports natively. * * Examples: * - `https://yourserver.com/apple.svg` * - `/images/myImage.png` * - `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3...` * - `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4...` */ logo_urls?: [ string ] | [ string, string ]; /** * URL of image to be displayed as the logo for the exchange. The `show_exchange_logos` featureset needs to be enabled for this to be visible in the UI. * * The image should ideally be square in dimension. You can use any image type which * the browser supports natively. Simple SVG images are recommended. * * Examples: * - `https://yourserver.com/exchangeLogo.svg` * - `/images/myImage.png` * - `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3...` * - `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4...` */ exchange_logo?: string; /** * Additional metadata to include with the symbol information. * These parameters will not affect existing properties such as 'ticker' or 'name' * and will not be processed by the library. However, they can be accessed later * through the {@link IChartWidgetApi.symbolExt} method, impacting existing * properties such as 'ticker' or 'name'. */ library_custom_fields?: Record; } 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 { /** Color type {@link ColorType} */ colorType?: ColorType; /** Line gradient start color */ gradientStartColor?: string; /** Line gradient end color */ gradientEndColor?: string; /** Line color */ color: string; /** Line Style {@link LineStyle} */ linestyle: number; /** Line width */ linewidth: number; } export interface LineStyles { hline: { style_dashed: typeof LINESTYLE_DASHED; style_dotted: typeof LINESTYLE_DOTTED; style_solid: typeof LINESTYLE_SOLID; }; } /** * Represents the state of a Drawing */ export interface LineToolState { /** The entity ID of the drawing */ id: EntityId; /** The associated symbol ID for the drawing */ symbol?: string; /** The source ID of the object's owner */ ownerSource: string; /** The ID of the group to which drawing belongs */ groupId?: string; /** The associated symbol's currency ID */ currencyId?: string | null; /** The associated symbol's unit ID */ unitId?: string | null; /** The current state object of the drawing */ state: unknown; } /** * Additional information for the {@link IExternalSaveLoadAdapter.loadLineToolsAndGroups} request. */ export interface LineToolsAndGroupsLoadRequestContext { /** The name / identifier of the symbol displayed as the main series on the chart. */ symbol?: string; } /** * Represents the state of drawings and groups */ export interface LineToolsAndGroupsState { /** A map of sources to drawing states */ sources: Map | null; /** A map of group IDs to drawings group states */ groups: Map; /** The symbol ID associated with the drawings and groups */ symbol?: string; } /** * Represents the state of a group of LineTools */ export interface LineToolsGroupState { /** The ID of the drawings group */ id: string; /** The name of the drawings group */ name: string; /** The symbol associated with the drawings group */ symbol: string; /** The associated symbol's currency ID */ currencyId?: string | null; /** The associated symbol's unit ID */ unitId?: string | null; } /** * Overrides for the 'Linear Regression Curve' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface LinearRegressionCurveIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Linear Regression Slope' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface LinearRegressionSlopeIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#FF5252` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * 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; } /** * Overrides for the 'MACD' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MACDIndicatorOverrides { /** Default value: `15` */ "histogram.display": number; /** Default value: `0` */ "histogram.linestyle": number; /** Default value: `1` */ "histogram.linewidth": number; /** Default value: `columns` */ "histogram.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "histogram.trackprice": boolean; /** Default value: `0` */ "histogram.transparency": number; /** Default value: `#FF5252` */ "histogram.color": string; /** Default value: `15` */ "macd.display": number; /** Default value: `0` */ "macd.linestyle": number; /** Default value: `1` */ "macd.linewidth": number; /** Default value: `line` */ "macd.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "macd.trackprice": boolean; /** Default value: `0` */ "macd.transparency": number; /** Default value: `#2196F3` */ "macd.color": string; /** Default value: `15` */ "signal.display": number; /** Default value: `0` */ "signal.linestyle": number; /** Default value: `1` */ "signal.linewidth": number; /** Default value: `line` */ "signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "signal.trackprice": boolean; /** Default value: `0` */ "signal.transparency": number; /** Default value: `#FF6D00` */ "signal.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'MA Cross' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MACrossIndicatorOverrides { /** Default value: `15` */ "short:plot.display": number; /** Default value: `0` */ "short:plot.linestyle": number; /** Default value: `1` */ "short:plot.linewidth": number; /** Default value: `line` */ "short:plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "short:plot.trackprice": boolean; /** Default value: `0` */ "short:plot.transparency": number; /** Default value: `#43A047` */ "short:plot.color": string; /** Default value: `15` */ "long:plot.display": number; /** Default value: `0` */ "long:plot.linestyle": number; /** Default value: `1` */ "long:plot.linewidth": number; /** Default value: `line` */ "long:plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "long:plot.trackprice": boolean; /** Default value: `0` */ "long:plot.transparency": number; /** Default value: `#FF6D00` */ "long:plot.color": string; /** Default value: `15` */ "crosses.display": number; /** Default value: `0` */ "crosses.linestyle": number; /** Default value: `4` */ "crosses.linewidth": number; /** Default value: `cross` */ "crosses.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "crosses.trackprice": boolean; /** Default value: `0` */ "crosses.transparency": number; /** Default value: `#2196F3` */ "crosses.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'MA with EMA Cross' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MAwithEMACrossIndicatorOverrides { /** Default value: `15` */ "ma.display": number; /** Default value: `0` */ "ma.linestyle": number; /** Default value: `1` */ "ma.linewidth": number; /** Default value: `line` */ "ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ma.trackprice": boolean; /** Default value: `0` */ "ma.transparency": number; /** Default value: `#FF6D00` */ "ma.color": string; /** Default value: `15` */ "ema.display": number; /** Default value: `0` */ "ema.linestyle": number; /** Default value: `1` */ "ema.linewidth": number; /** Default value: `line` */ "ema.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ema.trackprice": boolean; /** Default value: `0` */ "ema.transparency": number; /** Default value: `#43A047` */ "ema.color": string; /** Default value: `15` */ "crosses.display": number; /** Default value: `0` */ "crosses.linestyle": number; /** Default value: `4` */ "crosses.linewidth": number; /** Default value: `cross` */ "crosses.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "crosses.trackprice": boolean; /** Default value: `0` */ "crosses.transparency": number; /** Default value: `#2196F3` */ "crosses.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Majority Rule' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MajorityRuleIndicatorOverrides { /** Default value: `15` */ "majority rule.display": number; /** Default value: `0` */ "majority rule.linestyle": number; /** Default value: `1` */ "majority rule.linewidth": number; /** Default value: `line` */ "majority rule.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "majority rule.trackprice": boolean; /** Default value: `0` */ "majority rule.transparency": number; /** Default value: `#FF5252` */ "majority rule.color": string; [key: string]: StudyOverrideValueType; } export interface MappedObject { [key: string]: TValue | undefined; } export interface Mark { /** ID of the mark */ id: string | number; /** * Time for the mark. * Unix timestamp in seconds. */ 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://yourserver.com/adobe.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 { /** Border color */ border: string; /** Background color */ background: string; } /** * Overrides for the 'Mass Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MassIndexIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } export interface MathFunctions { max(value: number, ...args: (IPineSeries | number)[] | number[]): number; max(value: IPineSeries, ...args: (IPineSeries | number)[] | number[]): IPineSeries; min(value: number, ...args: (IPineSeries | number)[] | number[]): number; min(value: IPineSeries, ...args: (IPineSeries | number)[] | number[]): IPineSeries; negative(value: IPineSeries): IPineSeries; negative(value: number): number; } /** * Overrides for the 'McGinley Dynamic' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface McGinleyDynamicIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Median Price' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MedianPriceIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#FF6D00` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** Separator for a dropdown or context menu */ export interface MenuSeparator extends ActionDescription { /** Is a menu separator */ separator: boolean; } /** * Overrides for the 'Momentum' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MomentumIndicatorOverrides { /** Default value: `#787B86` */ "zero.color": string; /** Default value: `2` */ "zero.linestyle": number; /** Default value: `1` */ "zero.linewidth": number; /** Default value: `true` */ "zero.visible": boolean; /** Default value: `0` */ "zero.value": number; /** Default value: `15` */ "mom.display": number; /** Default value: `0` */ "mom.linestyle": number; /** Default value: `1` */ "mom.linewidth": number; /** Default value: `line` */ "mom.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "mom.trackprice": boolean; /** Default value: `0` */ "mom.transparency": number; /** Default value: `#2196F3` */ "mom.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Money Flow Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MoneyFlowIndexIndicatorOverrides { /** Default value: `#7E57C2` */ "hlines background.color": string; /** Default value: `90` */ "hlines background.transparency": number; /** Default value: `true` */ "hlines background.visible": boolean; /** Default value: `#787B86` */ "upperlimit.color": string; /** Default value: `2` */ "upperlimit.linestyle": number; /** Default value: `1` */ "upperlimit.linewidth": number; /** Default value: `true` */ "upperlimit.visible": boolean; /** Default value: `80` */ "upperlimit.value": number; /** Default value: `#787B86` */ "lowerlimit.color": string; /** Default value: `2` */ "lowerlimit.linestyle": number; /** Default value: `1` */ "lowerlimit.linewidth": number; /** Default value: `true` */ "lowerlimit.visible": boolean; /** Default value: `20` */ "lowerlimit.value": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#7E57C2` */ "plot.color": string; [key: string]: StudyOverrideValueType; } 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; } /** * Overrides for the 'Moving Average Adaptive' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MovingAverageAdaptiveIndicatorOverrides { /** Default value: `15` */ "plot 1.display": number; /** Default value: `0` */ "plot 1.linestyle": number; /** Default value: `1` */ "plot 1.linewidth": number; /** Default value: `line` */ "plot 1.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "plot 1.transparency": number; /** Default value: `false` */ "plot 1.trackprice": boolean; /** Default value: `#AB47BC` */ "plot 1.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Moving Average Channel' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MovingAverageChannelIndicatorOverrides { /** Default value: `#2196F3` */ "plots background.color": string; /** Default value: `90` */ "plots background.transparency": number; /** Default value: `true` */ "plots background.visible": boolean; /** Default value: `15` */ "upper.display": number; /** Default value: `0` */ "upper.linestyle": number; /** Default value: `1` */ "upper.linewidth": number; /** Default value: `line` */ "upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "upper.trackprice": boolean; /** Default value: `0` */ "upper.transparency": number; /** Default value: `#2196F3` */ "upper.color": string; /** Default value: `15` */ "lower.display": number; /** Default value: `0` */ "lower.linestyle": number; /** Default value: `1` */ "lower.linewidth": number; /** Default value: `line` */ "lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lower.trackprice": boolean; /** Default value: `0` */ "lower.transparency": number; /** Default value: `#FF6D00` */ "lower.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Moving Average Double' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MovingAverageDoubleIndicatorOverrides { /** Default value: `15` */ "plot 1.display": number; /** Default value: `0` */ "plot 1.linestyle": number; /** Default value: `1` */ "plot 1.linewidth": number; /** Default value: `line` */ "plot 1.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 1.trackprice": boolean; /** Default value: `0` */ "plot 1.transparency": number; /** Default value: `#FF6D00` */ "plot 1.color": string; /** Default value: `15` */ "plot 2.display": number; /** Default value: `0` */ "plot 2.linestyle": number; /** Default value: `1` */ "plot 2.linewidth": number; /** Default value: `line` */ "plot 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 2.trackprice": boolean; /** Default value: `0` */ "plot 2.transparency": number; /** Default value: `#2196F3` */ "plot 2.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Moving Average Exponential' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MovingAverageExponentialIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; /** Default value: `0` */ "smoothed ma.display": number; /** Default value: `0` */ "smoothed ma.linestyle": number; /** Default value: `1` */ "smoothed ma.linewidth": number; /** Default value: `line` */ "smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "smoothed ma.trackprice": boolean; /** Default value: `0` */ "smoothed ma.transparency": number; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Moving Average Hamming' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MovingAverageHammingIndicatorOverrides { /** Default value: `15` */ "plot 1.display": number; /** Default value: `0` */ "plot 1.linestyle": number; /** Default value: `1` */ "plot 1.linewidth": number; /** Default value: `line` */ "plot 1.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "plot 1.transparency": number; /** Default value: `false` */ "plot 1.trackprice": boolean; /** Default value: `#4CAF50` */ "plot 1.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Moving Average' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MovingAverageIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; /** Default value: `0` */ "smoothed ma.display": number; /** Default value: `0` */ "smoothed ma.linestyle": number; /** Default value: `1` */ "smoothed ma.linewidth": number; /** Default value: `line` */ "smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "smoothed ma.trackprice": boolean; /** Default value: `0` */ "smoothed ma.transparency": number; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Moving Average Multiple' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MovingAverageMultipleIndicatorOverrides { /** Default value: `15` */ "plot 1.display": number; /** Default value: `0` */ "plot 1.linestyle": number; /** Default value: `1` */ "plot 1.linewidth": number; /** Default value: `line` */ "plot 1.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "plot 1.transparency": number; /** Default value: `false` */ "plot 1.trackprice": boolean; /** Default value: `#9C27B0` */ "plot 1.color": string; /** Default value: `15` */ "plot 2.display": number; /** Default value: `0` */ "plot 2.linestyle": number; /** Default value: `1` */ "plot 2.linewidth": number; /** Default value: `0` */ "plot 2.transparency": number; /** Default value: `line` */ "plot 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 2.trackprice": boolean; /** Default value: `#FF6D00` */ "plot 2.color": string; /** Default value: `15` */ "plot 3.display": number; /** Default value: `0` */ "plot 3.linestyle": number; /** Default value: `1` */ "plot 3.linewidth": number; /** Default value: `0` */ "plot 3.transparency": number; /** Default value: `line` */ "plot 3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 3.trackprice": boolean; /** Default value: `#43A047` */ "plot 3.color": string; /** Default value: `15` */ "plot 4.display": number; /** Default value: `0` */ "plot 4.linestyle": number; /** Default value: `1` */ "plot 4.linewidth": number; /** Default value: `0` */ "plot 4.transparency": number; /** Default value: `line` */ "plot 4.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 4.trackprice": boolean; /** Default value: `#26C6DA` */ "plot 4.color": string; /** Default value: `15` */ "plot 5.display": number; /** Default value: `0` */ "plot 5.linestyle": number; /** Default value: `1` */ "plot 5.linewidth": number; /** Default value: `0` */ "plot 5.transparency": number; /** Default value: `line` */ "plot 5.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 5.trackprice": boolean; /** Default value: `#F50057` */ "plot 5.color": string; /** Default value: `15` */ "plot 6.display": number; /** Default value: `0` */ "plot 6.linestyle": number; /** Default value: `1` */ "plot 6.linewidth": number; /** Default value: `0` */ "plot 6.transparency": number; /** Default value: `line` */ "plot 6.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 6.trackprice": boolean; /** Default value: `#2196F3` */ "plot 6.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Moving Average Triple' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MovingAverageTripleIndicatorOverrides { /** Default value: `15` */ "plot 1.display": number; /** Default value: `0` */ "plot 1.linestyle": number; /** Default value: `1` */ "plot 1.linewidth": number; /** Default value: `line` */ "plot 1.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "plot 1.transparency": number; /** Default value: `false` */ "plot 1.trackprice": boolean; /** Default value: `#FF6D00` */ "plot 1.color": string; /** Default value: `15` */ "plot 2.display": number; /** Default value: `0` */ "plot 2.linestyle": number; /** Default value: `1` */ "plot 2.linewidth": number; /** Default value: `0` */ "plot 2.transparency": number; /** Default value: `line` */ "plot 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 2.trackprice": boolean; /** Default value: `#2196F3` */ "plot 2.color": string; /** Default value: `15` */ "plot 3.display": number; /** Default value: `0` */ "plot 3.linestyle": number; /** Default value: `1` */ "plot 3.linewidth": number; /** Default value: `0` */ "plot 3.transparency": number; /** Default value: `line` */ "plot 3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 3.trackprice": boolean; /** Default value: `#26C6DA` */ "plot 3.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Moving Average Weighted' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface MovingAverageWeightedIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } export interface NegativeBaseInputFieldValidatorResult extends BaseInputFieldValidatorResult { /** @inheritDoc */ valid: false; /** Reason why base input value is invalid */ errorMessage: string; } /** * Overrides for the 'Net Volume' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface NetVolumeIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } export interface NewsItem { /** News item title. */ title: string; /** Provider of the news item */ provider: NewsProvider; /** Published date */ published: number; /** Link to the news item. This link is opened in a pop-up dialog when a user clicks on the corresponding news item. If `link` is not provided, the information from the {@link fullDescription} property is displayed instead. */ link?: string; /** Short description */ shortDescription?: string; /** Full description */ fullDescription?: string; } export interface NewsProvider { /** Unique ID of the news provider */ id: string; /** Name of the news provider */ name: string; /** Provider-related logo ID. It is used to generate a link to the provider’s logo */ logo_id?: string; url?: string; } /** * Number format options */ export interface NumberFormatterFormatOptions extends FormatterFormatOptions { /** * Disable exponential form */ noExponentialForm?: boolean; } /** * Formatting options for numbers */ export interface NumericFormattingParams { /** * String that represents the decimal part of a number. * This character separates the integer part from the fractional part. * @example "123.4" // Using a dot as the decimal sign * @example "123,4" // Using a comma as the decimal sign * @example "123'4" // Using an apostrophe as the decimal sign */ decimal_sign: string; /** * String that represents the grouping separator for large numbers. * This character separates groups of thousands to improve readability. * @example "1 234.5" // Using a space as the grouping separator * @example "1,234.5" // Using a comma as the grouping separator */ grouping_separator: string; } /** * Overrides for the 'On Balance Volume' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface OnBalanceVolumeIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; /** Default value: `0` */ "smoothed ma.display": number; /** Default value: `0` */ "smoothed ma.linestyle": number; /** Default value: `1` */ "smoothed ma.linewidth": number; /** Default value: `line` */ "smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "smoothed ma.trackprice": boolean; /** Default value: `0` */ "smoothed ma.transparency": number; [key: string]: StudyOverrideValueType; } /** * Interface for an URL which will be opened */ export interface OpenUrlSolution { /** * Link to be opened */ openUrl: { /** URL to be opened */ url: string; /** text for solution button */ text: string; }; } export interface OrderDialogOptions extends TradingDialogOptions { /** * Using this flag, you can change `Trade Value` to `Total` in the *Order Info* section of the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket). */ showTotal?: boolean; } export interface OrderDuration { /** * type is OrderDurationMetaInfo.value */ type: string; /** Order duration time */ datetime?: number; } /** * Order duration options that determine how long the order remains active. * Refer to [Enable Time in force menu](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-time-in-force-menu) for more information. */ export interface OrderDurationMetaInfo { /** If it is set to `true`, then the Display date control in Order Ticket for this duration type will be displayed. */ hasDatePicker?: boolean; /** If it is set to `true`, then the Display time control in Order Ticket 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 Order Ticket for the first time. */ default?: boolean; /** Localized title of the duration. The title will be displayed in the Duration control of Order Ticket. */ name: string; /** Duration identifier */ value: string; /** A list of order types for which this duration type will be displayed in the Duration control of Order Ticket. Default value is `[OrderType.Limit, OrderType.Stop, OrderType.StopLimit]`. */ supportedOrderTypes?: OrderType[]; } /** * Override properties for the Order drawing tool. */ export interface OrderLineToolOverrides { /** Default value: `rgba(255, 255, 255, 0.25)` */ "linetoolorder.bodyBackgroundColor": string; /** Default value: `25` */ "linetoolorder.bodyBackgroundTransparency": number; /** Default value: `#4094e8` */ "linetoolorder.bodyBorderActiveBuyColor": string; /** Default value: `#e75656` */ "linetoolorder.bodyBorderActiveSellColor": string; /** Default value: `rgba(64, 148, 232, 0.5)` */ "linetoolorder.bodyBorderInactiveBuyColor": string; /** Default value: `rgba(231, 86, 86, 0.5)` */ "linetoolorder.bodyBorderInactiveSellColor": string; /** Default value: `true` */ "linetoolorder.bodyFontBold": boolean; /** Default value: `Verdana` */ "linetoolorder.bodyFontFamily": string; /** Default value: `false` */ "linetoolorder.bodyFontItalic": boolean; /** Default value: `9` */ "linetoolorder.bodyFontSize": number; /** Default value: `#4094e8` */ "linetoolorder.bodyTextActiveBuyColor": string; /** Default value: `#268c02` */ "linetoolorder.bodyTextActiveLimitColor": string; /** Default value: `#e75656` */ "linetoolorder.bodyTextActiveSellColor": string; /** Default value: `#e75656` */ "linetoolorder.bodyTextActiveStopColor": string; /** Default value: `rgba(64, 148, 232, 0.5)` */ "linetoolorder.bodyTextInactiveBuyColor": string; /** Default value: `rgba(38, 140, 2, 0.5)` */ "linetoolorder.bodyTextInactiveLimitColor": string; /** Default value: `rgba(231, 86, 86, 0.5)` */ "linetoolorder.bodyTextInactiveSellColor": string; /** Default value: `rgba(231, 86, 86, 0.5)` */ "linetoolorder.bodyTextInactiveStopColor": string; /** Default value: `rgba(255, 255, 255, 0.25)` */ "linetoolorder.cancelButtonBackgroundColor": string; /** Default value: `25` */ "linetoolorder.cancelButtonBackgroundTransparency": number; /** Default value: `#4094e8` */ "linetoolorder.cancelButtonBorderActiveBuyColor": string; /** Default value: `#e75656` */ "linetoolorder.cancelButtonBorderActiveSellColor": string; /** Default value: `rgba(64, 148, 232, 0.5)` */ "linetoolorder.cancelButtonBorderInactiveBuyColor": string; /** Default value: `rgba(231, 86, 86, 0.5)` */ "linetoolorder.cancelButtonBorderInactiveSellColor": string; /** Default value: `#4094e8` */ "linetoolorder.cancelButtonIconActiveBuyColor": string; /** Default value: `#e75656` */ "linetoolorder.cancelButtonIconActiveSellColor": string; /** Default value: `rgba(64, 148, 232, 0.5)` */ "linetoolorder.cancelButtonIconInactiveBuyColor": string; /** Default value: `rgba(231, 86, 86, 0.5)` */ "linetoolorder.cancelButtonIconInactiveSellColor": string; /** Default value: `undefined` */ "linetoolorder.cancelTooltip": string; /** Default value: `inherit` */ "linetoolorder.extendLeft": string; /** Default value: `#4094e8` */ "linetoolorder.lineActiveBuyColor": string; /** Default value: `#e75656` */ "linetoolorder.lineActiveSellColor": string; /** Default value: `#FF0000` */ "linetoolorder.lineColor": string; /** Default value: `rgba(64, 148, 232, 0.5)` */ "linetoolorder.lineInactiveBuyColor": string; /** Default value: `rgba(231, 86, 86, 0.5)` */ "linetoolorder.lineInactiveSellColor": string; /** Default value: `inherit` */ "linetoolorder.lineLength": string; /** Default value: `percentage` */ "linetoolorder.lineLengthUnit": string; /** Default value: `inherit` */ "linetoolorder.lineStyle": string; /** Default value: `inherit` */ "linetoolorder.lineWidth": string; /** Default value: `undefined` */ "linetoolorder.modifyTooltip": string; /** Default value: `#4094e8` */ "linetoolorder.quantityBackgroundActiveBuyColor": string; /** Default value: `#e75656` */ "linetoolorder.quantityBackgroundActiveSellColor": string; /** Default value: `rgba(64, 148, 232, 0.5)` */ "linetoolorder.quantityBackgroundInactiveBuyColor": string; /** Default value: `rgba(231, 86, 86, 0.5)` */ "linetoolorder.quantityBackgroundInactiveSellColor": string; /** Default value: `#4094e8` */ "linetoolorder.quantityBorderActiveBuyColor": string; /** Default value: `#e75656` */ "linetoolorder.quantityBorderActiveSellColor": string; /** Default value: `rgba(64, 148, 232, 0.5)` */ "linetoolorder.quantityBorderInactiveBuyColor": string; /** Default value: `rgba(231, 86, 86, 0.5)` */ "linetoolorder.quantityBorderInactiveSellColor": string; /** Default value: `true` */ "linetoolorder.quantityFontBold": boolean; /** Default value: `Verdana` */ "linetoolorder.quantityFontFamily": string; /** Default value: `false` */ "linetoolorder.quantityFontItalic": boolean; /** Default value: `9` */ "linetoolorder.quantityFontSize": number; /** Default value: `#ffffff` */ "linetoolorder.quantityTextColor": string; /** Default value: `0` */ "linetoolorder.quantityTextTransparency": number; /** Default value: `undefined` */ "linetoolorder.tooltip": string; } 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?: OrderPreviewMessage[]; /** Error messages */ errors?: OrderPreviewMessage[]; } /** * 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 information is not sufficient to place an order. */ export interface OrderTemplate extends OrderTemplateBase { } export interface OrderTemplateBase { /** Symbol identifier */ symbol: string; /** Order Type */ type?: OrderType; /** order / execution side */ side?: Side; /** Order quantity */ qty?: number; /** Type of Stop Order */ stopType?: StopType; /** Current Quotes */ currentQuotes?: AskBid; /** Order stop price */ stopPrice?: number; /** Order limit price */ limitPrice?: number; /** Order Take Profit (Brackets) */ takeProfit?: number; /** Order Stop loss (Brackets) */ stopLoss?: number; /** Order Guaranteed Stop loss (Brackets) */ guaranteedStop?: number; /** Order Trailing stop (Brackets) */ trailingStopPips?: number; /** Duration or expiration of an order */ duration?: OrderDuration; /** Custom input fields */ customFields?: CustomInputFieldsValues; } /** * Settings for the ellipsis menu of the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket). You can read and adjust these settings using the * {@link IBrokerConnectionAdapterHost.getOrderTicketSetting} and * {@link IBrokerConnectionAdapterHost.setOrderTicketSetting} methods. */ export interface OrderTicketSettings { /** If true, the "Show Order Price in Ticks" setting is displayed. */ showRelativePriceControl: boolean; /** If true, the "Show order confirmations" setting is displayed. */ showOrderPreview: boolean; } export interface OverlayIndicatorOverrides { /** * The style type for _Overlay_ can be any of the following. * Default value: 2 (`line`) * * For each style, there are additional properties that you can customize. Refer to the links in the _OverlayIndicatorOverrides_ column to see the lists of properties. * * | ChartStyle name | ChartStyle # | OverlayIndicatorOverrides | * | :--------------- | :---------- | :------------------ | * | Bar | 0 | {@link OverlayIndicatorOverridesBar} | * | Candle | 1 | {@link OverlayIndicatorOverridesCandle} | * | Line | 2 | {@link OverlayIndicatorOverridesLine} | * | Area | 3 | {@link OverlayIndicatorOverridesArea} | * | HollowCandle | 4 | {@link OverlayIndicatorOverridesHollowCandle} | * | Baseline | 5 | {@link OverlayIndicatorOverridesBaseline} | * | HiLo | 6 | {@link OverlayIndicatorOverridesHiLo} | * | Column | 7 | {@link OverlayIndicatorOverridesColumn} | * | HLCArea | 8 | {@link OverlayIndicatorOverridesHLCArea} | * | LineWithMarkers | 14 | {@link OverlayIndicatorOverridesLineWithMarkers} | * | Stepline | 15 | {@link OverlayIndicatorOverridesStepline} | * */ style: Exclude; /** * Price line visibility. * Default value: `false` */ showPriceLine: boolean; /** * Enables the _Overlay_ to extend the time scale. * Default value: `false` */ allowExtendTimeScale: boolean; /** * [`minTick`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesmintick) * Default value: `default` */ minTick: string; } export interface OverlayIndicatorOverridesArea extends Partial { style: ChartStyle.Area; /** * Use the properties as follow: `areaStyle.color1`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface OverlayIndicatorOverridesBar extends Partial { style: ChartStyle.Bar; /** * Use the properties as follow: `barStyle.downColor`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface OverlayIndicatorOverridesBaseline extends Partial { style: ChartStyle.Baseline; /** * Use the properties as follow: `baselineStyle.baselineColor`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface OverlayIndicatorOverridesCandle extends Partial { style: ChartStyle.Candle; /** * Use the properties as follow: `candleStyle.downColor`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface OverlayIndicatorOverridesColumn extends Partial { style: ChartStyle.Column; /** * Use the properties as follow: `columnStyle.downColor`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface OverlayIndicatorOverridesHLCArea extends Partial { style: ChartStyle.HLCArea; /** * Use the properties as follow: `hlcAreaStyle.highLineColor`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface OverlayIndicatorOverridesHiLo extends Partial { style: ChartStyle.HiLo; /** * Use the properties as follow: `hiloStyle.color`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface OverlayIndicatorOverridesHollowCandle extends Partial { style: ChartStyle.HollowCandle; /** * Use the properties as follow: `hollowCandleStyle.downColor`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface OverlayIndicatorOverridesLine extends Partial { style: ChartStyle.Line; /** * Use the properties as follow: `lineStyle.color`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface OverlayIndicatorOverridesLineWithMarkers extends Partial { style: ChartStyle.LineWithMarkers; /** * Use the properties as follow: `lineWithMarkerStyle.color`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface OverlayIndicatorOverridesStepline extends Partial { style: ChartStyle.Stepline; /** * Use the properties as follow: `steplineStyle.color`: `pink` */ [key: string]: StudyOverrideValueType | undefined; } export interface Overrides { [key: string]: string | number | boolean; } /** * Overrides for the 'Parabolic SAR' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ParabolicSARIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `cross` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Override properties for the Parallelchannel drawing tool. */ export interface ParallelchannelLineToolOverrides { /** Default value: `rgba(41, 98, 255, 0.2)` */ "linetoolparallelchannel.backgroundColor": string; /** Default value: `false` */ "linetoolparallelchannel.extendLeft": boolean; /** Default value: `false` */ "linetoolparallelchannel.extendRight": boolean; /** Default value: `true` */ "linetoolparallelchannel.fillBackground": boolean; /** Default value: `false` */ "linetoolparallelchannel.labelBold": boolean; /** Default value: `14` */ "linetoolparallelchannel.labelFontSize": number; /** Default value: `left` */ "linetoolparallelchannel.labelHorzAlign": string; /** Default value: `false` */ "linetoolparallelchannel.labelItalic": boolean; /** Default value: `#2962FF` */ "linetoolparallelchannel.labelTextColor": string; /** Default value: `bottom` */ "linetoolparallelchannel.labelVertAlign": string; /** Default value: `false` */ "linetoolparallelchannel.labelVisible": boolean; /** Default value: `#2962FF` */ "linetoolparallelchannel.linecolor": string; /** Default value: `0` */ "linetoolparallelchannel.linestyle": number; /** Default value: `2` */ "linetoolparallelchannel.linewidth": number; /** Default value: `#2962FF` */ "linetoolparallelchannel.midlinecolor": string; /** Default value: `2` */ "linetoolparallelchannel.midlinestyle": number; /** Default value: `1` */ "linetoolparallelchannel.midlinewidth": number; /** Default value: `true` */ "linetoolparallelchannel.showMidline": boolean; /** Default value: `20` */ "linetoolparallelchannel.transparency": number; } /** * Override properties for the Path drawing tool. */ export interface PathLineToolOverrides { /** Default value: `0` */ "linetoolpath.leftEnd": number; /** Default value: `#2962FF` */ "linetoolpath.lineColor": string; /** Default value: `0` */ "linetoolpath.lineStyle": number; /** Default value: `2` */ "linetoolpath.lineWidth": number; /** Default value: `1` */ "linetoolpath.rightEnd": number; } /** * 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 { /** Standard library functions for PineJS */ Std: PineJSStd; } /** * PineJS standard library functions. */ export interface PineJSStd { /** * Default maximum size of a pine series. */ max_series_default_size: 10001; /** * Epsilon (machine precision) * * @returns Epsilon (machine precision). Upper bound on the relative approximation error due to rounding in floating point arithmetic. */ eps(): number; /** * High Price * * @param context - PineJS execution context. * @returns Current high price. */ high(context: IContext): number; /** * Low Price * * @param context - PineJS execution context. * @returns Current low price. */ low(context: IContext): number; /** * Open Price * * @param context - PineJS execution context. * @returns Current open price. */ open(context: IContext): number; /** * Close Price * * @param context - PineJS execution context. * @returns Current close price. */ close(context: IContext): number; /** * Is a shortcut for (open + high + low + close)/4 * * @param context - PineJS execution context. * @returns Calculated average of the current OHLC values */ ohlc4(context: IContext): number; /** * Current bar volume * * @param context - PineJS execution context. * @returns Current bar volume */ volume(context: IContext): number; /** * Current bar time * * @param context - PineJS execution context. * @returns UNIX time of current bar according to the symbol timezone and not UTC. */ time(context: IContext): number; /** * Current bar time * * @param context - PineJS execution context. * @param period - Period * @returns UNIX time of current bar according to the symbol timezone and not UTC. */ time(context: IContext, period: string): number; /** * Is a shortcut for (high + low)/2 * * @param context - PineJS execution context. * @returns Calculated average of the current HL values */ hl2(context: IContext): number; /** * Is a shortcut for (high + low + close)/3 * * @param context - PineJS execution context. * @returns Calculated average of the current HLC values */ hlc3(context: IContext): number; /** * Resolution string, e.g. 60 - 60 minutes, D - daily, W - weekly, M - monthly, 5D - 5 days, 12M - one year, 3M - one quarter * * @param context - PineJS execution context. * @returns The resolution string for the current context */ period(context: IContext): ResolutionString; /** * Ticker ID * * @param context - PineJS execution context. * @returns Ticker ID for the current symbol */ tickerid(context: IContext): string; /** * Year of current bar time in exchange timezone. * * @param context - PineJS execution context. * @param time optional time. Current bar time will be used by default. * @returns Current bar year in exchange timezone. */ year(context: IContext, time?: number): number; /** * Month of current bar time in exchange timezone. * * @param context - PineJS execution context. * @param time optional time. Current bar time will be used by default. * @returns Current bar month in exchange timezone. */ month(context: IContext, time?: number): number; /** * Week number of current bar time in exchange timezone. * * @param context - PineJS execution context. * @param time optional time. Current bar time will be used by default. * @returns Week number of current bar in exchange timezone. */ weekofyear(context: IContext, time?: number): number; /** * Day of month for current bar time in exchange timezone. * * @param context - PineJS execution context. * @param time optional time. Current bar time will be used by default. * @returns Day of month for current bar time in exchange timezone. */ dayofmonth(context: IContext, time?: number): number; /** * Day of week for current bar time in exchange timezone. * * @param context - PineJS execution context. * @param time optional time. Current bar time will be used by default. * @returns Day of week for current bar time in exchange timezone. */ dayofweek(context: IContext, time?: number): number; /** * Hour of current bar time in exchange timezone. * * @param context - PineJS execution context. * @param time optional time. Current bar time will be used by default. * @returns Current bar hour in exchange timezone. */ hour(context: IContext, time?: number): number; /** * Minute of current bar time in exchange timezone. * * @param context - PineJS execution context. * @param time optional time. Current bar time will be used by default. * @returns Current bar minute in exchange timezone. */ minute(context: IContext, time?: number): number; /** * Second of current bar time in exchange timezone. * * @param context - PineJS execution context. * @param time optional time. Current bar time will be used by default. * @returns Current bar second in exchange timezone. */ second(context: IContext, time?: number): number; /** * Checks if `n1` is greater than or equal to `n2` * * @param n1 * @param n2 * @param eps - Epsilon (Optional). * @returns True if `n1` is greater than or equal to `n2`. */ greaterOrEqual(n1: number, n2: number, eps?: number): boolean; /** * Checks if `n1` is less than or equal to `n2` * * @param n1 * @param n2 * @param eps - Epsilon (Optional). * @returns True if `n1` is less than or equal to `n2`. */ lessOrEqual(n1: number, n2: number, eps?: number): boolean; /** * Checks if `n1` is equal to `n2` (within the accuracy of epsilon). * * @param n1 * @param n2 * @param eps - Epsilon (Optional). * @returns True if `n1` is equal to `n2`. */ equal(n1: number, n2: number, eps?: number): boolean; /** * Checks if `n1` is greater than `n2` * * @param n1 * @param n2 * @param eps - Epsilon (Optional). * @returns True if `n1` is greater than `n2`. */ greater(n1: number, n2: number, eps?: number): boolean; /** * Checks if `n1` is less than `n2` * * @param n1 * @param n2 * @param eps - Epsilon (Optional). * @returns True if `n1` is less than `n2`. */ less(n1: number, n2: number, eps?: number): boolean; /** * Compare the values of `n1` and `n2` * * @param n1 * @param n2 * @param eps - Epsilon (Optional). * @returns `0` if values are equal. `1` if x1 is greater than x2. `-1` if x1 is less than x2 */ compare(n1: number, n2: number, eps?: number): -1 | 0 | 1; /** * Checks if `n1` is greater than or equal to `n2` * * @param n1 * @param n2 * @returns `1` if `n1` is greater than or equal to `n2`, `0` otherwise. */ ge(n1: number, n2: number): number; /** * Checks if `n1` is less than or equal to `n2` * * @param n1 * @param n2 * @returns `1` if `n1` is greater than or equal to `n2`, `0` otherwise. */ le(n1: number, n2: number): number; /** * Checks if `n1` is equal to `n2`. * * @param n1 * @param n2 * @returns `1` if `n1` is equal to `n2`, `0` otherwise. */ eq(n1: number, n2: number): number; /** * Checks if `n1` is not equal to `n2`. * * @param n1 * @param n2 * @returns `1` if `n1` is not equal to `n2`, `0` otherwise. */ neq(n1: number, n2: number): number; /** * Checks if `n1` is greater than `n2` * * @param n1 * @param n2 * @returns `1` if `n1` is greater than `n2`, `0` otherwise. */ gt(n1: number, n2: number): number; /** * Checks if `n1` is less than `n2` * * @param n1 * @param n2 * @returns `1` if `n1` is less than `n2`, `0` otherwise. */ lt(n1: number, n2: number): number; /** * If ... then ... else ... * `iff` does exactly the same thing as ternary conditional operator `?:` but in a functional style. Also `iff` is slightly less efficient than operator `?:` * * @param condition - condition to check * @param thenValue - value to use if condition is true * @param elseValue - value to use if condition is false * @returns either thenValue or elseValue */ iff(condition: number, thenValue: number, elseValue: number): number; /** * True Range * * @param n_handleNaN - How NaN values are handled. If truthy, and previous bar's close is `NaN` then tr would be calculated as current bar `high-low`. Otherwise tr would return `NaN` in such cases. Also note, that `atr` uses `tr(true)`. * @param ctx - PineJS execution context. * @returns True range. It is `max(high - low, abs(high - close[1]), abs(low - close[1]))` */ tr(n_handleNaN: number | undefined, ctx: IContext): number; /** * Function atr (average true range) returns the RMA of true range. True range is `max(high - low, abs(high - close[1]), abs(low - close[1]))` * * @param length - Length (number of bars back). * @param context - PineJS execution context. * @returns Average true range. */ atr(length: number, context: IContext): number; /** * Determines whether the current resolution is a daily, weekly, or monthly resolution. * * @param context - PineJS execution context. * @returns true if current resolution is a daily or weekly or monthly resolution */ isdwm(context: IContext): boolean; /** * Determines whether the current resolution is an intraday (minutes or seconds) resolution. * * @param context - PineJS execution context. * @returns true if current resolution is an intraday (minutes or seconds) resolution */ isintraday(context: IContext): boolean; /** * Determines whether the current resolution is a daily resolution. * * @param context - PineJS execution context. * @returns true if current resolution is a daily resolution */ isdaily(context: IContext): boolean; /** * Determines whether the current resolution is a weekly resolution. * * @param context - PineJS execution context. * @returns true if current resolution is a weekly resolution */ isweekly(context: IContext): boolean; /** * Determines whether the current resolution is a monthly resolution. * * @param context - PineJS execution context. * @returns true if current resolution is a monthly resolution */ ismonthly(context: IContext): boolean; /** * select session breaks for intraday resolutions only * * @param context - PineJS execution context. * @param times - An array of numbers representing the times to select session breaks from. * @returns session breaks for intraday resolutions only. */ selectSessionBreaks(context: IContext, times: number[]): number[]; /** * checks whether a new session can be created * * @param context - PineJS execution context. * @returns checks whether a new session can be created */ createNewSessionCheck(context: IContext): (time: number) => boolean; /** * Display an error message. * * @param message - message to display for error * @param title - title to display for error */ error(message: string, title?: string): never; /** * Zig-zag pivot points * * @param n_deviation - Deviation * @param n_depth - Depth (integer) * @param context - PineJS execution context. * @returns the zig-zag pivot points */ zigzag(n_deviation: number, n_depth: number, context: IContext): number; /** * Zig-zag pivot points * * @param n_deviation - Deviation * @param n_depth - Depth (integer) * @param context - PineJS execution context. * @returns the zig-zag pivot points (for bars) */ zigzagbars(n_deviation: number, n_depth: number, context: IContext): number; /** * Time of the current update * * @param context - PineJS execution context. * @returns symbol update time */ updatetime(context: IContext): number; /** * Ticker ID for the current symbol * * @param context - PineJS execution context. * @returns Ticker ID for the current symbol */ ticker(context: IContext): string; /** * Percent rank is the percentage of how many previous values were less than or equal to the current value of given series. * * @param source - Series of values to process. * @param length - Number of bars (length). * @returns Percent rank of `source` for `length` bars back. */ percentrank(source: IPineSeries, length: number): number; /** * Test if the series is now rising for length bars long. * * @param series - Series of values to process. * @param length - Number of bars (length). * @returns `true` if current `x` is greater than any previous `x` for length bars back, `false` otherwise. */ rising(series: IPineSeries, length: number): number; /** * Test if the series is now falling for length bars long. * * @param series - Series of values to process. * @param length - Number of bars (length). * @returns `true` if current `x` is less than any previous `x` for length bars back, `false` otherwise. */ falling(series: IPineSeries, length: number): number; /** * Relative strength index. It is calculated based on rma's of upward and downward change of x. * * @param upper - upward change * @param lower - downward change * @returns Relative strength index. */ rsi(upper: number, lower: number): number; /** * The sum function returns the sliding sum of last y values of x. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Sum of x for y bars back. */ sum(source: IPineSeries, length: number, context: IContext): number; /** * Simple Moving Average. The sum of last `length` values of `source`, divided by `length`. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Simple moving average of x for y bars back. */ sma(source: IPineSeries, length: number, context: IContext): number; /** * Smoothed Moving Average. * * @param n_value Next value in the series to calculate. * @param n_length Smoothing length. * @param ctx PineJS execution context. * @returns The smoothed moving average value. */ smma(n_value: number, n_length: number, ctx: IContext): number; /** * Moving average used in RSI. It is the exponentially weighted moving average with `alpha = 1 / length`. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Exponential moving average of `x` with `alpha = 1 / y`. */ rma(source: IPineSeries, length: number, context: IContext): number; /** * Exponential Moving Average. In EMA weighting factors decrease exponentially. * * It calculates by using a formula: `EMA = alpha * x + (1 - alpha) * EMA[1]`, where `alpha = 2 / (y + 1)`. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Exponential moving average of `x` with `alpha = 2 / (y + 1)` */ ema(source: IPineSeries, length: number, context: IContext): number; /** * The wma function returns weighted moving average of `source` for `length` bars back. In wma weighting factors decrease in arithmetical progression. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Weighted moving average of `series` for `length` bars back. */ wma(source: IPineSeries, length: number, context: IContext): number; /** * The vwma function returns volume-weighted moving average of `source` for `length` bars back. It is the same as: `sma(x * volume, y) / sma(volume, y)` * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Volume-weighted moving average of `source` for `length` bars back. */ vwma(source: IPineSeries, length: number, context: IContext): number; /** * Symmetrically weighted moving average with fixed length: 4. Weights: `[1/6, 2/6, 2/6, 1/6]`. * * @param source - Series of values to process. * @param context - PineJS execution context. * @returns Symmetrically weighted moving average */ swma(source: IPineSeries, context: IContext): number; /** * For a given series replaces NaN values with previous nearest non-NaN value. * * @param n_current - Series of values to process. * @param context - PineJS execution context. * @returns Series without na gaps. */ fixnan(n_current: number, context: IContext): number; /** * Lowest value offset for a given number of bars back. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Offset to the lowest bar. */ lowestbars(source: IPineSeries, length: number, context: IContext): number; /** * Lowest value for a given number of bars back. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Lowest value. */ lowest(source: IPineSeries, length: number, context: IContext): number; /** * Highest value offset for a given number of bars back. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Offset to the highest bar. */ highestbars(source: IPineSeries, length: number, context: IContext): number; /** * Highest value for a given number of bars back. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Highest value. */ highest(source: IPineSeries, length: number, context: IContext): number; /** * Cumulative (total) sum. The function tracks the previous values internally. * * @param n_value Value to add to the sum. * @param context PineJS execution context. * @returns The sum. */ cum(n_value: number, context: IContext): number; /** * Accumulation/distribution index. * * @param context - PineJS execution context. * @returns Accumulation/distribution index. */ accdist(context: IContext): number; /** * Correlation coefficient. Describes the degree to which two series tend to deviate from their `sma` values. * * @param sourceA - Source series. * @param sourceB - Target series. * @param length - Length (number of bars back). * @param context - PineJS execution context. * @returns Correlation coefficient. */ correlation(sourceA: IPineSeries, sourceB: IPineSeries, length: number, context: IContext): number; /** * Stochastic. It is calculated by a formula: `100 * (close - lowest(low, length)) / (highest(high, length) - lowest(low, length))` * * @param source - Source series. * @param high - Series of high. * @param low - Series of low. * @param length - Length (number of bars back). * @param context - PineJS execution context. * @returns Stochastic value. */ stoch(source: IPineSeries, high: IPineSeries, low: IPineSeries, length: number, context: IContext): number; /** * True strength index. It uses moving averages of the underlying momentum of a financial instrument. * * @param source - Source series. * @param shortLength - Length (number of bars back). * @param longLength - Length (number of bars back). * @param context - PineJS execution context. * @returns True strength index. A value in range `[-1, 1]` */ tsi(source: IPineSeries, shortLength: number, longLength: number, context: IContext): number; /** * Crossing of series. * * @param n_0 - First value. * @param n_1 - Second value. * @param context - PineJS execution context. * @returns `true` if two series have crossed each other, otherwise `false`. */ cross(n_0: number, n_1: number, context: IContext): boolean; /** * Linear regression curve. A line that best fits the prices specified over a user-defined time period. * It is calculated using the least squares method. The result of this function is calculated using the formula: * `linreg = intercept + slope * (length - 1 - offset)`, where intercept and slope are the values calculated with * the least squares method on source series (x argument). * * @param source - Source series. * @param length - Length (number of bars back). * @param offset - Offset (number of bars) * @returns Linear regression curve point. */ linreg(source: IPineSeries, length: number, offset: number): number; /** * Parabolic SAR (parabolic stop and reverse) is a method devised by J. Welles Wilder, Jr., to find potential reversals in the market price direction of traded goods. * * @param start - Start. * @param inc - Increment. * @param max - Maximum. * @param context - PineJS execution context. * @returns Parabolic SAR value. */ sar(start: number, inc: number, max: number, context: IContext): number; /** * Arnaud Legoux Moving Average. It uses Gaussian distribution as weights for moving average. * * @param series - Series of values to process. * @param length - Number of bars (length). * @param offset - Controls tradeoff between smoothness (closer to 1) and responsiveness (closer to 0). * @param sigma - Changes the smoothness of ALMA. The larger sigma the smoother ALMA. */ alma(series: IPineSeries, length: number, offset: number, sigma: number): number; /** * Difference between current value and previous, `x - x[1]`. * * @param source - Series to process. * @returns The result of subtraction. */ change(source: IPineSeries): number; /** * Rate of Change. * * Function roc (rate of change) showing the difference between current value of `source` and the value of `source` that was `length` days ago. It is calculated by the formula: `100 * change(src, length) / src[length]`. * * @param source - Series of values to process. * @param length - Number of bars (length). * @returns The rate of change of `source` for `length` bars back. */ roc(source: IPineSeries, length: number): number; /** * Measure of difference between the series and its sma. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Deviation of source for length bars back. */ dev(source: IPineSeries, length: number, context: IContext): number; /** * Standard deviation. Note: This is a biased estimation of standard deviation. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Standard deviation. */ stdev(source: IPineSeries, length: number, context: IContext): number; /** * Variance is the expectation of the squared deviation of a series from its mean `sma`, and it informally measures how far a set of numbers are spread out from their mean. Note: This is a biased estimation of sample variance. * * @param source - Series of values to process. * @param length - Number of bars (length). * @param context - PineJS execution context. * @returns Variance of `source` for `length` bars back. */ variance(source: IPineSeries, length: number, context: IContext): number; /** * Get time in `daysCount` number of days while taking Daylight savings time into account. * * @param timezone - Timezone * @param utcTime - Date (JS built-in) * @param daysCount - Number of days * @returns The time is `daysCount` number of days, taking into account Daylight savings time. */ add_days_considering_dst(timezone: string, utcTime: Date, daysCount: number): Date; /** * Get time in `yearsCount` number of years while taking Daylight savings time into account. * * @param timezone - Timezone * @param utcTime - Date (JS built-in) * @param yearsCount - Number of years * @returns The time is `yearsCount` number of years, taking into account Daylight savings time. */ add_years_considering_dst(timezone: string, utcTime: Date, yearsCount: number): Date; /** * Calculates the directional movement values +DI, -DI, DX, ADX, and ADXR. * * @param diLength - Number of bars (length) used when calculating the +DI and -DI values. * @param adxSmoothingLength - Number of bars (length) used when calculating the ADX value. * @param context - PineJS execution context. * @returns An array of the +DI, -DI, DX, ADX, and ADXR values with diLength smoothing for the (+/-)DI values and adxSmoothingLength for the ADX value. */ dmi(diLength: number, adxSmoothingLength: number, context: IContext): [ number, number, number, number, number ]; /** * Test value if it's a NaN. * * @param n - value to test * @returns `1` if `n` is not a valid number (`n` is `NaN`), otherwise `0`. Returns `NaN` if `n` is undefined. */ na(n?: number): number; /** * Replaces NaN values with zeros (or given value) in a series. * * @param x - value to test (and potentially replace) * @param y - fallback value. `0` by default. * @returns `x` if it's a valid (not NaN) number, otherwise `y` */ nz(x: number, y?: number): number; /** * Logical AND. * * @returns `1` if both values are truthy, `0` otherwise. */ and(n_0: number, n_1: number): number; /** * Logical OR. * * @returns `1` if either value is truthy, `0` otherwise. */ or(n_0: number, n_1: number): number; /** * Logical negation (NOT). * * @returns `1` if value is falsy, `0` if value is truthy. */ not(n_0: number): number; /** * Maximum number in the array * * @returns The greatest of multiple given values */ max(...values: number[]): number; /** * Minimum number in the array * * @returns The smallest of multiple given values */ min(...values: number[]): number; /** * Mathematical power function. * * @param base - Specify the base to use. * @param exponent - Specifies the exponent. * @returns `x` raised to the power of `y`. */ pow(base: number, exponent: number): number; /** * Absolute value of x is x if x >= 0, or -x otherwise. * * @returns The absolute value of `x` */ abs(x: number): number; /** * Natural logarithm of any `x > 0` is the unique `y` such that `e^y = x` * * @returns The natural logarithm of `x`. */ log(x: number): number; /** * Base 10 logarithm of any `x > 0` is the unique `y` such that `10^y = x` * * @returns The base 10 logarithm of `x`. */ log10(x: number): number; /** * Square root of any `x >= 0` is the unique `y >= 0` such that `y^2 = x` * * @returns The square root of `x` */ sqrt(x: number): number; /** * Sign (signum) of `x` is `0` if the x is zero, `1.0` if the `x` is greater than zero, `-1.0` if the `x` is less than zero. * * @returns The sign of `x` */ sign(x: number): number; /** * The exp function of `x` is `e^x`, where `x` is the argument and `e` is Euler's number. * * @returns A number representing `e^x`. */ exp(x: number): number; /** * The sin function returns the trigonometric sine of an angle. * * @param x - Angle, in radians. * @returns The trigonometric sine of an angle. */ sin(x: number): number; /** * The cos function returns the trigonometric cosine of an angle. * * @param x - Angle, in radians. * @returns The trigonometric cosine of an angle. */ cos(x: number): number; /** * The tan function returns the trigonometric tangent of an angle. * * @param x - Angle, in radians. * @returns The trigonometric tangent of an angle. */ tan(x: number): number; /** * The asin function returns the arcsine (in radians) of number such that `sin(asin(y)) = y` for `y` in range `[-1, 1]`. * * @param x - Angle, in radians. * @returns The arcsine of a value; the returned angle is in the range `[-Pi/2, Pi/2]`, or na if y is outside of range `[-1, 1]`. */ asin(x: number): number; /** * The acos function returns the arccosine (in radians) of number such that `cos(acos(y)) = y` for `y` in range `[-1, 1]`. * * @param x - Angle, in radians. * @returns The arc cosine of a value; the returned angle is in the range `[0, Pi]`, or na if y is outside of range `[-1, 1]`. */ acos(x: number): number; /** * The atan function returns the arctangent (in radians) of number such that `tan(atan(y)) = y` for any `y`. * * @param x - Angle, in radians. * @returns The arc tangent of a value; the returned angle is in the range `[-Pi/2, Pi/2]`. */ atan(x: number): number; /** * Round the number down to the closest integer * * @returns The largest integer less than or equal to the given number. */ floor(x: number): number; /** * The ceil function returns the smallest (closest to negative infinity) integer that is greater than or equal to the argument. * * @returns The smallest integer greater than or equal to the given number. */ ceil(x: number): number; /** * Round the number to the nearest integer * * @returns The value of `x` rounded to the nearest integer, with ties rounding up. If the precision parameter is used, returns a float value rounded to that number of decimal places. */ round(x: number): number; /** * Calculates average of all given series (elementwise). * * @returns the average of the values */ avg(...values: number[]): number; /** * Current bar index * * @param context - PineJS execution context. * @returns Current bar index. Numbering is zero-based, index of the first historical bar is 0. */ n(context: IContext): number; /** * Check if a value is zero. * * @param v the value to test. * @returns `true` if the value is zero, `false` otherwise. */ isZero: (v: number) => number; /** * Convert a number to a boolean. * * @param v the value to convert. * @returns `true` if the number is finite and non-zero, `false` otherwise. */ toBool(v: number): boolean; /** * Get the symbol currency code. * * @param ctx PineJS execution context. * @returns Symbol currency code. */ currencyCode(ctx: IContext): string | null | undefined; /** * Get the symbol unit ID. * * @param ctx PineJS execution context. * @returns Symbol unit ID. */ unitId(ctx: IContext): string | null | undefined; /** * Get the symbol interval. For example: if the symbol has a resolution of `1D` then this function would return `1`. * * @param ctx PineJS execution context. * @returns Symbol interval. */ interval(ctx: IContext): number; } export interface PineStudyResultComposite { /** Type is composite */ type: "composite"; /** Composite data */ data: TPineStudyResultSimple[]; } export interface PipValues { /** The value of one pip for buy orders, expressed in account currency. */ buyPipValue: number; /** The value of one pip for sell orders, expressed in account currency. */ sellPipValue: number; } /** * Override properties for the Pitchfan drawing tool. */ export interface PitchfanLineToolOverrides { /** Default value: `true` */ "linetoolpitchfan.fillBackground": boolean; /** Default value: `0.25` */ "linetoolpitchfan.level0.coeff": number; /** Default value: `#ffb74d` */ "linetoolpitchfan.level0.color": string; /** Default value: `0` */ "linetoolpitchfan.level0.linestyle": number; /** Default value: `2` */ "linetoolpitchfan.level0.linewidth": number; /** Default value: `false` */ "linetoolpitchfan.level0.visible": boolean; /** Default value: `0.382` */ "linetoolpitchfan.level1.coeff": number; /** Default value: `#81c784` */ "linetoolpitchfan.level1.color": string; /** Default value: `0` */ "linetoolpitchfan.level1.linestyle": number; /** Default value: `2` */ "linetoolpitchfan.level1.linewidth": number; /** Default value: `false` */ "linetoolpitchfan.level1.visible": boolean; /** Default value: `0.5` */ "linetoolpitchfan.level2.coeff": number; /** Default value: `#00bcd4` */ "linetoolpitchfan.level2.color": string; /** Default value: `0` */ "linetoolpitchfan.level2.linestyle": number; /** Default value: `2` */ "linetoolpitchfan.level2.linewidth": number; /** Default value: `true` */ "linetoolpitchfan.level2.visible": boolean; /** Default value: `0.618` */ "linetoolpitchfan.level3.coeff": number; /** Default value: `#089981` */ "linetoolpitchfan.level3.color": string; /** Default value: `0` */ "linetoolpitchfan.level3.linestyle": number; /** Default value: `2` */ "linetoolpitchfan.level3.linewidth": number; /** Default value: `false` */ "linetoolpitchfan.level3.visible": boolean; /** Default value: `0.75` */ "linetoolpitchfan.level4.coeff": number; /** Default value: `#00bcd4` */ "linetoolpitchfan.level4.color": string; /** Default value: `0` */ "linetoolpitchfan.level4.linestyle": number; /** Default value: `2` */ "linetoolpitchfan.level4.linewidth": number; /** Default value: `false` */ "linetoolpitchfan.level4.visible": boolean; /** Default value: `1` */ "linetoolpitchfan.level5.coeff": number; /** Default value: `#2962FF` */ "linetoolpitchfan.level5.color": string; /** Default value: `0` */ "linetoolpitchfan.level5.linestyle": number; /** Default value: `2` */ "linetoolpitchfan.level5.linewidth": number; /** Default value: `true` */ "linetoolpitchfan.level5.visible": boolean; /** Default value: `1.5` */ "linetoolpitchfan.level6.coeff": number; /** Default value: `#9c27b0` */ "linetoolpitchfan.level6.color": string; /** Default value: `0` */ "linetoolpitchfan.level6.linestyle": number; /** Default value: `2` */ "linetoolpitchfan.level6.linewidth": number; /** Default value: `false` */ "linetoolpitchfan.level6.visible": boolean; /** Default value: `1.75` */ "linetoolpitchfan.level7.coeff": number; /** Default value: `#e91e63` */ "linetoolpitchfan.level7.color": string; /** Default value: `0` */ "linetoolpitchfan.level7.linestyle": number; /** Default value: `2` */ "linetoolpitchfan.level7.linewidth": number; /** Default value: `false` */ "linetoolpitchfan.level7.visible": boolean; /** Default value: `2` */ "linetoolpitchfan.level8.coeff": number; /** Default value: `#F77C80` */ "linetoolpitchfan.level8.color": string; /** Default value: `0` */ "linetoolpitchfan.level8.linestyle": number; /** Default value: `2` */ "linetoolpitchfan.level8.linewidth": number; /** Default value: `false` */ "linetoolpitchfan.level8.visible": boolean; /** Default value: `#F23645` */ "linetoolpitchfan.median.color": string; /** Default value: `0` */ "linetoolpitchfan.median.linestyle": number; /** Default value: `2` */ "linetoolpitchfan.median.linewidth": number; /** Default value: `true` */ "linetoolpitchfan.median.visible": boolean; /** Default value: `80` */ "linetoolpitchfan.transparency": number; } /** * Override properties for the Pitchfork drawing tool. */ export interface PitchforkLineToolOverrides { /** Default value: `false` */ "linetoolpitchfork.extendLines": boolean; /** Default value: `true` */ "linetoolpitchfork.fillBackground": boolean; /** Default value: `0.25` */ "linetoolpitchfork.level0.coeff": number; /** Default value: `#ffb74d` */ "linetoolpitchfork.level0.color": string; /** Default value: `0` */ "linetoolpitchfork.level0.linestyle": number; /** Default value: `2` */ "linetoolpitchfork.level0.linewidth": number; /** Default value: `false` */ "linetoolpitchfork.level0.visible": boolean; /** Default value: `0.382` */ "linetoolpitchfork.level1.coeff": number; /** Default value: `#81c784` */ "linetoolpitchfork.level1.color": string; /** Default value: `0` */ "linetoolpitchfork.level1.linestyle": number; /** Default value: `2` */ "linetoolpitchfork.level1.linewidth": number; /** Default value: `false` */ "linetoolpitchfork.level1.visible": boolean; /** Default value: `0.5` */ "linetoolpitchfork.level2.coeff": number; /** Default value: `#089981` */ "linetoolpitchfork.level2.color": string; /** Default value: `0` */ "linetoolpitchfork.level2.linestyle": number; /** Default value: `2` */ "linetoolpitchfork.level2.linewidth": number; /** Default value: `true` */ "linetoolpitchfork.level2.visible": boolean; /** Default value: `0.618` */ "linetoolpitchfork.level3.coeff": number; /** Default value: `#089981` */ "linetoolpitchfork.level3.color": string; /** Default value: `0` */ "linetoolpitchfork.level3.linestyle": number; /** Default value: `2` */ "linetoolpitchfork.level3.linewidth": number; /** Default value: `false` */ "linetoolpitchfork.level3.visible": boolean; /** Default value: `0.75` */ "linetoolpitchfork.level4.coeff": number; /** Default value: `#00bcd4` */ "linetoolpitchfork.level4.color": string; /** Default value: `0` */ "linetoolpitchfork.level4.linestyle": number; /** Default value: `2` */ "linetoolpitchfork.level4.linewidth": number; /** Default value: `false` */ "linetoolpitchfork.level4.visible": boolean; /** Default value: `1` */ "linetoolpitchfork.level5.coeff": number; /** Default value: `#2962FF` */ "linetoolpitchfork.level5.color": string; /** Default value: `0` */ "linetoolpitchfork.level5.linestyle": number; /** Default value: `2` */ "linetoolpitchfork.level5.linewidth": number; /** Default value: `true` */ "linetoolpitchfork.level5.visible": boolean; /** Default value: `1.5` */ "linetoolpitchfork.level6.coeff": number; /** Default value: `#9c27b0` */ "linetoolpitchfork.level6.color": string; /** Default value: `0` */ "linetoolpitchfork.level6.linestyle": number; /** Default value: `2` */ "linetoolpitchfork.level6.linewidth": number; /** Default value: `false` */ "linetoolpitchfork.level6.visible": boolean; /** Default value: `1.75` */ "linetoolpitchfork.level7.coeff": number; /** Default value: `#e91e63` */ "linetoolpitchfork.level7.color": string; /** Default value: `0` */ "linetoolpitchfork.level7.linestyle": number; /** Default value: `2` */ "linetoolpitchfork.level7.linewidth": number; /** Default value: `false` */ "linetoolpitchfork.level7.visible": boolean; /** Default value: `2` */ "linetoolpitchfork.level8.coeff": number; /** Default value: `#F77C80` */ "linetoolpitchfork.level8.color": string; /** Default value: `0` */ "linetoolpitchfork.level8.linestyle": number; /** Default value: `2` */ "linetoolpitchfork.level8.linewidth": number; /** Default value: `false` */ "linetoolpitchfork.level8.visible": boolean; /** Default value: `#F23645` */ "linetoolpitchfork.median.color": string; /** Default value: `0` */ "linetoolpitchfork.median.linestyle": number; /** Default value: `2` */ "linetoolpitchfork.median.linewidth": number; /** Default value: `true` */ "linetoolpitchfork.median.visible": boolean; /** Default value: `0` */ "linetoolpitchfork.style": number; /** Default value: `80` */ "linetoolpitchfork.transparency": number; } /** * Overrides for the 'Pivot Points Standard' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface PivotPointsStandardIndicatorOverrides { [key: string]: StudyOverrideValueType; } export interface PlaceOrderResult { /** Order id - this is mainly used for debugging purpose */ orderId?: string; } export interface PlacedOrder extends PlacedOrderBase, CustomFields { } /** * An object that contains information 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; /** Guaranteed stop loss price (double). Available when Brackets are enabled and supportGuaranteedStop flag is set to true */ guaranteedStop?: 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 Plot { readonly id: string; } export interface PlotOptions { color: string; display: DisplayOption; linewidth: number; offset: number; style: PlotStyles[keyof PlotStyles]; title: string; } export interface PlotStyles { line: StudyPlotType.Line; } 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; } /** * Polygon Preferences */ export interface PolygonPreferences { /** Transparency of the Polygon. Value between 0 and 100, where `100` -> fully transparent */ transparency: number; /** Color of the Polygon */ color: string; } /** * Override properties for the Polyline drawing tool. */ export interface PolylineLineToolOverrides { /** Default value: `rgba(0, 188, 212, 0.2)` */ "linetoolpolyline.backgroundColor": string; /** Default value: `true` */ "linetoolpolyline.fillBackground": boolean; /** Default value: `false` */ "linetoolpolyline.filled": boolean; /** Default value: `#00bcd4` */ "linetoolpolyline.linecolor": string; /** Default value: `0` */ "linetoolpolyline.linestyle": number; /** Default value: `2` */ "linetoolpolyline.linewidth": number; /** Default value: `80` */ "linetoolpolyline.transparency": number; } 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; /** * The weighted average price of all positions for a symbol. * The library uses this value to draw a position line on the chart and to calculate [profit and loss values](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss). */ avgPrice: number; /** Last update time (unix timestamp in milliseconds) */ updateTime?: number; /** Message describing the state of the position */ message?: OrderOrPositionMessage; } export interface PositionDialogOptions extends TradingDialogOptions { } /** * Override properties for the Position drawing tool. */ export interface PositionLineToolOverrides { /** Default value: `rgba(255, 255, 255, 0.25)` */ "linetoolposition.bodyBackgroundColor": string; /** Default value: `25` */ "linetoolposition.bodyBackgroundTransparency": number; /** Default value: `#4094e8` */ "linetoolposition.bodyBorderBuyColor": string; /** Default value: `#e75656` */ "linetoolposition.bodyBorderSellColor": string; /** Default value: `true` */ "linetoolposition.bodyFontBold": boolean; /** Default value: `Verdana` */ "linetoolposition.bodyFontFamily": string; /** Default value: `false` */ "linetoolposition.bodyFontItalic": boolean; /** Default value: `9` */ "linetoolposition.bodyFontSize": number; /** Default value: `#e75656` */ "linetoolposition.bodyTextNegativeColor": string; /** Default value: `#646464` */ "linetoolposition.bodyTextNeutralColor": string; /** Default value: `#268c02` */ "linetoolposition.bodyTextPositiveColor": string; /** Default value: `rgba(255, 255, 255, 0.25)` */ "linetoolposition.closeButtonBackgroundColor": string; /** Default value: `25` */ "linetoolposition.closeButtonBackgroundTransparency": number; /** Default value: `#4094e8` */ "linetoolposition.closeButtonBorderBuyColor": string; /** Default value: `#e75656` */ "linetoolposition.closeButtonBorderSellColor": string; /** Default value: `#4094e8` */ "linetoolposition.closeButtonIconBuyColor": string; /** Default value: `#e75656` */ "linetoolposition.closeButtonIconSellColor": string; /** Default value: `undefined` */ "linetoolposition.closeTooltip": string; /** Default value: `inherit` */ "linetoolposition.extendLeft": string; /** Default value: `#4094e8` */ "linetoolposition.lineBuyColor": string; /** Default value: `inherit` */ "linetoolposition.lineLength": string; /** Default value: `percentage` */ "linetoolposition.lineLengthUnit": string; /** Default value: `#e75656` */ "linetoolposition.lineSellColor": string; /** Default value: `inherit` */ "linetoolposition.lineStyle": string; /** Default value: `inherit` */ "linetoolposition.lineWidth": string; /** Default value: `undefined` */ "linetoolposition.protectTooltip": string; /** Default value: `#4094e8` */ "linetoolposition.quantityBackgroundBuyColor": string; /** Default value: `#e75656` */ "linetoolposition.quantityBackgroundSellColor": string; /** Default value: `#4094e8` */ "linetoolposition.quantityBorderBuyColor": string; /** Default value: `#e75656` */ "linetoolposition.quantityBorderSellColor": string; /** Default value: `true` */ "linetoolposition.quantityFontBold": boolean; /** Default value: `Verdana` */ "linetoolposition.quantityFontFamily": string; /** Default value: `false` */ "linetoolposition.quantityFontItalic": boolean; /** Default value: `9` */ "linetoolposition.quantityFontSize": number; /** Default value: `#ffffff` */ "linetoolposition.quantityTextColor": string; /** Default value: `0` */ "linetoolposition.quantityTextTransparency": number; /** Default value: `rgba(255, 255, 255, 0.25)` */ "linetoolposition.reverseButtonBackgroundColor": string; /** Default value: `25` */ "linetoolposition.reverseButtonBackgroundTransparency": number; /** Default value: `#4094e8` */ "linetoolposition.reverseButtonBorderBuyColor": string; /** Default value: `#e75656` */ "linetoolposition.reverseButtonBorderSellColor": string; /** Default value: `#4094e8` */ "linetoolposition.reverseButtonIconBuyColor": string; /** Default value: `#e75656` */ "linetoolposition.reverseButtonIconSellColor": string; /** Default value: `undefined` */ "linetoolposition.reverseTooltip": string; /** Default value: `undefined` */ "linetoolposition.tooltip": string; } /** * 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 information is sufficient to place an order. */ export interface PreOrder extends OrderTemplateBase { /** @inheritDoc */ symbol: string; /** @inheritDoc */ type: OrderType; /** @inheritDoc */ side: Side; /** @inheritDoc */ qty: number; /** * It is set to `true`, if the order closes a position. */ isClose?: boolean; } /** * Override properties for the Prediction drawing tool. */ export interface PredictionLineToolOverrides { /** Default value: `#202020` */ "linetoolprediction.centersColor": string; /** Default value: `#F23645` */ "linetoolprediction.failureBackground": string; /** Default value: `#ffffff` */ "linetoolprediction.failureTextColor": string; /** Default value: `#ead289` */ "linetoolprediction.intermediateBackColor": string; /** Default value: `#6d4d22` */ "linetoolprediction.intermediateTextColor": string; /** Default value: `#2962FF` */ "linetoolprediction.linecolor": string; /** Default value: `2` */ "linetoolprediction.linewidth": number; /** Default value: `#2962FF` */ "linetoolprediction.sourceBackColor": string; /** Default value: `#2962FF` */ "linetoolprediction.sourceStrokeColor": string; /** Default value: `#ffffff` */ "linetoolprediction.sourceTextColor": string; /** Default value: `#4caf50` */ "linetoolprediction.successBackground": string; /** Default value: `#ffffff` */ "linetoolprediction.successTextColor": string; /** Default value: `#2962FF` */ "linetoolprediction.targetBackColor": string; /** Default value: `#2962FF` */ "linetoolprediction.targetStrokeColor": string; /** Default value: `#ffffff` */ "linetoolprediction.targetTextColor": string; /** Default value: `10` */ "linetoolprediction.transparency": number; } /** * Overrides for the 'Price Channel' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface PriceChannelIndicatorOverrides { /** Default value: `15` */ "highprice line.display": number; /** Default value: `0` */ "highprice line.linestyle": number; /** Default value: `1` */ "highprice line.linewidth": number; /** Default value: `line` */ "highprice line.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "highprice line.trackprice": boolean; /** Default value: `0` */ "highprice line.transparency": number; /** Default value: `#F50057` */ "highprice line.color": string; /** Default value: `15` */ "lowprice line.display": number; /** Default value: `0` */ "lowprice line.linestyle": number; /** Default value: `1` */ "lowprice line.linewidth": number; /** Default value: `line` */ "lowprice line.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lowprice line.trackprice": boolean; /** Default value: `0` */ "lowprice line.transparency": number; /** Default value: `#F50057` */ "lowprice line.color": string; /** Default value: `15` */ "centerprice line.display": number; /** Default value: `0` */ "centerprice line.linestyle": number; /** Default value: `1` */ "centerprice line.linewidth": number; /** Default value: `line` */ "centerprice line.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "centerprice line.trackprice": boolean; /** Default value: `0` */ "centerprice line.transparency": number; /** Default value: `#2196F3` */ "centerprice line.color": string; [key: string]: StudyOverrideValueType; } export interface PriceFormatterFormatOptions extends SymbolValueFormatterFormatOptions { /** Add `tailSize` digits to fractional part of result string */ tailSize?: number; /** Add minus sign to result string */ signNegative?: boolean; /** Use Right to left format */ useRtlFormat?: boolean; /** Cuts price by priceScalePrecision, without rounding */ cutFractionalByPrecision?: boolean; /** Remove all trailing zeroes in decimal part */ removeAllEndingZeros?: boolean; } /** * Overrides for the 'Price Oscillator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface PriceOscillatorIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#089981` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Price Volume Trend' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface PriceVolumeTrendIndicatorOverrides { /** Default value: `15` */ "pvt.display": number; /** Default value: `0` */ "pvt.linestyle": number; /** Default value: `1` */ "pvt.linewidth": number; /** Default value: `line` */ "pvt.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "pvt.trackprice": boolean; /** Default value: `0` */ "pvt.transparency": number; /** Default value: `#2196F3` */ "pvt.color": string; [key: string]: StudyOverrideValueType; } /** * Position defined by a price and time. */ export interface PricedPoint extends TimePoint { /** Price */ price: number; } /** * Override properties for the Pricelabel drawing tool. */ export interface PricelabelLineToolOverrides { /** Default value: `#2962FF` */ "linetoolpricelabel.backgroundColor": string; /** Default value: `#2962FF` */ "linetoolpricelabel.borderColor": string; /** Default value: `#ffffff` */ "linetoolpricelabel.color": string; /** Default value: `14` */ "linetoolpricelabel.fontsize": number; /** Default value: `bold` */ "linetoolpricelabel.fontWeight": string; /** Default value: `0` */ "linetoolpricelabel.transparency": number; } /** * Override properties for the Projection drawing tool. */ export interface ProjectionLineToolOverrides { /** Default value: `rgba(41, 98, 255, 0.2)` */ "linetoolprojection.color1": string; /** Default value: `rgba(156, 39, 176, 0.2)` */ "linetoolprojection.color2": string; /** Default value: `true` */ "linetoolprojection.fillBackground": boolean; /** Default value: `1` */ "linetoolprojection.level1.coeff": number; /** Default value: `#808080` */ "linetoolprojection.level1.color": string; /** Default value: `0` */ "linetoolprojection.level1.linestyle": number; /** Default value: `2` */ "linetoolprojection.level1.linewidth": number; /** Default value: `true` */ "linetoolprojection.level1.visible": boolean; /** Default value: `2` */ "linetoolprojection.linewidth": number; /** Default value: `true` */ "linetoolprojection.showCoeffs": boolean; /** Default value: `80` */ "linetoolprojection.transparency": number; /** Default value: `#9C9C9C` */ "linetoolprojection.trendline.color": string; /** Default value: `0` */ "linetoolprojection.trendline.linestyle": number; /** Default value: `true` */ "linetoolprojection.trendline.visible": boolean; } /** * 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; } /** * Options for specifying a Range which includes a resolution, and a time frame. */ export interface RangeOptions { /** * Time frame for the range. */ val: TimeFrameValue; /** * Resolution for the range. */ res: ResolutionString; } /** * Overrides for the 'Rank Correlation Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface RankCorrelationIndexIndicatorOverrides { /** Default value: `#787B86` */ "zero line.color": string; /** Default value: `2` */ "zero line.linestyle": number; /** Default value: `1` */ "zero line.linewidth": number; /** Default value: `true` */ "zero line.visible": boolean; /** Default value: `0` */ "zero line.value": number; /** Default value: `15` */ "rci.display": number; /** Default value: `0` */ "rci.linestyle": number; /** Default value: `1` */ "rci.linewidth": number; /** Default value: `line` */ "rci.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "rci.trackprice": boolean; /** Default value: `0` */ "rci.transparency": number; /** Default value: `#2196F3` */ "rci.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Rate Of Change' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface RateOfChangeIndicatorOverrides { /** Default value: `#787B86` */ "zero line.color": string; /** Default value: `2` */ "zero line.linestyle": number; /** Default value: `1` */ "zero line.linewidth": number; /** Default value: `true` */ "zero line.visible": boolean; /** Default value: `0` */ "zero line.value": number; /** Default value: `15` */ "roc.display": number; /** Default value: `0` */ "roc.linestyle": number; /** Default value: `1` */ "roc.linewidth": number; /** Default value: `line` */ "roc.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "roc.trackprice": boolean; /** Default value: `0` */ "roc.transparency": number; /** Default value: `#2196F3` */ "roc.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Ratio' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface RatioIndicatorOverrides { /** Default value: `undefined` */ "negativefill.color": string; /** Default value: `0` */ "negativefill.transparency": number; /** Default value: `true` */ "negativefill.visible": boolean; /** Default value: `undefined` */ "positivefill.color": string; /** Default value: `0` */ "positivefill.transparency": number; /** Default value: `true` */ "positivefill.visible": boolean; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `2` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `35` */ "plot.transparency": number; /** Default value: `#800080` */ "plot.color": string; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "baseline.linestyle": number; /** Default value: `2` */ "baseline.linewidth": number; /** Default value: `line` */ "baseline.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "baseline.trackprice": boolean; /** Default value: `0` */ "baseline.transparency": number; /** Default value: `rgba(0, 0, 0, 0)` */ "baseline.color": string; /** Default value: `0` */ "baseline.display": number; [key: string]: StudyOverrideValueType; } export interface RawStudyMetaInfo extends RawStudyMetaInfoBase { /** Identifier for Study */ readonly id: RawStudyMetaInfoId; } export interface RawStudyMetaInfoBase { /** * Description of the study. It will be displayed in the Indicators window and will be used as a name argument when calling the createStudy method */ readonly description: string; /** Short description of the study. Will be displayed on the chart */ readonly shortDescription: string; /** Name for the study */ readonly name?: string; /** Metainfo version of the study. The current version is 53, and the default one is 0. */ readonly _metainfoVersion?: number; /** Use {@link format} instead. * @deprecated */ readonly precision?: number | string; /** * A type of data that an indicator displays, such as `volume` or `price`. Values on the [Price Scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale) depend on this data type. * Additionally, you can adjust a precision of indicator values. To do this, specify the `precision` property in {@link StudyPlotValuePrecisionFormat}. * * For more information about `format`, refer to the [Metainfo](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/metainfo) article. */ readonly format: StudyPlotValueFormat; /** Whether the study should appear on the main series pane */ readonly is_price_study?: boolean; /** should be `true` in Custom Study */ readonly isCustomIndicator?: boolean; /** Whether the study price scale should be the same as the main series one. */ readonly linkedToSeries?: boolean; /** Price scale to use for the study */ readonly priceScale?: StudyTargetPriceScale; /** Whether the study should appear in Indicators list. */ readonly is_hidden_study?: boolean; /** an object containing settings that are applied when user clicks 'Apply Defaults'. See dedicated article: [Custom Studies Defaults](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/Custom-Studies-Defaults) */ readonly defaults: Readonly>; /** Bands */ readonly bands?: readonly Readonly[]; /** Filled area is a special object, which allows coloring an area between two plots or hlines. Please note, that it is impossible to fill the area between a band and a hline. */ readonly filledAreas?: readonly Readonly[]; /** An array of objects that represent input parameters. For more information, refer to the [Inputs](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/Custom-Studies-Inputs) article. */ readonly inputs?: StudyInputInfoList; /** Symbol source */ readonly symbolSource?: SymbolSource; /** * definitions of palettes that are used in plots and defaults. Palettes allows you use different styles (not only colors) for each line point. * * This object contains palette names as keys, and palette info as values: `[palette.name]: { colors, valToIndex, addDefaultColor }`, where * - `colors`* - an object `{ [color_id]: { name: 'name' }}`, where name is a string that will appear on Style tab of study properties dialog. * - `valToIndex` - an object, the mapping between the values that are returned by the script and palette colors. * - `addDefaultColor` - boolean, if true the defaults are used for colorer type plot, when its value is null or undefined. */ readonly palettes?: MappedObject>; /** array with study plots info. See dedicated article: [Custom Studies Plots](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Plots) */ readonly plots?: readonly Readonly[]; /** an object with plot id as keys and style info as values. */ readonly styles?: MappedObject>; /** array with study plots info. See dedicated article: [Custom Studies OHLC Plots](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-OHLC-Plots) */ readonly ohlcPlots?: MappedObject>; /** Financial Period */ readonly financialPeriod?: FinancialPeriod; /** Key for grouping studies */ readonly groupingKey?: string; /** Define should be study on series level or not */ readonly behind_chart?: boolean; } /** * Override properties for the Ray drawing tool. */ export interface RayLineToolOverrides { /** Default value: `false` */ "linetoolray.alwaysShowStats": boolean; /** Default value: `false` */ "linetoolray.bold": boolean; /** Default value: `false` */ "linetoolray.extendLeft": boolean; /** Default value: `true` */ "linetoolray.extendRight": boolean; /** Default value: `14` */ "linetoolray.fontsize": number; /** Default value: `center` */ "linetoolray.horzLabelsAlign": string; /** Default value: `false` */ "linetoolray.italic": boolean; /** Default value: `0` */ "linetoolray.leftEnd": number; /** Default value: `#2962FF` */ "linetoolray.linecolor": string; /** Default value: `0` */ "linetoolray.linestyle": number; /** Default value: `2` */ "linetoolray.linewidth": number; /** Default value: `0` */ "linetoolray.rightEnd": number; /** Default value: `false` */ "linetoolray.showAngle": boolean; /** Default value: `false` */ "linetoolray.showBarsRange": boolean; /** Default value: `false` */ "linetoolray.showDateTimeRange": boolean; /** Default value: `false` */ "linetoolray.showDistance": boolean; /** Default value: `false` */ "linetoolray.showMiddlePoint": boolean; /** Default value: `false` */ "linetoolray.showPercentPriceRange": boolean; /** Default value: `false` */ "linetoolray.showPipsPriceRange": boolean; /** Default value: `false` */ "linetoolray.showPriceLabels": boolean; /** Default value: `false` */ "linetoolray.showPriceRange": boolean; /** Default value: `2` */ "linetoolray.statsPosition": number; /** Default value: `#2962FF` */ "linetoolray.textcolor": string; /** Default value: `bottom` */ "linetoolray.vertLabelsAlign": string; } /** * Overrides for the 'Regression Trend' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface RegressionTrendIndicatorOverrides { [key: string]: StudyOverrideValueType; } /** * Override properties for the Regressiontrend drawing tool. */ export interface RegressiontrendLineToolOverrides { /** Default value: `0` */ "linetoolregressiontrend.inputs.first bar time": number; /** Default value: `0` */ "linetoolregressiontrend.inputs.last bar time": number; /** Default value: `-2` */ "linetoolregressiontrend.inputs.lower diviation": number; /** Default value: `close` */ "linetoolregressiontrend.inputs.source": string; /** Default value: `2` */ "linetoolregressiontrend.inputs.upper diviation": number; /** Default value: `true` */ "linetoolregressiontrend.inputs.use lower diviation": boolean; /** Default value: `true` */ "linetoolregressiontrend.inputs.use upper diviation": boolean; /** Default value: `0` */ "linetoolregressiontrend.linestyle": number; /** Default value: `1` */ "linetoolregressiontrend.linewidth": number; /** Default value: `default` */ "linetoolregressiontrend.precision": string; /** Default value: `rgba(242, 54, 69, 0.3)` */ "linetoolregressiontrend.styles.baseLine.color": string; /** Default value: `15` */ "linetoolregressiontrend.styles.baseLine.display": number; /** Default value: `2` */ "linetoolregressiontrend.styles.baseLine.linestyle": number; /** Default value: `1` */ "linetoolregressiontrend.styles.baseLine.linewidth": number; /** Default value: `rgba(41, 98, 255, 0.3)` */ "linetoolregressiontrend.styles.downLine.color": string; /** Default value: `15` */ "linetoolregressiontrend.styles.downLine.display": number; /** Default value: `0` */ "linetoolregressiontrend.styles.downLine.linestyle": number; /** Default value: `2` */ "linetoolregressiontrend.styles.downLine.linewidth": number; /** Default value: `false` */ "linetoolregressiontrend.styles.extendLines": boolean; /** Default value: `true` */ "linetoolregressiontrend.styles.showPearsons": boolean; /** Default value: `70` */ "linetoolregressiontrend.styles.transparency": number; /** Default value: `rgba(41, 98, 255, 0.3)` */ "linetoolregressiontrend.styles.upLine.color": string; /** Default value: `15` */ "linetoolregressiontrend.styles.upLine.display": number; /** Default value: `0` */ "linetoolregressiontrend.styles.upLine.linestyle": number; /** Default value: `2` */ "linetoolregressiontrend.styles.upLine.linewidth": number; } /** * Overrides for the 'Relative Strength Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface RelativeStrengthIndexIndicatorOverrides { /** Default value: `#7E57C2` */ "hlines background.color": string; /** Default value: `90` */ "hlines background.transparency": number; /** Default value: `true` */ "hlines background.visible": boolean; /** Default value: `#787B86` */ "upperlimit.color": string; /** Default value: `2` */ "upperlimit.linestyle": number; /** Default value: `1` */ "upperlimit.linewidth": number; /** Default value: `true` */ "upperlimit.visible": boolean; /** Default value: `70` */ "upperlimit.value": number; /** Default value: `-1.1` */ "upperlimit.zorder": number; /** Default value: `#787B86` */ "middlelimit.color": string; /** Default value: `2` */ "middlelimit.linestyle": number; /** Default value: `1` */ "middlelimit.linewidth": number; /** Default value: `true` */ "middlelimit.visible": boolean; /** Default value: `50` */ "middlelimit.value": number; /** Default value: `-1.11` */ "middlelimit.zorder": number; /** Default value: `#787B86` */ "lowerlimit.color": string; /** Default value: `2` */ "lowerlimit.linestyle": number; /** Default value: `1` */ "lowerlimit.linewidth": number; /** Default value: `true` */ "lowerlimit.visible": boolean; /** Default value: `30` */ "lowerlimit.value": number; /** Default value: `-1.111` */ "lowerlimit.zorder": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#7E57C2` */ "plot.color": string; /** Default value: `0` */ "smoothed ma.display": number; /** Default value: `0` */ "smoothed ma.linestyle": number; /** Default value: `1` */ "smoothed ma.linewidth": number; /** Default value: `line` */ "smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "smoothed ma.trackprice": boolean; /** Default value: `0` */ "smoothed ma.transparency": number; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Relative Vigor Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface RelativeVigorIndexIndicatorOverrides { /** Default value: `15` */ "rvgi.display": number; /** Default value: `0` */ "rvgi.linestyle": number; /** Default value: `1` */ "rvgi.linewidth": number; /** Default value: `line` */ "rvgi.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "rvgi.trackprice": boolean; /** Default value: `0` */ "rvgi.transparency": number; /** Default value: `#089981` */ "rvgi.color": string; /** Default value: `15` */ "signal.display": number; /** Default value: `0` */ "signal.linestyle": number; /** Default value: `1` */ "signal.linewidth": number; /** Default value: `line` */ "signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "signal.trackprice": boolean; /** Default value: `0` */ "signal.transparency": number; /** Default value: `#F23645` */ "signal.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Relative Volatility Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface RelativeVolatilityIndexIndicatorOverrides { /** Default value: `#7E57C2` */ "hlines background.color": string; /** Default value: `90` */ "hlines background.transparency": number; /** Default value: `true` */ "hlines background.visible": boolean; /** Default value: `#787B86` */ "upperlimit.color": string; /** Default value: `2` */ "upperlimit.linestyle": number; /** Default value: `1` */ "upperlimit.linewidth": number; /** Default value: `true` */ "upperlimit.visible": boolean; /** Default value: `80` */ "upperlimit.value": number; /** Default value: `#787B86` */ "lowerlimit.color": string; /** Default value: `2` */ "lowerlimit.linestyle": number; /** Default value: `1` */ "lowerlimit.linewidth": number; /** Default value: `true` */ "lowerlimit.visible": boolean; /** Default value: `20` */ "lowerlimit.value": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#7E57C2` */ "plot.color": string; [key: string]: StudyOverrideValueType; } 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 RequestFunctions { security(tickerId: TickerId, options?: RequestSecurityOptions): IPineSeries; } export interface RequestSecurityOptions { expression: () => IPineSeries; } export interface RestBrokerConnectionInfo { /** URL endpoint */ url: string; /** Access token for the REST API */ access_token: string; } /** * Override properties for the Riskrewardlong drawing tool. */ export interface RiskrewardlongLineToolOverrides { /** Default value: `1000` */ "linetoolriskrewardlong.accountSize": number; /** Default value: `false` */ "linetoolriskrewardlong.alwaysShowStats": boolean; /** Default value: `#667b8b` */ "linetoolriskrewardlong.borderColor": string; /** Default value: `false` */ "linetoolriskrewardlong.compact": boolean; /** Default value: `NONE` */ "linetoolriskrewardlong.currency": string; /** Default value: `false` */ "linetoolriskrewardlong.drawBorder": boolean; /** Default value: `true` */ "linetoolriskrewardlong.fillBackground": boolean; /** Default value: `true` */ "linetoolriskrewardlong.fillLabelBackground": boolean; /** Default value: `12` */ "linetoolriskrewardlong.fontsize": number; /** Default value: `#585858` */ "linetoolriskrewardlong.labelBackgroundColor": string; /** Default value: `#808080` */ "linetoolriskrewardlong.linecolor": string; /** Default value: `1` */ "linetoolriskrewardlong.linewidth": number; /** Default value: `1` */ "linetoolriskrewardlong.lotSize": number; /** Default value: `rgba(8, 153, 129, 0.2)` */ "linetoolriskrewardlong.profitBackground": string; /** Default value: `80` */ "linetoolriskrewardlong.profitBackgroundTransparency": number; /** Default value: `25` */ "linetoolriskrewardlong.risk": number; /** Default value: `percents` */ "linetoolriskrewardlong.riskDisplayMode": string; /** Default value: `true` */ "linetoolriskrewardlong.showPriceLabels": boolean; /** Default value: `rgba(242, 54, 69, 0.2)` */ "linetoolriskrewardlong.stopBackground": string; /** Default value: `80` */ "linetoolriskrewardlong.stopBackgroundTransparency": number; /** Default value: `#ffffff` */ "linetoolriskrewardlong.textcolor": string; } /** * Override properties for the Riskrewardshort drawing tool. */ export interface RiskrewardshortLineToolOverrides { /** Default value: `1000` */ "linetoolriskrewardshort.accountSize": number; /** Default value: `false` */ "linetoolriskrewardshort.alwaysShowStats": boolean; /** Default value: `#667b8b` */ "linetoolriskrewardshort.borderColor": string; /** Default value: `false` */ "linetoolriskrewardshort.compact": boolean; /** Default value: `NONE` */ "linetoolriskrewardshort.currency": string; /** Default value: `false` */ "linetoolriskrewardshort.drawBorder": boolean; /** Default value: `true` */ "linetoolriskrewardshort.fillBackground": boolean; /** Default value: `true` */ "linetoolriskrewardshort.fillLabelBackground": boolean; /** Default value: `12` */ "linetoolriskrewardshort.fontsize": number; /** Default value: `#585858` */ "linetoolriskrewardshort.labelBackgroundColor": string; /** Default value: `#808080` */ "linetoolriskrewardshort.linecolor": string; /** Default value: `1` */ "linetoolriskrewardshort.linewidth": number; /** Default value: `1` */ "linetoolriskrewardshort.lotSize": number; /** Default value: `rgba(8, 153, 129, 0.2)` */ "linetoolriskrewardshort.profitBackground": string; /** Default value: `80` */ "linetoolriskrewardshort.profitBackgroundTransparency": number; /** Default value: `25` */ "linetoolriskrewardshort.risk": number; /** Default value: `percents` */ "linetoolriskrewardshort.riskDisplayMode": string; /** Default value: `true` */ "linetoolriskrewardshort.showPriceLabels": boolean; /** Default value: `rgba(242, 54, 69, 0.2)` */ "linetoolriskrewardshort.stopBackground": string; /** Default value: `80` */ "linetoolriskrewardshort.stopBackgroundTransparency": number; /** Default value: `#ffffff` */ "linetoolriskrewardshort.textcolor": string; } /** * Override properties for the Rotatedrectangle drawing tool. */ export interface RotatedrectangleLineToolOverrides { /** Default value: `rgba(76, 175, 80, 0.2)` */ "linetoolrotatedrectangle.backgroundColor": string; /** Default value: `#4caf50` */ "linetoolrotatedrectangle.color": string; /** Default value: `true` */ "linetoolrotatedrectangle.fillBackground": boolean; /** Default value: `2` */ "linetoolrotatedrectangle.linewidth": number; /** Default value: `50` */ "linetoolrotatedrectangle.transparency": number; } 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; } export interface RuntimeFunctions { error(message: string): never; } /** * Overrides for the 'SMI Ergodic Indicator/Oscillator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface SMIErgodicIndicatorOscillatorIndicatorOverrides { /** Default value: `15` */ "indicator.display": number; /** Default value: `0` */ "indicator.linestyle": number; /** Default value: `1` */ "indicator.linewidth": number; /** Default value: `line` */ "indicator.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "indicator.trackprice": boolean; /** Default value: `0` */ "indicator.transparency": number; /** Default value: `#2196F3` */ "indicator.color": string; /** Default value: `15` */ "signal.display": number; /** Default value: `0` */ "signal.linestyle": number; /** Default value: `1` */ "signal.linewidth": number; /** Default value: `line` */ "signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "signal.trackprice": boolean; /** Default value: `0` */ "signal.transparency": number; /** Default value: `#FF6D00` */ "signal.color": string; /** Default value: `15` */ "oscillator.display": number; /** Default value: `0` */ "oscillator.linestyle": number; /** Default value: `1` */ "oscillator.linewidth": number; /** Default value: `histogram` */ "oscillator.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "oscillator.trackprice": boolean; /** Default value: `0` */ "oscillator.transparency": number; /** Default value: `#FF5252` */ "oscillator.color": string; [key: string]: StudyOverrideValueType; } /** * Save chart error information */ export interface SaveChartErrorInfo { /** Error message */ message: string; } /** * Save Chart Options */ export interface SaveChartOptions { /** * Whether drawings should be included in the saved data. * * @default true */ includeDrawings?: boolean; } /** * 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 | number; /** 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; } /** * Override properties for the Schiffpitchfork2 drawing tool. */ export interface Schiffpitchfork2LineToolOverrides { /** Default value: `false` */ "linetoolschiffpitchfork2.extendLines": boolean; /** Default value: `true` */ "linetoolschiffpitchfork2.fillBackground": boolean; /** Default value: `0.25` */ "linetoolschiffpitchfork2.level0.coeff": number; /** Default value: `#ffb74d` */ "linetoolschiffpitchfork2.level0.color": string; /** Default value: `0` */ "linetoolschiffpitchfork2.level0.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork2.level0.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork2.level0.visible": boolean; /** Default value: `0.382` */ "linetoolschiffpitchfork2.level1.coeff": number; /** Default value: `#81c784` */ "linetoolschiffpitchfork2.level1.color": string; /** Default value: `0` */ "linetoolschiffpitchfork2.level1.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork2.level1.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork2.level1.visible": boolean; /** Default value: `0.5` */ "linetoolschiffpitchfork2.level2.coeff": number; /** Default value: `#089981` */ "linetoolschiffpitchfork2.level2.color": string; /** Default value: `0` */ "linetoolschiffpitchfork2.level2.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork2.level2.linewidth": number; /** Default value: `true` */ "linetoolschiffpitchfork2.level2.visible": boolean; /** Default value: `0.618` */ "linetoolschiffpitchfork2.level3.coeff": number; /** Default value: `#089981` */ "linetoolschiffpitchfork2.level3.color": string; /** Default value: `0` */ "linetoolschiffpitchfork2.level3.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork2.level3.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork2.level3.visible": boolean; /** Default value: `0.75` */ "linetoolschiffpitchfork2.level4.coeff": number; /** Default value: `#00bcd4` */ "linetoolschiffpitchfork2.level4.color": string; /** Default value: `0` */ "linetoolschiffpitchfork2.level4.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork2.level4.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork2.level4.visible": boolean; /** Default value: `1` */ "linetoolschiffpitchfork2.level5.coeff": number; /** Default value: `#2962FF` */ "linetoolschiffpitchfork2.level5.color": string; /** Default value: `0` */ "linetoolschiffpitchfork2.level5.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork2.level5.linewidth": number; /** Default value: `true` */ "linetoolschiffpitchfork2.level5.visible": boolean; /** Default value: `1.5` */ "linetoolschiffpitchfork2.level6.coeff": number; /** Default value: `#9c27b0` */ "linetoolschiffpitchfork2.level6.color": string; /** Default value: `0` */ "linetoolschiffpitchfork2.level6.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork2.level6.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork2.level6.visible": boolean; /** Default value: `1.75` */ "linetoolschiffpitchfork2.level7.coeff": number; /** Default value: `#e91e63` */ "linetoolschiffpitchfork2.level7.color": string; /** Default value: `0` */ "linetoolschiffpitchfork2.level7.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork2.level7.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork2.level7.visible": boolean; /** Default value: `2` */ "linetoolschiffpitchfork2.level8.coeff": number; /** Default value: `#F77C80` */ "linetoolschiffpitchfork2.level8.color": string; /** Default value: `0` */ "linetoolschiffpitchfork2.level8.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork2.level8.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork2.level8.visible": boolean; /** Default value: `#F23645` */ "linetoolschiffpitchfork2.median.color": string; /** Default value: `0` */ "linetoolschiffpitchfork2.median.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork2.median.linewidth": number; /** Default value: `true` */ "linetoolschiffpitchfork2.median.visible": boolean; /** Default value: `3` */ "linetoolschiffpitchfork2.style": number; /** Default value: `80` */ "linetoolschiffpitchfork2.transparency": number; } /** * Override properties for the Schiffpitchfork drawing tool. */ export interface SchiffpitchforkLineToolOverrides { /** Default value: `false` */ "linetoolschiffpitchfork.extendLines": boolean; /** Default value: `true` */ "linetoolschiffpitchfork.fillBackground": boolean; /** Default value: `0.25` */ "linetoolschiffpitchfork.level0.coeff": number; /** Default value: `#ffb74d` */ "linetoolschiffpitchfork.level0.color": string; /** Default value: `0` */ "linetoolschiffpitchfork.level0.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork.level0.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork.level0.visible": boolean; /** Default value: `0.382` */ "linetoolschiffpitchfork.level1.coeff": number; /** Default value: `#81c784` */ "linetoolschiffpitchfork.level1.color": string; /** Default value: `0` */ "linetoolschiffpitchfork.level1.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork.level1.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork.level1.visible": boolean; /** Default value: `0.5` */ "linetoolschiffpitchfork.level2.coeff": number; /** Default value: `#089981` */ "linetoolschiffpitchfork.level2.color": string; /** Default value: `0` */ "linetoolschiffpitchfork.level2.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork.level2.linewidth": number; /** Default value: `true` */ "linetoolschiffpitchfork.level2.visible": boolean; /** Default value: `0.618` */ "linetoolschiffpitchfork.level3.coeff": number; /** Default value: `#089981` */ "linetoolschiffpitchfork.level3.color": string; /** Default value: `0` */ "linetoolschiffpitchfork.level3.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork.level3.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork.level3.visible": boolean; /** Default value: `0.75` */ "linetoolschiffpitchfork.level4.coeff": number; /** Default value: `#00bcd4` */ "linetoolschiffpitchfork.level4.color": string; /** Default value: `0` */ "linetoolschiffpitchfork.level4.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork.level4.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork.level4.visible": boolean; /** Default value: `1` */ "linetoolschiffpitchfork.level5.coeff": number; /** Default value: `#2962FF` */ "linetoolschiffpitchfork.level5.color": string; /** Default value: `0` */ "linetoolschiffpitchfork.level5.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork.level5.linewidth": number; /** Default value: `true` */ "linetoolschiffpitchfork.level5.visible": boolean; /** Default value: `1.5` */ "linetoolschiffpitchfork.level6.coeff": number; /** Default value: `#9c27b0` */ "linetoolschiffpitchfork.level6.color": string; /** Default value: `0` */ "linetoolschiffpitchfork.level6.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork.level6.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork.level6.visible": boolean; /** Default value: `1.75` */ "linetoolschiffpitchfork.level7.coeff": number; /** Default value: `#e91e63` */ "linetoolschiffpitchfork.level7.color": string; /** Default value: `0` */ "linetoolschiffpitchfork.level7.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork.level7.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork.level7.visible": boolean; /** Default value: `2` */ "linetoolschiffpitchfork.level8.coeff": number; /** Default value: `#F77C80` */ "linetoolschiffpitchfork.level8.color": string; /** Default value: `0` */ "linetoolschiffpitchfork.level8.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork.level8.linewidth": number; /** Default value: `false` */ "linetoolschiffpitchfork.level8.visible": boolean; /** Default value: `#F23645` */ "linetoolschiffpitchfork.median.color": string; /** Default value: `0` */ "linetoolschiffpitchfork.median.linestyle": number; /** Default value: `2` */ "linetoolschiffpitchfork.median.linewidth": number; /** Default value: `true` */ "linetoolschiffpitchfork.median.visible": boolean; /** Default value: `1` */ "linetoolschiffpitchfork.style": number; /** Default value: `80` */ "linetoolschiffpitchfork.transparency": number; } export interface ScriptContext { readonly barstate: BarState; readonly color: Colors; readonly input: InputFunctions; readonly linestyle: LineStyles; readonly math: MathFunctions; readonly plotstyle: PlotStyles; readonly request: RequestFunctions; readonly runtime: RuntimeFunctions; readonly ta: TAFunctions; readonly ticker: TickerFunctions; readonly timeframe: TimeframeFunctions; open(): IPineSeries; high(): IPineSeries; low(): IPineSeries; close(): IPineSeries; volume(): IPineSeries; year(): number; na(value: number): boolean; series(value: number): IPineSeries; fill(plot1: HLine, plot2: HLine, options?: Partial): unknown; fill(plot1: Plot, plot2: Plot, options?: Partial): unknown; hline(price: number, options?: Partial): HLine; indicator(options: Partial): void; plot(source: IPineSeries | number, options?: Partial): Plot; } /** * [Symbol Search](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search) result item. * Pass the resulting array of symbols as a parameter to {@link SearchSymbolsCallback} of the [`searchSymbols`](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#searchsymbols) method. * * @example * ``` * { * description: 'Apple Inc.', * exchange: 'NasdaqNM', * symbol: 'AAPL', * ticker: 'AAPL', * type: 'stock', * } * ``` */ export interface SearchSymbolResultItem { /** Short symbol name */ symbol: string; /** Description */ description: string; /** Exchange name */ exchange: string; /** * It is a unique identifier for a particular symbol in your [symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology). * * You should avoid using colons (":") in ticker values unless you are following the TradingView format: "NYSE:IBM". Using colons may cause unexpected behaviour and display bugs. * * Corresponds with {@link LibrarySymbolInfo.ticker}. */ ticker?: string; /** * Type of symbol * * 'stock' | 'futures' | 'forex' | 'index' */ type: string; /** * URL of image/s to be displayed as the logo/s for the symbol. The `show_symbol_logos` featureset needs to be enabled for this to be visible in the UI. * * - If a single url is returned then that url will solely be used to display the symbol logo. * - If two urls are provided then the images will be displayed as two partially overlapping * circles with the first url appearing on top. This is typically used for FOREX where you would * like to display two country flags as the symbol logo. * * The image/s should ideally be square in dimension. You can use any image type which * the browser supports natively. Simple SVG images are recommended. * * Examples: * - `https://yourserver.com/symbolName.svg` * - `/images/myImage.png` * - `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3...` * - `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4...` */ logo_urls?: [ string ] | [ string, string ]; /** * URL of image to be displayed as the logo for the exchange. The `show_exchange_logos` featureset needs to be enabled for this to be visible in the UI. * * The image should ideally be square in dimension. You can use any image type which * the browser supports natively. Simple SVG images are recommended. * * Examples: * - `https://yourserver.com/exchangeLogo.svg` * - `/images/myImage.png` * - `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3...` * - `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4...` */ exchange_logo?: 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; /** Line With Markers Style Preferences */ [ChartStyle.LineWithMarkers]: LineStylePreferences; /** Step Line Style Preferences */ [ChartStyle.Stepline]: LineStylePreferences; /** Area Style Preferences */ [ChartStyle.Area]: AreaStylePreferences; /** HLC Area Style Preferences */ [ChartStyle.HLCArea]: HLCAreaStylePreferences; /** 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; /** HLC bars Style Preferences */ [ChartStyle.HLCBars]: HLCBarsStylePreferences; /** Volume Candle Style Preferences */ [ChartStyle.VolCandle]: CandleStylePreferences; } /** * Overrides for the 'Sessions' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface SessionsIndicatorOverrides { [key: string]: StudyOverrideValueType; } /** * Options for setting a chart's resolution. */ export interface SetResolutionOptions { /** * An optional callback function. Called when the data for the new resolution has loaded. */ dataReady?: () => void; /** * A boolean flag. Allows to disable making the current chart active in the layout. */ doNotActivateChart?: boolean; } /** * Options for setting a chart's symbol. */ export interface SetSymbolOptions { /** * An optional callback function. Called when the data for the new symbol has loaded. */ dataReady?: () => void; /** * A boolean flag. Allows to disable making the current chart active in the layout. */ doNotActivateChart?: boolean; } /** * 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; /** * In the current implementation, we cannot capture all errors during the `SetVisibleRange` process, * which means we cannot guarantee that the process will always be resolved or rejected. * To address this issue, you can use the `rejectByTimeout` option to ensure rejection after a specified timeout. */ rejectByTimeout?: number; } /** * Override properties for the Signpost drawing tool. */ export interface SignpostLineToolOverrides { /** Default value: `false` */ "linetoolsignpost.bold": boolean; /** Default value: `🙂` */ "linetoolsignpost.emoji": string; /** Default value: `12` */ "linetoolsignpost.fontSize": number; /** Default value: `false` */ "linetoolsignpost.italic": boolean; /** Default value: `#2962FF` */ "linetoolsignpost.plateColor": string; /** Default value: `false` */ "linetoolsignpost.showImage": boolean; } /** * Override properties for the Sineline drawing tool. */ export interface SinelineLineToolOverrides { /** Default value: `#159980` */ "linetoolsineline.linecolor": string; /** Default value: `0` */ "linetoolsineline.linestyle": number; /** Default value: `2` */ "linetoolsineline.linewidth": 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 order duration options that determine how long the order remains active. * Specifying `durations` enables a drop-down menu in the Order Ticket for supported orders. * Refer to [Enable Time in force menu](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#enable-time-in-force-menu) for more information. * * The objects have the following keys: `{ name, value, hasDatePicker?, hasTimePicker?, default?, supportedOrderTypes? }`. */ durations?: OrderDurationMetaInfo[]; /** * Order Rules */ orderRules?: OrderRule[]; /** * This optional field can be used to replace the standard Order Ticket and the Add Protection dialogs with your own. * Values of the following two fields are functions that are called by the Trading Platform 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 | IndividualPosition, brackets: Brackets, focus?: OrderTicketFocusControl) => Promise; * showCancelOrderDialog?: (order: Order) => Promise; * showClosePositionDialog?: (position: Position | IndividualPosition) => Promise; * } * ``` */ customUI?: BrokerCustomUI; } /** * Overrides for the 'Smoothed Moving Average' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface SmoothedMovingAverageIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#673AB7` */ "plot.color": string; [key: string]: StudyOverrideValueType; } export interface SolidFillOptions extends CommonFillOptions { color: string; } 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 SourceInputOptions extends CommonInputOptions { } /** * Overrides for the 'Spread' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface SpreadIndicatorOverrides { /** Default value: `undefined` */ "negative fill.color": string; /** Default value: `0` */ "negative fill.transparency": number; /** Default value: `true` */ "negative fill.visible": boolean; /** Default value: `undefined` */ "positive fill.color": string; /** Default value: `0` */ "positive fill.transparency": number; /** Default value: `true` */ "positive fill.visible": boolean; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `2` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `35` */ "plot.transparency": number; /** Default value: `#800080` */ "plot.color": string; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "baseline.linestyle": number; /** Default value: `2` */ "baseline.linewidth": number; /** Default value: `line` */ "baseline.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "baseline.trackprice": boolean; /** Default value: `0` */ "baseline.transparency": number; /** Default value: `rgba(0, 0, 0, 0)` */ "baseline.color": string; /** Default value: `0` */ "baseline.display": number; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Standard Deviation' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface StandardDeviationIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#089981` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Standard Error Bands' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface StandardErrorBandsIndicatorOverrides { /** Default value: `#2196F3` */ "background.color": string; /** Default value: `95` */ "background.transparency": number; /** Default value: `true` */ "background.visible": boolean; /** Default value: `15` */ "plot 1.display": number; /** Default value: `0` */ "plot 1.linestyle": number; /** Default value: `1` */ "plot 1.linewidth": number; /** Default value: `line` */ "plot 1.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "plot 1.transparency": number; /** Default value: `false` */ "plot 1.trackprice": boolean; /** Default value: `#2196F3` */ "plot 1.color": string; /** Default value: `15` */ "plot 2.display": number; /** Default value: `0` */ "plot 2.linestyle": number; /** Default value: `1` */ "plot 2.linewidth": number; /** Default value: `0` */ "plot 2.transparency": number; /** Default value: `line` */ "plot 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 2.trackprice": boolean; /** Default value: `#FF6D00` */ "plot 2.color": string; /** Default value: `15` */ "plot 3.display": number; /** Default value: `0` */ "plot 3.linestyle": number; /** Default value: `1` */ "plot 3.linewidth": number; /** Default value: `0` */ "plot 3.transparency": number; /** Default value: `line` */ "plot 3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot 3.trackprice": boolean; /** Default value: `#2196F3` */ "plot 3.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Standard Error' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface StandardErrorIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#FF6D00` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * The interface that describes the mapping of values in the {@link AccountManagerColumnBase.formatter} and {@link AccountManagerColumnBase.dataFields} properties of the Account Manager columns. * Refer to the [Value formatters](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters) section for more information. */ /* eslint-disable jsdoc/require-jsdoc */ export interface StandardFormattersDependenciesMapping { [StandardFormatterName.Default]: string[]; [StandardFormatterName.Symbol]: SymbolFormatterProperties[keyof SymbolFormatterProperties]; [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.FormatPriceInCurrency]: [ priceProperty: string, currencyProperty: 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.FixedInCurrency]: [ valueProperty: string, currencyProperty: 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.ProfitInPercent]: [ plPercent: string ]; [StandardFormatterName.Percentage]: [ valueProperty: string ]; [StandardFormatterName.MarginPercent]: [ valueProperty: string ]; [StandardFormatterName.Empty]: [ ]; } /* eslint-enable jsdoc/require-jsdoc */ /** * 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"; } /** * Override properties for the Sticker drawing tool. */ export interface StickerLineToolOverrides { /** Default value: `1.5707963267948966` */ "linetoolsticker.angle": number; /** Default value: `110` */ "linetoolsticker.size": number; } /** * Overrides for the 'Stochastic' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface StochasticIndicatorOverrides { /** Default value: `#2196F3` */ "hlines background.color": string; /** Default value: `90` */ "hlines background.transparency": number; /** Default value: `true` */ "hlines background.visible": boolean; /** Default value: `#787B86` */ "upperlimit.color": string; /** Default value: `2` */ "upperlimit.linestyle": number; /** Default value: `1` */ "upperlimit.linewidth": number; /** Default value: `true` */ "upperlimit.visible": boolean; /** Default value: `80` */ "upperlimit.value": number; /** Default value: `#787B86` */ "lowerlimit.color": string; /** Default value: `2` */ "lowerlimit.linestyle": number; /** Default value: `1` */ "lowerlimit.linewidth": number; /** Default value: `true` */ "lowerlimit.visible": boolean; /** Default value: `20` */ "lowerlimit.value": number; /** Default value: `15` */ "%k.display": number; /** Default value: `0` */ "%k.linestyle": number; /** Default value: `1` */ "%k.linewidth": number; /** Default value: `line` */ "%k.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "%k.trackprice": boolean; /** Default value: `0` */ "%k.transparency": number; /** Default value: `#2196F3` */ "%k.color": string; /** Default value: `15` */ "%d.display": number; /** Default value: `0` */ "%d.linestyle": number; /** Default value: `1` */ "%d.linewidth": number; /** Default value: `line` */ "%d.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "%d.trackprice": boolean; /** Default value: `0` */ "%d.transparency": number; /** Default value: `#FF6D00` */ "%d.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Stochastic RSI' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface StochasticRSIIndicatorOverrides { /** Default value: `#2196F3` */ "hlines background.color": string; /** Default value: `90` */ "hlines background.transparency": number; /** Default value: `true` */ "hlines background.visible": boolean; /** Default value: `#787B86` */ "upperlimit.color": string; /** Default value: `2` */ "upperlimit.linestyle": number; /** Default value: `1` */ "upperlimit.linewidth": number; /** Default value: `true` */ "upperlimit.visible": boolean; /** Default value: `80` */ "upperlimit.value": number; /** Default value: `#787B86` */ "lowerlimit.color": string; /** Default value: `2` */ "lowerlimit.linestyle": number; /** Default value: `1` */ "lowerlimit.linewidth": number; /** Default value: `true` */ "lowerlimit.visible": boolean; /** Default value: `20` */ "lowerlimit.value": number; /** Default value: `15` */ "%k.display": number; /** Default value: `0` */ "%k.linestyle": number; /** Default value: `1` */ "%k.linewidth": number; /** Default value: `line` */ "%k.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "%k.trackprice": boolean; /** Default value: `0` */ "%k.transparency": number; /** Default value: `#2196F3` */ "%k.color": string; /** Default value: `15` */ "%d.display": number; /** Default value: `0` */ "%d.linestyle": number; /** Default value: `1` */ "%d.linewidth": number; /** Default value: `line` */ "%d.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "%d.trackprice": boolean; /** Default value: `0` */ "%d.transparency": number; /** Default value: `#FF6D00` */ "%d.color": string; [key: string]: StudyOverrideValueType; } export interface StringInputOptions extends CommonInputOptions { options: TOptions; } /** * 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; } /** * Preferences for adjusting the visual appearance of the background of a band area. */ export interface StudyBandBackgroundPreferences { /** Background color for the Band area */ backgroundColor: string; /** Transparency of the band area */ transparency?: number; /** Whether the background area should be filled with the `backgroundColor` */ fillBackground: boolean; } /** * 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 { /** Input type is BarTime */ readonly type: StudyInputType.BarTime; /** Default value */ readonly defval: number; /** Maximum time */ readonly max: number; /** Minimum time */ 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 { /** Input type is Boolean */ readonly type: StudyInputType.Bool; /** Default value for the input */ 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; } export interface StudyColorInputInfo extends StudyInputBaseInfo { /** Input type is Color */ readonly type: StudyInputType.Color; /** Default value for the input */ 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 { /** Defaults for the area background */ areaBackground: StudyBandBackgroundPreferences; /** Defaults for the bands background */ bandsBackground: StudyBandBackgroundPreferences; /** Defaults for the bands */ bands: readonly Required[]; /** Defaults for the filled area styles */ filledAreasStyle: MappedObject; /** Defaults for the study inputs */ inputs: StudyInputsSimple; /** Defaults for the study palette styles */ palettes: MappedObject; /** Default for the study precision */ precision: number | string; /** Defaults for the study styles */ styles: MappedObject; /** Defaults for the OHLC plots */ ohlcPlots: MappedObject; /** Defaults for the study graphics */ 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; /** * Should the area be filled up to the point that two plots intersect, instead of by plot index? * * Used for plot_plot filled area types. */ readonly fillToIntersection?: boolean; } /** * 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 { /** Defaults for the horizontal lines study graphics */ horizlines?: ValueByStyleId; /** Defaults for the polygon study graphics */ polygons?: ValueByStyleId; /** Defaults for the horizontal histogram study graphics */ hhists?: ValueByStyleId; /** Defaults for the vertical lines study graphics */ vertlines?: ValueByStyleId; } export interface StudyInputBaseInfo { /** Id for the input */ readonly id: string; /** Title of the input */ readonly name: string; /** default value of the input variable. It has the specific type for a given input and can be optional. */ readonly defval?: StudyInputValue; /** Input type */ readonly type: StudyInputType; /** if true, then user will be asked to confirm input value before indicator is added to chart. Default value is false. */ readonly confirm?: boolean; /** Is the input hidden */ readonly isHidden?: boolean; /** Is the input visible */ readonly visible?: string; /** An array of plot ids, upon the hiding of which, this input should also be hidden within the legend */ readonly hideWhenPlotsHidden?: string[]; /** Whether the input should be rendered based on user inputs */ readonly active?: boolean; } /** * 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; /** * If defined, defines the number of bars to plot on chart. */ readonly showLast?: number; } export interface StudyNumericInputInfo extends StudyInputBaseInfo { /** Input type is Numeric */ readonly type: StudyInputType.Integer | StudyInputType.Float | StudyInputType.Price; /** Default value */ readonly defval: number; /** Maximum value */ readonly max?: number; /** Minimum value */ readonly min?: number; /** Step size for value */ 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; /** Visibility */ 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 { /** Title */ readonly title: string; /** Is hidden */ readonly isHidden?: boolean; /** Draw border for OHLC candles */ readonly drawBorder?: boolean; /** Show last value */ readonly showLast?: number; /** * optional flag to indicate the plot should be drawn on main pane */ readonly forceOverlay?: boolean; /** * Info about the Price Scale formatting */ readonly format?: Partial; } /** * Parameter object passed to event callback. */ export interface StudyOrDrawingAddedToChartEventParams { /** * Name of the added study or drawing. */ label: string; /** * Id of the added study or drawing. */ value: string; } /** * Indicator overrides. * See [Indicator Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides). * * Use these properties to specify default indicator style via {@link ChartingLibraryWidgetOptions.studies_overrides} and {@link IChartingLibraryWidget.applyStudiesOverrides}. */ export interface StudyOverrides { /** * - Default value: `close` * - Input type: `text` * - Options: `["close","high"]` */ "52 week high/low.high source": string; /** * - Default value: `close` * - Input type: `text` * - Options: `["close","low"]` */ "52 week high/low.low source": string; /** Default value: `15` */ "accelerator oscillator.plot.display": number; /** Default value: `0` */ "accelerator oscillator.plot.linestyle": number; /** Default value: `1` */ "accelerator oscillator.plot.linewidth": number; /** Default value: `histogram` */ "accelerator oscillator.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "accelerator oscillator.plot.trackprice": boolean; /** Default value: `0` */ "accelerator oscillator.plot.transparency": number; /** Default value: `#000080` */ "accelerator oscillator.plot.color": string; /** Default value: `15` */ "accumulation/distribution.plot.display": number; /** Default value: `0` */ "accumulation/distribution.plot.linestyle": number; /** Default value: `1` */ "accumulation/distribution.plot.linewidth": number; /** Default value: `line` */ "accumulation/distribution.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "accumulation/distribution.plot.trackprice": boolean; /** Default value: `0` */ "accumulation/distribution.plot.transparency": number; /** Default value: `#2196F3` */ "accumulation/distribution.plot.color": string; /** Default value: `15` */ "accumulative swing index.asi.display": number; /** Default value: `0` */ "accumulative swing index.asi.linestyle": number; /** Default value: `1` */ "accumulative swing index.asi.linewidth": number; /** Default value: `line` */ "accumulative swing index.asi.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "accumulative swing index.asi.trackprice": boolean; /** Default value: `0` */ "accumulative swing index.asi.transparency": number; /** Default value: `#2196F3` */ "accumulative swing index.asi.color": string; /** * - Default value: `10` * - Input type: `float` * - Min: `0.1` * - Max: `100000` */ "accumulative swing index.limit move value": number; /** Default value: `15` */ "advance/decline.plot.display": number; /** Default value: `0` */ "advance/decline.plot.linestyle": number; /** Default value: `1` */ "advance/decline.plot.linewidth": number; /** Default value: `line` */ "advance/decline.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "advance/decline.plot.trackprice": boolean; /** Default value: `0` */ "advance/decline.plot.transparency": number; /** Default value: `#2196F3` */ "advance/decline.plot.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "advance/decline.length": number; /** Default value: `#4caf50` */ "anchored vwap.background #1.color": string; /** Default value: `95` */ "anchored vwap.background #1.transparency": number; /** Default value: `true` */ "anchored vwap.background #1.visible": boolean; /** Default value: `15` */ "anchored vwap.vwap.display": number; /** Default value: `#1e88e5` */ "anchored vwap.vwap.color": string; /** Default value: `0` */ "anchored vwap.vwap.linestyle": number; /** Default value: `1` */ "anchored vwap.vwap.linewidth": number; /** Default value: `line` */ "anchored vwap.vwap.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "anchored vwap.vwap.trackprice": boolean; /** Default value: `0` */ "anchored vwap.vwap.transparency": number; /** Default value: `15` */ "anchored vwap.lower band #1.display": number; /** Default value: `#4caf50` */ "anchored vwap.lower band #1.color": string; /** Default value: `0` */ "anchored vwap.lower band #1.linestyle": number; /** Default value: `1` */ "anchored vwap.lower band #1.linewidth": number; /** Default value: `line` */ "anchored vwap.lower band #1.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "anchored vwap.lower band #1.trackprice": boolean; /** Default value: `0` */ "anchored vwap.lower band #1.transparency": number; /** Default value: `15` */ "anchored vwap.lower band #2.display": number; /** Default value: `#808000` */ "anchored vwap.lower band #2.color": string; /** Default value: `0` */ "anchored vwap.lower band #2.linestyle": number; /** Default value: `1` */ "anchored vwap.lower band #2.linewidth": number; /** Default value: `line` */ "anchored vwap.lower band #2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "anchored vwap.lower band #2.trackprice": boolean; /** Default value: `0` */ "anchored vwap.lower band #2.transparency": number; /** Default value: `15` */ "anchored vwap.lower band #3.display": number; /** Default value: `#00897b` */ "anchored vwap.lower band #3.color": string; /** Default value: `0` */ "anchored vwap.lower band #3.linestyle": number; /** Default value: `1` */ "anchored vwap.lower band #3.linewidth": number; /** Default value: `line` */ "anchored vwap.lower band #3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "anchored vwap.lower band #3.trackprice": boolean; /** Default value: `0` */ "anchored vwap.lower band #3.transparency": number; /** Default value: `15` */ "anchored vwap.upper band #1.display": number; /** Default value: `#4caf50` */ "anchored vwap.upper band #1.color": string; /** Default value: `0` */ "anchored vwap.upper band #1.linestyle": number; /** Default value: `1` */ "anchored vwap.upper band #1.linewidth": number; /** Default value: `line` */ "anchored vwap.upper band #1.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "anchored vwap.upper band #1.trackprice": boolean; /** Default value: `0` */ "anchored vwap.upper band #1.transparency": number; /** Default value: `15` */ "anchored vwap.upper band #2.display": number; /** Default value: `#808000` */ "anchored vwap.upper band #2.color": string; /** Default value: `0` */ "anchored vwap.upper band #2.linestyle": number; /** Default value: `1` */ "anchored vwap.upper band #2.linewidth": number; /** Default value: `line` */ "anchored vwap.upper band #2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "anchored vwap.upper band #2.trackprice": boolean; /** Default value: `0` */ "anchored vwap.upper band #2.transparency": number; /** Default value: `15` */ "anchored vwap.upper band #3.display": number; /** Default value: `#00897b` */ "anchored vwap.upper band #3.color": string; /** Default value: `0` */ "anchored vwap.upper band #3.linestyle": number; /** Default value: `1` */ "anchored vwap.upper band #3.linewidth": number; /** Default value: `line` */ "anchored vwap.upper band #3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "anchored vwap.upper band #3.trackprice": boolean; /** Default value: `0` */ "anchored vwap.upper band #3.transparency": number; /** * - Default value: `0` * - Input type: `time` * - IsHidden: `true` * - Max: `9007199254740991` * - Min: `-9007199254740991` */ "anchored vwap.start time": number; /** * - Default value: `Standard Deviation` * - Input type: `text` * - Group: `"Bands Settings"` * - Options: `["Standard Deviation","Percentage"]` * - Tooltip: `"Determines the units used to calculate the distance of the bands. When 'Percentage' is selected, a multiplier of 1 means 1%."` */ "anchored vwap.bands calculation mode": string; /** * - Default value: `1` * - Input type: `float` * - Group: `"Bands Settings"` * - Inline: `"band_1"` * - Max: `1.7976931348623157e+308` * - Min: `0` * - Step: `0.5` */ "anchored vwap.bands multiplier #1": number; /** * - Default value: `2` * - Input type: `float` * - Group: `"Bands Settings"` * - Inline: `"band_2"` * - Max: `1.7976931348623157e+308` * - Min: `0` * - Step: `0.5` */ "anchored vwap.bands multiplier #2": number; /** * - Default value: `3` * - Input type: `float` * - Group: `"Bands Settings"` * - Inline: `"band_3"` * - Max: `1.7976931348623157e+308` * - Min: `0` * - Step: `0.5` */ "anchored vwap.bands multiplier #3": number; /** * - Default value: `false` * - Input type: `bool` * - Group: `"Bands Settings"` * - Inline: `"band_3"` */ "anchored vwap. :input": boolean; /** * - Default value: `hlc3` * - Input type: `source` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "anchored vwap.source": string; /** Default value: `15` */ "arnaud legoux moving average.plot.display": number; /** Default value: `0` */ "arnaud legoux moving average.plot.linestyle": number; /** Default value: `1` */ "arnaud legoux moving average.plot.linewidth": number; /** Default value: `line` */ "arnaud legoux moving average.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "arnaud legoux moving average.plot.trackprice": boolean; /** Default value: `0` */ "arnaud legoux moving average.plot.transparency": number; /** Default value: `#2196F3` */ "arnaud legoux moving average.plot.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `0` * - Max: `5000` */ "arnaud legoux moving average.window size": number; /** * - Default value: `0.85` * - Input type: `float` * - Min: `-1000000000000` * - Max: `1000000000000` */ "arnaud legoux moving average.offset": number; /** * - Default value: `6` * - Input type: `float` * - Min: `-1000000000000` * - Max: `1000000000000` */ "arnaud legoux moving average.sigma": number; /** Default value: `15` */ "aroon.upper.display": number; /** Default value: `0` */ "aroon.upper.linestyle": number; /** Default value: `1` */ "aroon.upper.linewidth": number; /** Default value: `line` */ "aroon.upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "aroon.upper.trackprice": boolean; /** Default value: `0` */ "aroon.upper.transparency": number; /** Default value: `#FB8C00` */ "aroon.upper.color": string; /** Default value: `15` */ "aroon.lower.display": number; /** Default value: `0` */ "aroon.lower.linestyle": number; /** Default value: `1` */ "aroon.lower.linewidth": number; /** Default value: `line` */ "aroon.lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "aroon.lower.trackprice": boolean; /** Default value: `0` */ "aroon.lower.transparency": number; /** Default value: `#2196F3` */ "aroon.lower.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "aroon.length": number; /** Default value: `15` */ "average directional index.adx.display": number; /** Default value: `0` */ "average directional index.adx.linestyle": number; /** Default value: `1` */ "average directional index.adx.linewidth": number; /** Default value: `line` */ "average directional index.adx.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "average directional index.adx.trackprice": boolean; /** Default value: `0` */ "average directional index.adx.transparency": number; /** Default value: `#FF5252` */ "average directional index.adx.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `-1000000000000` * - Max: `1000000000000` */ "average directional index.adx smoothing": number; /** * - Default value: `14` * - Input type: `integer` * - Min: `-1000000000000` * - Max: `1000000000000` */ "average directional index.di length": number; /** Default value: `15` */ "average price.plot.display": number; /** Default value: `0` */ "average price.plot.linestyle": number; /** Default value: `1` */ "average price.plot.linewidth": number; /** Default value: `line` */ "average price.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "average price.plot.trackprice": boolean; /** Default value: `0` */ "average price.plot.transparency": number; /** Default value: `#2196F3` */ "average price.plot.color": string; /** * - Default value: `undefined` * - Input type: `symbol` * - Optional: `true` * - IsHidden: `false` */ "average price.other symbol": string; /** Default value: `15` */ "average true range.plot.display": number; /** Default value: `0` */ "average true range.plot.linestyle": number; /** Default value: `1` */ "average true range.plot.linewidth": number; /** Default value: `line` */ "average true range.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "average true range.plot.trackprice": boolean; /** Default value: `0` */ "average true range.plot.transparency": number; /** Default value: `#801922` */ "average true range.plot.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "average true range.length": number; /** Default value: `15` */ "awesome oscillator.plot.display": number; /** Default value: `0` */ "awesome oscillator.plot.linestyle": number; /** Default value: `1` */ "awesome oscillator.plot.linewidth": number; /** Default value: `histogram` */ "awesome oscillator.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "awesome oscillator.plot.trackprice": boolean; /** Default value: `0` */ "awesome oscillator.plot.transparency": number; /** Default value: `#000080` */ "awesome oscillator.plot.color": string; /** Default value: `15` */ "balance of power.plot.display": number; /** Default value: `0` */ "balance of power.plot.linestyle": number; /** Default value: `1` */ "balance of power.plot.linewidth": number; /** Default value: `line` */ "balance of power.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "balance of power.plot.trackprice": boolean; /** Default value: `0` */ "balance of power.plot.transparency": number; /** Default value: `#FF5252` */ "balance of power.plot.color": string; /** Default value: `#2196F3` */ "bollinger bands.plots background.color": string; /** Default value: `95` */ "bollinger bands.plots background.transparency": number; /** Default value: `true` */ "bollinger bands.plots background.visible": boolean; /** Default value: `0` */ "bollinger bands.median.linestyle": number; /** Default value: `1` */ "bollinger bands.median.linewidth": number; /** Default value: `line` */ "bollinger bands.median.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "bollinger bands.median.trackprice": boolean; /** Default value: `0` */ "bollinger bands.median.transparency": number; /** Default value: `true` */ "bollinger bands.median.visible": boolean; /** Default value: `#FF6D00` */ "bollinger bands.median.color": string; /** Default value: `0` */ "bollinger bands.upper.linestyle": number; /** Default value: `1` */ "bollinger bands.upper.linewidth": number; /** Default value: `line` */ "bollinger bands.upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "bollinger bands.upper.trackprice": boolean; /** Default value: `0` */ "bollinger bands.upper.transparency": number; /** Default value: `true` */ "bollinger bands.upper.visible": boolean; /** Default value: `#2196F3` */ "bollinger bands.upper.color": string; /** Default value: `0` */ "bollinger bands.lower.linestyle": number; /** Default value: `1` */ "bollinger bands.lower.linewidth": number; /** Default value: `line` */ "bollinger bands.lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "bollinger bands.lower.trackprice": boolean; /** Default value: `0` */ "bollinger bands.lower.transparency": number; /** Default value: `true` */ "bollinger bands.lower.visible": boolean; /** Default value: `#2196F3` */ "bollinger bands.lower.color": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "bollinger bands.length": number; /** * - Default value: `2` * - Input type: `float` * - Min: `0.001` * - Max: `50` */ "bollinger bands.mult": number; /** * - Default value: `undefined` * - Input type: `symbol` * - Optional: `true` * - IsHidden: `false` */ "bollinger bands.other symbol": string; /** Default value: `#26A69A` */ "bollinger bands %b.hlines background.color": string; /** Default value: `90` */ "bollinger bands %b.hlines background.transparency": number; /** Default value: `true` */ "bollinger bands %b.hlines background.visible": boolean; /** Default value: `#787B86` */ "bollinger bands %b.upperlimit.color": string; /** Default value: `2` */ "bollinger bands %b.upperlimit.linestyle": number; /** Default value: `1` */ "bollinger bands %b.upperlimit.linewidth": number; /** Default value: `true` */ "bollinger bands %b.upperlimit.visible": boolean; /** Default value: `1` */ "bollinger bands %b.upperlimit.value": number; /** Default value: `#787B86` */ "bollinger bands %b.lowerlimit.color": string; /** Default value: `2` */ "bollinger bands %b.lowerlimit.linestyle": number; /** Default value: `1` */ "bollinger bands %b.lowerlimit.linewidth": number; /** Default value: `true` */ "bollinger bands %b.lowerlimit.visible": boolean; /** Default value: `0` */ "bollinger bands %b.lowerlimit.value": number; /** Default value: `0` */ "bollinger bands %b.plot.linestyle": number; /** Default value: `1` */ "bollinger bands %b.plot.linewidth": number; /** Default value: `line` */ "bollinger bands %b.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "bollinger bands %b.plot.trackprice": boolean; /** Default value: `0` */ "bollinger bands %b.plot.transparency": number; /** Default value: `true` */ "bollinger bands %b.plot.visible": boolean; /** Default value: `#22AB94` */ "bollinger bands %b.plot.color": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "bollinger bands %b.length": number; /** * - Default value: `2` * - Input type: `float` * - Min: `0.001` * - Max: `50` */ "bollinger bands %b.mult": number; /** Default value: `15` */ "bollinger bands width.plot.display": number; /** Default value: `0` */ "bollinger bands width.plot.linestyle": number; /** Default value: `1` */ "bollinger bands width.plot.linewidth": number; /** Default value: `line` */ "bollinger bands width.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "bollinger bands width.plot.trackprice": boolean; /** Default value: `0` */ "bollinger bands width.plot.transparency": number; /** Default value: `#FF6D00` */ "bollinger bands width.plot.color": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "bollinger bands width.length": number; /** * - Default value: `2` * - Input type: `float` * - Min: `0.001` * - Max: `50` */ "bollinger bands width.mult": number; /** Default value: `#787B86` */ "chaikin money flow.zero.color": string; /** Default value: `2` */ "chaikin money flow.zero.linestyle": number; /** Default value: `1` */ "chaikin money flow.zero.linewidth": number; /** Default value: `true` */ "chaikin money flow.zero.visible": boolean; /** Default value: `0` */ "chaikin money flow.zero.value": number; /** Default value: `15` */ "chaikin money flow.plot.display": number; /** Default value: `0` */ "chaikin money flow.plot.linestyle": number; /** Default value: `1` */ "chaikin money flow.plot.linewidth": number; /** Default value: `line` */ "chaikin money flow.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "chaikin money flow.plot.trackprice": boolean; /** Default value: `0` */ "chaikin money flow.plot.transparency": number; /** Default value: `#43A047` */ "chaikin money flow.plot.color": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "chaikin money flow.length": number; /** Default value: `#787B86` */ "chaikin oscillator.zero.color": string; /** Default value: `2` */ "chaikin oscillator.zero.linestyle": number; /** Default value: `1` */ "chaikin oscillator.zero.linewidth": number; /** Default value: `true` */ "chaikin oscillator.zero.visible": boolean; /** Default value: `0` */ "chaikin oscillator.zero.value": number; /** Default value: `15` */ "chaikin oscillator.plot.display": number; /** Default value: `0` */ "chaikin oscillator.plot.linestyle": number; /** Default value: `1` */ "chaikin oscillator.plot.linewidth": number; /** Default value: `line` */ "chaikin oscillator.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "chaikin oscillator.plot.trackprice": boolean; /** Default value: `0` */ "chaikin oscillator.plot.transparency": number; /** Default value: `#EC407A` */ "chaikin oscillator.plot.color": string; /** * - Default value: `3` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "chaikin oscillator.short": number; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "chaikin oscillator.long": number; /** Default value: `#787B86` */ "chaikin volatility.zero.color": string; /** Default value: `2` */ "chaikin volatility.zero.linestyle": number; /** Default value: `1` */ "chaikin volatility.zero.linewidth": number; /** Default value: `true` */ "chaikin volatility.zero.visible": boolean; /** Default value: `0` */ "chaikin volatility.zero.value": number; /** Default value: `15` */ "chaikin volatility.plot.display": number; /** Default value: `0` */ "chaikin volatility.plot.linestyle": number; /** Default value: `1` */ "chaikin volatility.plot.linewidth": number; /** Default value: `line` */ "chaikin volatility.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "chaikin volatility.plot.trackprice": boolean; /** Default value: `0` */ "chaikin volatility.plot.transparency": number; /** Default value: `#AB47BC` */ "chaikin volatility.plot.color": string; /** * - Default value: `10` * - Input type: `integer` */ "chaikin volatility.periods": number; /** * - Default value: `10` * - Input type: `integer` */ "chaikin volatility.rate of change lookback": number; /** Default value: `15` */ "chande kroll stop.long.display": number; /** Default value: `0` */ "chande kroll stop.long.linestyle": number; /** Default value: `1` */ "chande kroll stop.long.linewidth": number; /** Default value: `line` */ "chande kroll stop.long.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "chande kroll stop.long.trackprice": boolean; /** Default value: `0` */ "chande kroll stop.long.transparency": number; /** Default value: `#2196F3` */ "chande kroll stop.long.color": string; /** Default value: `15` */ "chande kroll stop.short.display": number; /** Default value: `0` */ "chande kroll stop.short.linestyle": number; /** Default value: `1` */ "chande kroll stop.short.linewidth": number; /** Default value: `line` */ "chande kroll stop.short.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "chande kroll stop.short.trackprice": boolean; /** Default value: `0` */ "chande kroll stop.short.transparency": number; /** Default value: `#FF6D00` */ "chande kroll stop.short.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `4999` */ "chande kroll stop.p": number; /** * - Default value: `1` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "chande kroll stop.x": number; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "chande kroll stop.q": number; /** Default value: `15` */ "chande momentum oscillator.plot.display": number; /** Default value: `0` */ "chande momentum oscillator.plot.linestyle": number; /** Default value: `1` */ "chande momentum oscillator.plot.linewidth": number; /** Default value: `line` */ "chande momentum oscillator.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "chande momentum oscillator.plot.trackprice": boolean; /** Default value: `0` */ "chande momentum oscillator.plot.transparency": number; /** Default value: `#2196F3` */ "chande momentum oscillator.plot.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "chande momentum oscillator.length": number; /** Default value: `15` */ "chop zone.plot.display": number; /** Default value: `0` */ "chop zone.plot.linestyle": number; /** Default value: `1` */ "chop zone.plot.linewidth": number; /** Default value: `columns` */ "chop zone.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "chop zone.plot.trackprice": boolean; /** Default value: `0` */ "chop zone.plot.transparency": number; /** Default value: `#000080` */ "chop zone.plot.color": string; /** Default value: `#2196F3` */ "choppiness index.hlines background.color": string; /** Default value: `90` */ "choppiness index.hlines background.transparency": number; /** Default value: `true` */ "choppiness index.hlines background.visible": boolean; /** Default value: `#787B86` */ "choppiness index.upperlimit.color": string; /** Default value: `2` */ "choppiness index.upperlimit.linestyle": number; /** Default value: `1` */ "choppiness index.upperlimit.linewidth": number; /** Default value: `true` */ "choppiness index.upperlimit.visible": boolean; /** Default value: `61.8` */ "choppiness index.upperlimit.value": number; /** Default value: `#787B86` */ "choppiness index.lowerlimit.color": string; /** Default value: `2` */ "choppiness index.lowerlimit.linestyle": number; /** Default value: `1` */ "choppiness index.lowerlimit.linewidth": number; /** Default value: `true` */ "choppiness index.lowerlimit.visible": boolean; /** Default value: `38.2` */ "choppiness index.lowerlimit.value": number; /** Default value: `15` */ "choppiness index.plot.display": number; /** Default value: `0` */ "choppiness index.plot.linestyle": number; /** Default value: `1` */ "choppiness index.plot.linewidth": number; /** Default value: `line` */ "choppiness index.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "choppiness index.plot.trackprice": boolean; /** Default value: `0` */ "choppiness index.plot.transparency": number; /** Default value: `#2196F3` */ "choppiness index.plot.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "choppiness index.length": number; /** Default value: `#2196F3` */ "commodity channel index.hlines background.color": string; /** Default value: `90` */ "commodity channel index.hlines background.transparency": number; /** Default value: `true` */ "commodity channel index.hlines background.visible": boolean; /** Default value: `#787B86` */ "commodity channel index.upperlimit.color": string; /** Default value: `2` */ "commodity channel index.upperlimit.linestyle": number; /** Default value: `1` */ "commodity channel index.upperlimit.linewidth": number; /** Default value: `true` */ "commodity channel index.upperlimit.visible": boolean; /** Default value: `100` */ "commodity channel index.upperlimit.value": number; /** Default value: `#787B86` */ "commodity channel index.lowerlimit.color": string; /** Default value: `2` */ "commodity channel index.lowerlimit.linestyle": number; /** Default value: `1` */ "commodity channel index.lowerlimit.linewidth": number; /** Default value: `true` */ "commodity channel index.lowerlimit.visible": boolean; /** Default value: `-100` */ "commodity channel index.lowerlimit.value": number; /** Default value: `15` */ "commodity channel index.plot.display": number; /** Default value: `0` */ "commodity channel index.plot.linestyle": number; /** Default value: `1` */ "commodity channel index.plot.linewidth": number; /** Default value: `line` */ "commodity channel index.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "commodity channel index.plot.trackprice": boolean; /** Default value: `0` */ "commodity channel index.plot.transparency": number; /** Default value: `#2196F3` */ "commodity channel index.plot.color": string; /** Default value: `0` */ "commodity channel index.smoothed ma.display": number; /** Default value: `0` */ "commodity channel index.smoothed ma.linestyle": number; /** Default value: `1` */ "commodity channel index.smoothed ma.linewidth": number; /** Default value: `line` */ "commodity channel index.smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "commodity channel index.smoothed ma.trackprice": boolean; /** Default value: `0` */ "commodity channel index.smoothed ma.transparency": number; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "commodity channel index.length": number; /** * - Default value: `SMA` * - Input type: `text` * - Options: `["SMA","EMA","WMA"]` */ "commodity channel index.smoothing line": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "commodity channel index.smoothing length": number; /** Default value: `15` */ "compare.plot.display": number; /** Default value: `0` */ "compare.plot.linestyle": number; /** Default value: `2` */ "compare.plot.linewidth": number; /** Default value: `line` */ "compare.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "compare.plot.trackprice": boolean; /** Default value: `0` */ "compare.plot.transparency": number; /** Default value: `#9C27B0` */ "compare.plot.color": string; /** * - Default value: `close` * - Input type: `text` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "compare.source": string; /** * - Default value: `undefined` * - Input type: `symbol` * - IsHidden: `true` */ "compare.symbol": string; /** Default value: `#2196F3` */ "connors rsi.hlines background.color": string; /** Default value: `90` */ "connors rsi.hlines background.transparency": number; /** Default value: `true` */ "connors rsi.hlines background.visible": boolean; /** Default value: `#787B86` */ "connors rsi.upperlimit.color": string; /** Default value: `2` */ "connors rsi.upperlimit.linestyle": number; /** Default value: `1` */ "connors rsi.upperlimit.linewidth": number; /** Default value: `true` */ "connors rsi.upperlimit.visible": boolean; /** Default value: `70` */ "connors rsi.upperlimit.value": number; /** Default value: `#787B86` */ "connors rsi.lowerlimit.color": string; /** Default value: `2` */ "connors rsi.lowerlimit.linestyle": number; /** Default value: `1` */ "connors rsi.lowerlimit.linewidth": number; /** Default value: `true` */ "connors rsi.lowerlimit.visible": boolean; /** Default value: `30` */ "connors rsi.lowerlimit.value": number; /** Default value: `15` */ "connors rsi.crsi.display": number; /** Default value: `0` */ "connors rsi.crsi.linestyle": number; /** Default value: `1` */ "connors rsi.crsi.linewidth": number; /** Default value: `line` */ "connors rsi.crsi.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "connors rsi.crsi.trackprice": boolean; /** Default value: `0` */ "connors rsi.crsi.transparency": number; /** Default value: `#2196F3` */ "connors rsi.crsi.color": string; /** * - Default value: `3` * - Input type: `integer` * - Min: `1` */ "connors rsi.rsi length": number; /** * - Default value: `2` * - Input type: `integer` * - Min: `1` */ "connors rsi.updown length": number; /** * - Default value: `100` * - Input type: `integer` * - Min: `1` */ "connors rsi.roc length": number; /** Default value: `15` */ "coppock curve.plot.display": number; /** Default value: `0` */ "coppock curve.plot.linestyle": number; /** Default value: `1` */ "coppock curve.plot.linewidth": number; /** Default value: `line` */ "coppock curve.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "coppock curve.plot.trackprice": boolean; /** Default value: `0` */ "coppock curve.plot.transparency": number; /** Default value: `#2196F3` */ "coppock curve.plot.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `-1000000000000` * - Max: `5000` */ "coppock curve.wma length": number; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `4999` */ "coppock curve.long roc length": number; /** * - Default value: `11` * - Input type: `integer` * - Min: `1` * - Max: `4999` */ "coppock curve.short roc length": number; /** Default value: `15` */ "correlation - log.plot.display": number; /** Default value: `0` */ "correlation - log.plot.linestyle": number; /** Default value: `1` */ "correlation - log.plot.linewidth": number; /** Default value: `line` */ "correlation - log.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "correlation - log.plot.trackprice": boolean; /** Default value: `0` */ "correlation - log.plot.transparency": number; /** Default value: `#2196F3` */ "correlation - log.plot.color": string; /** * - Default value: `undefined` * - Input type: `symbol` * - Confirm: `true` */ "correlation - log.instrument 1": string; /** * - Default value: `undefined` * - Input type: `symbol` * - Confirm: `true` */ "correlation - log.instrument 2": string; /** * - Default value: `25` * - Input type: `integer` */ "correlation - log.periods": number; /** Default value: `15` */ "correlation coefficient.plot.display": number; /** Default value: `0` */ "correlation coefficient.plot.linestyle": number; /** Default value: `1` */ "correlation coefficient.plot.linewidth": number; /** Default value: `area` */ "correlation coefficient.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "correlation coefficient.plot.trackprice": boolean; /** Default value: `0` */ "correlation coefficient.plot.transparency": number; /** Default value: `#2196F3` */ "correlation coefficient.plot.color": string; /** * - Default value: `undefined` * - Input type: `symbol` */ "correlation coefficient.sym": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "correlation coefficient.length": number; /** Default value: `#787B86` */ "detrended price oscillator.zero.color": string; /** Default value: `2` */ "detrended price oscillator.zero.linestyle": number; /** Default value: `1` */ "detrended price oscillator.zero.linewidth": number; /** Default value: `true` */ "detrended price oscillator.zero.visible": boolean; /** Default value: `0` */ "detrended price oscillator.zero.value": number; /** Default value: `15` */ "detrended price oscillator.dpo.display": number; /** Default value: `0` */ "detrended price oscillator.dpo.linestyle": number; /** Default value: `1` */ "detrended price oscillator.dpo.linewidth": number; /** Default value: `line` */ "detrended price oscillator.dpo.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "detrended price oscillator.dpo.trackprice": boolean; /** Default value: `0` */ "detrended price oscillator.dpo.transparency": number; /** Default value: `#43A047` */ "detrended price oscillator.dpo.color": string; /** * - Default value: `21` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "detrended price oscillator.period": number; /** * - Default value: `false` * - Input type: `bool` */ "detrended price oscillator.iscentered": boolean; /** Default value: `15` */ "directional movement.+di.display": number; /** Default value: `0` */ "directional movement.+di.linestyle": number; /** Default value: `1` */ "directional movement.+di.linewidth": number; /** Default value: `line` */ "directional movement.+di.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "directional movement.+di.trackprice": boolean; /** Default value: `0` */ "directional movement.+di.transparency": number; /** Default value: `#2196F3` */ "directional movement.+di.color": string; /** Default value: `15` */ "directional movement.-di.display": number; /** Default value: `0` */ "directional movement.-di.linestyle": number; /** Default value: `1` */ "directional movement.-di.linewidth": number; /** Default value: `line` */ "directional movement.-di.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "directional movement.-di.trackprice": boolean; /** Default value: `0` */ "directional movement.-di.transparency": number; /** Default value: `#FF6D00` */ "directional movement.-di.color": string; /** Default value: `15` */ "directional movement.adx.display": number; /** Default value: `0` */ "directional movement.adx.linestyle": number; /** Default value: `1` */ "directional movement.adx.linewidth": number; /** Default value: `line` */ "directional movement.adx.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "directional movement.adx.trackprice": boolean; /** Default value: `0` */ "directional movement.adx.transparency": number; /** Default value: `#F50057` */ "directional movement.adx.color": string; /** Default value: `15` */ "directional movement.dx.display": number; /** Default value: `0` */ "directional movement.dx.linestyle": number; /** Default value: `1` */ "directional movement.dx.linewidth": number; /** Default value: `line` */ "directional movement.dx.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "directional movement.dx.trackprice": boolean; /** Default value: `0` */ "directional movement.dx.transparency": number; /** Default value: `#FFA726` */ "directional movement.dx.color": string; /** Default value: `15` */ "directional movement.adxr.display": number; /** Default value: `0` */ "directional movement.adxr.linestyle": number; /** Default value: `1` */ "directional movement.adxr.linewidth": number; /** Default value: `line` */ "directional movement.adxr.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "directional movement.adxr.trackprice": boolean; /** Default value: `0` */ "directional movement.adxr.transparency": number; /** Default value: `#ab47bc` */ "directional movement.adxr.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "directional movement.di length": number; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `50` */ "directional movement.adx smoothing": number; /** Default value: `#2196F3` */ "donchian channels.plots background.color": string; /** Default value: `95` */ "donchian channels.plots background.transparency": number; /** Default value: `true` */ "donchian channels.plots background.visible": boolean; /** Default value: `15` */ "donchian channels.lower.display": number; /** Default value: `0` */ "donchian channels.lower.linestyle": number; /** Default value: `1` */ "donchian channels.lower.linewidth": number; /** Default value: `line` */ "donchian channels.lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "donchian channels.lower.trackprice": boolean; /** Default value: `0` */ "donchian channels.lower.transparency": number; /** Default value: `#2196F3` */ "donchian channels.lower.color": string; /** Default value: `15` */ "donchian channels.upper.display": number; /** Default value: `0` */ "donchian channels.upper.linestyle": number; /** Default value: `1` */ "donchian channels.upper.linewidth": number; /** Default value: `line` */ "donchian channels.upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "donchian channels.upper.trackprice": boolean; /** Default value: `0` */ "donchian channels.upper.transparency": number; /** Default value: `#2196F3` */ "donchian channels.upper.color": string; /** Default value: `15` */ "donchian channels.basis.display": number; /** Default value: `0` */ "donchian channels.basis.linestyle": number; /** Default value: `1` */ "donchian channels.basis.linewidth": number; /** Default value: `line` */ "donchian channels.basis.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "donchian channels.basis.trackprice": boolean; /** Default value: `0` */ "donchian channels.basis.transparency": number; /** Default value: `#FF6D00` */ "donchian channels.basis.color": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "donchian channels.length": number; /** * - Default value: `0` * - Input type: `integer` * - Min: `-1000` * - Max: `1000` */ "donchian channels.offset": number; /** Default value: `15` */ "double ema.plot.display": number; /** Default value: `0` */ "double ema.plot.linestyle": number; /** Default value: `1` */ "double ema.plot.linewidth": number; /** Default value: `line` */ "double ema.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "double ema.plot.trackprice": boolean; /** Default value: `0` */ "double ema.plot.transparency": number; /** Default value: `#43A047` */ "double ema.plot.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "double ema.length": number; /** Default value: `15` */ "ema cross.short:plot.display": number; /** Default value: `0` */ "ema cross.short:plot.linestyle": number; /** Default value: `1` */ "ema cross.short:plot.linewidth": number; /** Default value: `line` */ "ema cross.short:plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ema cross.short:plot.trackprice": boolean; /** Default value: `0` */ "ema cross.short:plot.transparency": number; /** Default value: `#FF6D00` */ "ema cross.short:plot.color": string; /** Default value: `15` */ "ema cross.long:plot.display": number; /** Default value: `0` */ "ema cross.long:plot.linestyle": number; /** Default value: `1` */ "ema cross.long:plot.linewidth": number; /** Default value: `line` */ "ema cross.long:plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ema cross.long:plot.trackprice": boolean; /** Default value: `0` */ "ema cross.long:plot.transparency": number; /** Default value: `#43A047` */ "ema cross.long:plot.color": string; /** Default value: `15` */ "ema cross.crosses.display": number; /** Default value: `0` */ "ema cross.crosses.linestyle": number; /** Default value: `4` */ "ema cross.crosses.linewidth": number; /** Default value: `cross` */ "ema cross.crosses.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ema cross.crosses.trackprice": boolean; /** Default value: `0` */ "ema cross.crosses.transparency": number; /** Default value: `#2196F3` */ "ema cross.crosses.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "ema cross.short:input": number; /** * - Default value: `26` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "ema cross.long:input": number; /** Default value: `15` */ "ease of movement.plot.display": number; /** Default value: `0` */ "ease of movement.plot.linestyle": number; /** Default value: `1` */ "ease of movement.plot.linewidth": number; /** Default value: `line` */ "ease of movement.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ease of movement.plot.trackprice": boolean; /** Default value: `0` */ "ease of movement.plot.transparency": number; /** Default value: `#43A047` */ "ease of movement.plot.color": string; /** * - Default value: `10000` * - Input type: `integer` * - Min: `1` * - Max: `1000000000` */ "ease of movement.divisor": number; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "ease of movement.length": number; /** Default value: `#787B86` */ "elder's force index.zero.color": string; /** Default value: `2` */ "elder's force index.zero.linestyle": number; /** Default value: `1` */ "elder's force index.zero.linewidth": number; /** Default value: `true` */ "elder's force index.zero.visible": boolean; /** Default value: `0` */ "elder's force index.zero.value": number; /** Default value: `15` */ "elder's force index.plot.display": number; /** Default value: `0` */ "elder's force index.plot.linestyle": number; /** Default value: `1` */ "elder's force index.plot.linewidth": number; /** Default value: `line` */ "elder's force index.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "elder's force index.plot.trackprice": boolean; /** Default value: `0` */ "elder's force index.plot.transparency": number; /** Default value: `#F23645` */ "elder's force index.plot.color": string; /** * - Default value: `13` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "elder's force index.length": number; /** Default value: `#2196F3` */ "envelopes.plots background.color": string; /** Default value: `95` */ "envelopes.plots background.transparency": number; /** Default value: `true` */ "envelopes.plots background.visible": boolean; /** Default value: `15` */ "envelopes.average.display": number; /** Default value: `0` */ "envelopes.average.linestyle": number; /** Default value: `1` */ "envelopes.average.linewidth": number; /** Default value: `line` */ "envelopes.average.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "envelopes.average.trackprice": boolean; /** Default value: `0` */ "envelopes.average.transparency": number; /** Default value: `#FF6D00` */ "envelopes.average.color": string; /** Default value: `15` */ "envelopes.upper.display": number; /** Default value: `0` */ "envelopes.upper.linestyle": number; /** Default value: `1` */ "envelopes.upper.linewidth": number; /** Default value: `line` */ "envelopes.upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "envelopes.upper.trackprice": boolean; /** Default value: `0` */ "envelopes.upper.transparency": number; /** Default value: `#2196F3` */ "envelopes.upper.color": string; /** Default value: `15` */ "envelopes.lower.display": number; /** Default value: `0` */ "envelopes.lower.linestyle": number; /** Default value: `1` */ "envelopes.lower.linewidth": number; /** Default value: `line` */ "envelopes.lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "envelopes.lower.trackprice": boolean; /** Default value: `0` */ "envelopes.lower.transparency": number; /** Default value: `#2196F3` */ "envelopes.lower.color": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "envelopes.length": number; /** * - Default value: `10` * - Input type: `float` * - Min: `0` */ "envelopes.upper percentage": number; /** * - Default value: `10` * - Input type: `float` * - Min: `0` */ "envelopes.lower percentage": number; /** * - Default value: `Simple` * - Input type: `text` * - Options: `["Simple","Exponential","Weighted"]` */ "envelopes.method": string; /** * - Default value: `close` * - Input type: `source` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "envelopes.source": string; /** Default value: `#E91E63` */ "fisher transform.level:band.color": string; /** Default value: `2` */ "fisher transform.level:band.linestyle": number; /** Default value: `1` */ "fisher transform.level:band.linewidth": number; /** Default value: `true` */ "fisher transform.level:band.visible": boolean; /** Default value: `-1.5` */ "fisher transform.level:band.value": number; /** Default value: `15` */ "fisher transform.fisher.display": number; /** Default value: `0` */ "fisher transform.fisher.linestyle": number; /** Default value: `1` */ "fisher transform.fisher.linewidth": number; /** Default value: `line` */ "fisher transform.fisher.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "fisher transform.fisher.trackprice": boolean; /** Default value: `0` */ "fisher transform.fisher.transparency": number; /** Default value: `#2196F3` */ "fisher transform.fisher.color": string; /** Default value: `15` */ "fisher transform.trigger.display": number; /** Default value: `0` */ "fisher transform.trigger.linestyle": number; /** Default value: `1` */ "fisher transform.trigger.linewidth": number; /** Default value: `line` */ "fisher transform.trigger.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "fisher transform.trigger.trackprice": boolean; /** Default value: `0` */ "fisher transform.trigger.transparency": number; /** Default value: `#FF6D00` */ "fisher transform.trigger.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "fisher transform.length": number; /** Default value: `undefined` */ "fixed range.developing poc.color": string; /** Default value: `0` */ "fixed range.developing poc.linestyle": number; /** Default value: `1` */ "fixed range.developing poc.linewidth": number; /** Default value: `step_line` */ "fixed range.developing poc.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "fixed range.developing poc.trackprice": boolean; /** Default value: `0` */ "fixed range.developing poc.transparency": number; /** Default value: `0` */ "fixed range.developing poc.display": number; /** Default value: `undefined` */ "fixed range.developing va high.color": string; /** Default value: `0` */ "fixed range.developing va high.linestyle": number; /** Default value: `1` */ "fixed range.developing va high.linewidth": number; /** Default value: `step_line` */ "fixed range.developing va high.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "fixed range.developing va high.trackprice": boolean; /** Default value: `0` */ "fixed range.developing va high.transparency": number; /** Default value: `0` */ "fixed range.developing va high.display": number; /** Default value: `undefined` */ "fixed range.developing va low.color": string; /** Default value: `0` */ "fixed range.developing va low.linestyle": number; /** Default value: `1` */ "fixed range.developing va low.linewidth": number; /** Default value: `step_line` */ "fixed range.developing va low.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "fixed range.developing va low.trackprice": boolean; /** Default value: `0` */ "fixed range.developing va low.transparency": number; /** Default value: `0` */ "fixed range.developing va low.display": number; /** * - Default value: `0` * - Input type: `time` * - IsHidden: `true` * - Max: `253370764800` * - Min: `-253370764800` */ "fixed range.first bar time": number; /** * - Default value: `0` * - Input type: `time` * - IsHidden: `true` * - Max: `253370764800` * - Min: `-253370764800` */ "fixed range.last bar time": number; /** * - Default value: `24` * - Input type: `integer` * - Max: `1000000` * - Min: `1` */ "fixed range.row size": number; /** * - Default value: `Number Of Rows` * - Input type: `text` * - Options: `["Number Of Rows","Ticks Per Row"]` */ "fixed range.rows layout": string; /** * - Default value: `true` * - Input type: `bool` * - IsHidden: `true` */ "fixed range.subscriberealtime": boolean; /** * - Default value: `70` * - Input type: `integer` * - Max: `100` * - Min: `0` */ "fixed range.value area volume": number; /** * - Default value: `Up/Down` * - Input type: `text` * - Options: `["Up/Down","Total","Delta"]` */ "fixed range.volume": string; /** Default value: `15` */ "guppy multiple moving average.trader ema 1.display": number; /** Default value: `#00FFFF` */ "guppy multiple moving average.trader ema 1.color": string; /** Default value: `0` */ "guppy multiple moving average.trader ema 1.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.trader ema 1.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.trader ema 1.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.trader ema 1.trackprice": boolean; /** Default value: `15` */ "guppy multiple moving average.trader ema 1.transparency": number; /** Default value: `15` */ "guppy multiple moving average.trader ema 2.display": number; /** Default value: `#00FFFF` */ "guppy multiple moving average.trader ema 2.color": string; /** Default value: `0` */ "guppy multiple moving average.trader ema 2.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.trader ema 2.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.trader ema 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.trader ema 2.trackprice": boolean; /** Default value: `12` */ "guppy multiple moving average.trader ema 2.transparency": number; /** Default value: `15` */ "guppy multiple moving average.trader ema 3.display": number; /** Default value: `#00FFFF` */ "guppy multiple moving average.trader ema 3.color": string; /** Default value: `0` */ "guppy multiple moving average.trader ema 3.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.trader ema 3.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.trader ema 3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.trader ema 3.trackprice": boolean; /** Default value: `9` */ "guppy multiple moving average.trader ema 3.transparency": number; /** Default value: `15` */ "guppy multiple moving average.trader ema 4.display": number; /** Default value: `#00FFFF` */ "guppy multiple moving average.trader ema 4.color": string; /** Default value: `0` */ "guppy multiple moving average.trader ema 4.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.trader ema 4.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.trader ema 4.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.trader ema 4.trackprice": boolean; /** Default value: `6` */ "guppy multiple moving average.trader ema 4.transparency": number; /** Default value: `15` */ "guppy multiple moving average.trader ema 5.display": number; /** Default value: `#00FFFF` */ "guppy multiple moving average.trader ema 5.color": string; /** Default value: `0` */ "guppy multiple moving average.trader ema 5.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.trader ema 5.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.trader ema 5.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.trader ema 5.trackprice": boolean; /** Default value: `3` */ "guppy multiple moving average.trader ema 5.transparency": number; /** Default value: `15` */ "guppy multiple moving average.trader ema 6.display": number; /** Default value: `#00FFFF` */ "guppy multiple moving average.trader ema 6.color": string; /** Default value: `0` */ "guppy multiple moving average.trader ema 6.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.trader ema 6.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.trader ema 6.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.trader ema 6.trackprice": boolean; /** Default value: `0` */ "guppy multiple moving average.trader ema 6.transparency": number; /** Default value: `15` */ "guppy multiple moving average.investor ema 1.display": number; /** Default value: `#FF0000` */ "guppy multiple moving average.investor ema 1.color": string; /** Default value: `0` */ "guppy multiple moving average.investor ema 1.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.investor ema 1.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.investor ema 1.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.investor ema 1.trackprice": boolean; /** Default value: `15` */ "guppy multiple moving average.investor ema 1.transparency": number; /** Default value: `15` */ "guppy multiple moving average.investor ema 2.display": number; /** Default value: `#FF0000` */ "guppy multiple moving average.investor ema 2.color": string; /** Default value: `0` */ "guppy multiple moving average.investor ema 2.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.investor ema 2.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.investor ema 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.investor ema 2.trackprice": boolean; /** Default value: `12` */ "guppy multiple moving average.investor ema 2.transparency": number; /** Default value: `15` */ "guppy multiple moving average.investor ema 3.display": number; /** Default value: `#FF0000` */ "guppy multiple moving average.investor ema 3.color": string; /** Default value: `0` */ "guppy multiple moving average.investor ema 3.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.investor ema 3.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.investor ema 3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.investor ema 3.trackprice": boolean; /** Default value: `9` */ "guppy multiple moving average.investor ema 3.transparency": number; /** Default value: `15` */ "guppy multiple moving average.investor ema 4.display": number; /** Default value: `#FF0000` */ "guppy multiple moving average.investor ema 4.color": string; /** Default value: `0` */ "guppy multiple moving average.investor ema 4.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.investor ema 4.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.investor ema 4.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.investor ema 4.trackprice": boolean; /** Default value: `6` */ "guppy multiple moving average.investor ema 4.transparency": number; /** Default value: `15` */ "guppy multiple moving average.investor ema 5.display": number; /** Default value: `#FF0000` */ "guppy multiple moving average.investor ema 5.color": string; /** Default value: `0` */ "guppy multiple moving average.investor ema 5.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.investor ema 5.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.investor ema 5.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.investor ema 5.trackprice": boolean; /** Default value: `3` */ "guppy multiple moving average.investor ema 5.transparency": number; /** Default value: `15` */ "guppy multiple moving average.investor ema 6.display": number; /** Default value: `#FF0000` */ "guppy multiple moving average.investor ema 6.color": string; /** Default value: `0` */ "guppy multiple moving average.investor ema 6.linestyle": number; /** Default value: `1` */ "guppy multiple moving average.investor ema 6.linewidth": number; /** Default value: `line` */ "guppy multiple moving average.investor ema 6.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "guppy multiple moving average.investor ema 6.trackprice": boolean; /** Default value: `0` */ "guppy multiple moving average.investor ema 6.transparency": number; /** * - Default value: `3` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.trader ema 1 length": number; /** * - Default value: `5` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.trader ema 2 length": number; /** * - Default value: `8` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.trader ema 3 length": number; /** * - Default value: `10` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.trader ema 4 length": number; /** * - Default value: `12` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.trader ema 5 length": number; /** * - Default value: `15` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.trader ema 6 length": number; /** * - Default value: `30` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.investor ema 1 length": number; /** * - Default value: `35` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.investor ema 2 length": number; /** * - Default value: `40` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.investor ema 3 length": number; /** * - Default value: `45` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.investor ema 4 length": number; /** * - Default value: `50` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.investor ema 5 length": number; /** * - Default value: `60` * - Input type: `integer` * - Max: `1000` * - Min: `1` */ "guppy multiple moving average.investor ema 6 length": number; /** Default value: `15` */ "historical volatility.plot.display": number; /** Default value: `0` */ "historical volatility.plot.linestyle": number; /** Default value: `1` */ "historical volatility.plot.linewidth": number; /** Default value: `line` */ "historical volatility.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "historical volatility.plot.trackprice": boolean; /** Default value: `0` */ "historical volatility.plot.transparency": number; /** Default value: `#2196F3` */ "historical volatility.plot.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "historical volatility.length": number; /** Default value: `15` */ "hull moving average.plot.display": number; /** Default value: `0` */ "hull moving average.plot.linestyle": number; /** Default value: `1` */ "hull moving average.plot.linewidth": number; /** Default value: `line` */ "hull moving average.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "hull moving average.plot.trackprice": boolean; /** Default value: `0` */ "hull moving average.plot.transparency": number; /** Default value: `#2196F3` */ "hull moving average.plot.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "hull moving average.length": number; /** Default value: `#000080` */ "ichimoku cloud.plots background.color": string; /** Default value: `90` */ "ichimoku cloud.plots background.transparency": number; /** Default value: `true` */ "ichimoku cloud.plots background.visible": boolean; /** Default value: `15` */ "ichimoku cloud.conversion line.display": number; /** Default value: `0` */ "ichimoku cloud.conversion line.linestyle": number; /** Default value: `1` */ "ichimoku cloud.conversion line.linewidth": number; /** Default value: `line` */ "ichimoku cloud.conversion line.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ichimoku cloud.conversion line.trackprice": boolean; /** Default value: `0` */ "ichimoku cloud.conversion line.transparency": number; /** Default value: `#2196F3` */ "ichimoku cloud.conversion line.color": string; /** Default value: `15` */ "ichimoku cloud.base line.display": number; /** Default value: `0` */ "ichimoku cloud.base line.linestyle": number; /** Default value: `1` */ "ichimoku cloud.base line.linewidth": number; /** Default value: `line` */ "ichimoku cloud.base line.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ichimoku cloud.base line.trackprice": boolean; /** Default value: `0` */ "ichimoku cloud.base line.transparency": number; /** Default value: `#801922` */ "ichimoku cloud.base line.color": string; /** Default value: `15` */ "ichimoku cloud.lagging span.display": number; /** Default value: `0` */ "ichimoku cloud.lagging span.linestyle": number; /** Default value: `1` */ "ichimoku cloud.lagging span.linewidth": number; /** Default value: `line` */ "ichimoku cloud.lagging span.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ichimoku cloud.lagging span.trackprice": boolean; /** Default value: `0` */ "ichimoku cloud.lagging span.transparency": number; /** Default value: `#43A047` */ "ichimoku cloud.lagging span.color": string; /** Default value: `15` */ "ichimoku cloud.leading span a.display": number; /** Default value: `0` */ "ichimoku cloud.leading span a.linestyle": number; /** Default value: `1` */ "ichimoku cloud.leading span a.linewidth": number; /** Default value: `line` */ "ichimoku cloud.leading span a.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ichimoku cloud.leading span a.trackprice": boolean; /** Default value: `0` */ "ichimoku cloud.leading span a.transparency": number; /** Default value: `#A5D6A7` */ "ichimoku cloud.leading span a.color": string; /** Default value: `15` */ "ichimoku cloud.leading span b.display": number; /** Default value: `0` */ "ichimoku cloud.leading span b.linestyle": number; /** Default value: `1` */ "ichimoku cloud.leading span b.linewidth": number; /** Default value: `line` */ "ichimoku cloud.leading span b.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ichimoku cloud.leading span b.trackprice": boolean; /** Default value: `0` */ "ichimoku cloud.leading span b.transparency": number; /** Default value: `#FAA1A4` */ "ichimoku cloud.leading span b.color": string; /** * - Default value: `undefined` * - Input type: `symbol` * - Optional: `true` * - IsHidden: `false` */ "ichimoku cloud.another symbol": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "ichimoku cloud.conversion line periods": number; /** * - Default value: `26` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "ichimoku cloud.base line periods": number; /** * - Default value: `52` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "ichimoku cloud.leading span periods": number; /** * - Default value: `26` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "ichimoku cloud.lagging span periods": number; /** * - Default value: `26` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "ichimoku cloud.leading shift periods": number; /** Default value: `#2196F3` */ "keltner channels.plots background.color": string; /** Default value: `95` */ "keltner channels.plots background.transparency": number; /** Default value: `true` */ "keltner channels.plots background.visible": boolean; /** Default value: `15` */ "keltner channels.upper.display": number; /** Default value: `0` */ "keltner channels.upper.linestyle": number; /** Default value: `1` */ "keltner channels.upper.linewidth": number; /** Default value: `line` */ "keltner channels.upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "keltner channels.upper.trackprice": boolean; /** Default value: `0` */ "keltner channels.upper.transparency": number; /** Default value: `#2196F3` */ "keltner channels.upper.color": string; /** Default value: `15` */ "keltner channels.middle.display": number; /** Default value: `0` */ "keltner channels.middle.linestyle": number; /** Default value: `1` */ "keltner channels.middle.linewidth": number; /** Default value: `line` */ "keltner channels.middle.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "keltner channels.middle.trackprice": boolean; /** Default value: `0` */ "keltner channels.middle.transparency": number; /** Default value: `#2196F3` */ "keltner channels.middle.color": string; /** Default value: `15` */ "keltner channels.lower.display": number; /** Default value: `0` */ "keltner channels.lower.linestyle": number; /** Default value: `1` */ "keltner channels.lower.linewidth": number; /** Default value: `line` */ "keltner channels.lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "keltner channels.lower.trackprice": boolean; /** Default value: `0` */ "keltner channels.lower.transparency": number; /** Default value: `#2196F3` */ "keltner channels.lower.color": string; /** * - Default value: `true` * - Input type: `bool` */ "keltner channels.usetruerange": boolean; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "keltner channels.length": number; /** * - Default value: `1` * - Input type: `float` * - Min: `-1000000000000` * - Max: `1000000000000` */ "keltner channels.mult": number; /** Default value: `15` */ "klinger oscillator.plot.display": number; /** Default value: `0` */ "klinger oscillator.plot.linestyle": number; /** Default value: `1` */ "klinger oscillator.plot.linewidth": number; /** Default value: `line` */ "klinger oscillator.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "klinger oscillator.plot.trackprice": boolean; /** Default value: `0` */ "klinger oscillator.plot.transparency": number; /** Default value: `#2196F3` */ "klinger oscillator.plot.color": string; /** Default value: `15` */ "klinger oscillator.signal.display": number; /** Default value: `0` */ "klinger oscillator.signal.linestyle": number; /** Default value: `1` */ "klinger oscillator.signal.linewidth": number; /** Default value: `line` */ "klinger oscillator.signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "klinger oscillator.signal.trackprice": boolean; /** Default value: `0` */ "klinger oscillator.signal.transparency": number; /** Default value: `#43A047` */ "klinger oscillator.signal.color": string; /** Default value: `#787B86` */ "know sure thing.zero.color": string; /** Default value: `2` */ "know sure thing.zero.linestyle": number; /** Default value: `1` */ "know sure thing.zero.linewidth": number; /** Default value: `true` */ "know sure thing.zero.visible": boolean; /** Default value: `0` */ "know sure thing.zero.value": number; /** Default value: `15` */ "know sure thing.kst.display": number; /** Default value: `0` */ "know sure thing.kst.linestyle": number; /** Default value: `1` */ "know sure thing.kst.linewidth": number; /** Default value: `line` */ "know sure thing.kst.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "know sure thing.kst.trackprice": boolean; /** Default value: `0` */ "know sure thing.kst.transparency": number; /** Default value: `#089981` */ "know sure thing.kst.color": string; /** Default value: `15` */ "know sure thing.signal.display": number; /** Default value: `0` */ "know sure thing.signal.linestyle": number; /** Default value: `1` */ "know sure thing.signal.linewidth": number; /** Default value: `line` */ "know sure thing.signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "know sure thing.signal.trackprice": boolean; /** Default value: `0` */ "know sure thing.signal.transparency": number; /** Default value: `#F23645` */ "know sure thing.signal.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "know sure thing.roclen1": number; /** * - Default value: `15` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "know sure thing.roclen2": number; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "know sure thing.roclen3": number; /** * - Default value: `30` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "know sure thing.roclen4": number; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "know sure thing.smalen1": number; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "know sure thing.smalen2": number; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "know sure thing.smalen3": number; /** * - Default value: `15` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "know sure thing.smalen4": number; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "know sure thing.siglen": number; /** Default value: `15` */ "least squares moving average.plot.display": number; /** Default value: `0` */ "least squares moving average.plot.linestyle": number; /** Default value: `1` */ "least squares moving average.plot.linewidth": number; /** Default value: `line` */ "least squares moving average.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "least squares moving average.plot.trackprice": boolean; /** Default value: `0` */ "least squares moving average.plot.transparency": number; /** Default value: `#2196F3` */ "least squares moving average.plot.color": string; /** * - Default value: `25` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "least squares moving average.length": number; /** * - Default value: `0` * - Input type: `integer` * - Min: `-1000000000000` * - Max: `1000000000000` */ "least squares moving average.offset": number; /** Default value: `15` */ "linear regression curve.plot.display": number; /** Default value: `0` */ "linear regression curve.plot.linestyle": number; /** Default value: `1` */ "linear regression curve.plot.linewidth": number; /** Default value: `line` */ "linear regression curve.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "linear regression curve.plot.trackprice": boolean; /** Default value: `0` */ "linear regression curve.plot.transparency": number; /** Default value: `#2196F3` */ "linear regression curve.plot.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "linear regression curve.length": number; /** Default value: `15` */ "linear regression slope.plot.display": number; /** Default value: `0` */ "linear regression slope.plot.linestyle": number; /** Default value: `1` */ "linear regression slope.plot.linewidth": number; /** Default value: `line` */ "linear regression slope.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "linear regression slope.plot.trackprice": boolean; /** Default value: `0` */ "linear regression slope.plot.transparency": number; /** Default value: `#FF5252` */ "linear regression slope.plot.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `2` */ "linear regression slope.periods": number; /** Default value: `15` */ "ma cross.short:plot.display": number; /** Default value: `0` */ "ma cross.short:plot.linestyle": number; /** Default value: `1` */ "ma cross.short:plot.linewidth": number; /** Default value: `line` */ "ma cross.short:plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ma cross.short:plot.trackprice": boolean; /** Default value: `0` */ "ma cross.short:plot.transparency": number; /** Default value: `#43A047` */ "ma cross.short:plot.color": string; /** Default value: `15` */ "ma cross.long:plot.display": number; /** Default value: `0` */ "ma cross.long:plot.linestyle": number; /** Default value: `1` */ "ma cross.long:plot.linewidth": number; /** Default value: `line` */ "ma cross.long:plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ma cross.long:plot.trackprice": boolean; /** Default value: `0` */ "ma cross.long:plot.transparency": number; /** Default value: `#FF6D00` */ "ma cross.long:plot.color": string; /** Default value: `15` */ "ma cross.crosses.display": number; /** Default value: `0` */ "ma cross.crosses.linestyle": number; /** Default value: `4` */ "ma cross.crosses.linewidth": number; /** Default value: `cross` */ "ma cross.crosses.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ma cross.crosses.trackprice": boolean; /** Default value: `0` */ "ma cross.crosses.transparency": number; /** Default value: `#2196F3` */ "ma cross.crosses.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "ma cross.short:input": number; /** * - Default value: `26` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "ma cross.long:input": number; /** Default value: `15` */ "ma with ema cross.ma.display": number; /** Default value: `0` */ "ma with ema cross.ma.linestyle": number; /** Default value: `1` */ "ma with ema cross.ma.linewidth": number; /** Default value: `line` */ "ma with ema cross.ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ma with ema cross.ma.trackprice": boolean; /** Default value: `0` */ "ma with ema cross.ma.transparency": number; /** Default value: `#FF6D00` */ "ma with ema cross.ma.color": string; /** Default value: `15` */ "ma with ema cross.ema.display": number; /** Default value: `0` */ "ma with ema cross.ema.linestyle": number; /** Default value: `1` */ "ma with ema cross.ema.linewidth": number; /** Default value: `line` */ "ma with ema cross.ema.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ma with ema cross.ema.trackprice": boolean; /** Default value: `0` */ "ma with ema cross.ema.transparency": number; /** Default value: `#43A047` */ "ma with ema cross.ema.color": string; /** Default value: `15` */ "ma with ema cross.crosses.display": number; /** Default value: `0` */ "ma with ema cross.crosses.linestyle": number; /** Default value: `4` */ "ma with ema cross.crosses.linewidth": number; /** Default value: `cross` */ "ma with ema cross.crosses.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ma with ema cross.crosses.trackprice": boolean; /** Default value: `0` */ "ma with ema cross.crosses.transparency": number; /** Default value: `#2196F3` */ "ma with ema cross.crosses.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "ma with ema cross.length ma": number; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "ma with ema cross.length ema": number; /** Default value: `15` */ "macd.histogram.display": number; /** Default value: `0` */ "macd.histogram.linestyle": number; /** Default value: `1` */ "macd.histogram.linewidth": number; /** Default value: `columns` */ "macd.histogram.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "macd.histogram.trackprice": boolean; /** Default value: `0` */ "macd.histogram.transparency": number; /** Default value: `#FF5252` */ "macd.histogram.color": string; /** Default value: `15` */ "macd.macd.display": number; /** Default value: `0` */ "macd.macd.linestyle": number; /** Default value: `1` */ "macd.macd.linewidth": number; /** Default value: `line` */ "macd.macd.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "macd.macd.trackprice": boolean; /** Default value: `0` */ "macd.macd.transparency": number; /** Default value: `#2196F3` */ "macd.macd.color": string; /** Default value: `15` */ "macd.signal.display": number; /** Default value: `0` */ "macd.signal.linestyle": number; /** Default value: `1` */ "macd.signal.linewidth": number; /** Default value: `line` */ "macd.signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "macd.signal.trackprice": boolean; /** Default value: `0` */ "macd.signal.transparency": number; /** Default value: `#FF6D00` */ "macd.signal.color": string; /** * - Default value: `undefined` * - Input type: `symbol` * - Optional: `true` * - IsHidden: `false` */ "macd.other symbol": string; /** * - Default value: `12` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "macd.fast length": number; /** * - Default value: `26` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "macd.slow length": number; /** * - Default value: `close` * - Input type: `source` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "macd.source": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `50` */ "macd.signal length": number; /** * - Default value: `EMA` * - Input type: `text` * - Options: `["SMA","EMA","WMA"]` */ "macd.oscillator ma type": string; /** * - Default value: `EMA` * - Input type: `text` * - Options: `["SMA","EMA","WMA"]` */ "macd.signal line ma type": string; /** Default value: `15` */ "majority rule.majority rule.display": number; /** Default value: `0` */ "majority rule.majority rule.linestyle": number; /** Default value: `1` */ "majority rule.majority rule.linewidth": number; /** Default value: `line` */ "majority rule.majority rule.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "majority rule.majority rule.trackprice": boolean; /** Default value: `0` */ "majority rule.majority rule.transparency": number; /** Default value: `#FF5252` */ "majority rule.majority rule.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` */ "majority rule.rolling period": number; /** Default value: `15` */ "mass index.plot.display": number; /** Default value: `0` */ "mass index.plot.linestyle": number; /** Default value: `1` */ "mass index.plot.linewidth": number; /** Default value: `line` */ "mass index.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "mass index.plot.trackprice": boolean; /** Default value: `0` */ "mass index.plot.transparency": number; /** Default value: `#2196F3` */ "mass index.plot.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "mass index.length": number; /** Default value: `15` */ "mcginley dynamic.plot.display": number; /** Default value: `0` */ "mcginley dynamic.plot.linestyle": number; /** Default value: `1` */ "mcginley dynamic.plot.linewidth": number; /** Default value: `line` */ "mcginley dynamic.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "mcginley dynamic.plot.trackprice": boolean; /** Default value: `0` */ "mcginley dynamic.plot.transparency": number; /** Default value: `#2196F3` */ "mcginley dynamic.plot.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "mcginley dynamic.length": number; /** Default value: `15` */ "median price.plot.display": number; /** Default value: `0` */ "median price.plot.linestyle": number; /** Default value: `1` */ "median price.plot.linewidth": number; /** Default value: `line` */ "median price.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "median price.plot.trackprice": boolean; /** Default value: `0` */ "median price.plot.transparency": number; /** Default value: `#FF6D00` */ "median price.plot.color": string; /** Default value: `#787B86` */ "momentum.zero.color": string; /** Default value: `2` */ "momentum.zero.linestyle": number; /** Default value: `1` */ "momentum.zero.linewidth": number; /** Default value: `true` */ "momentum.zero.visible": boolean; /** Default value: `0` */ "momentum.zero.value": number; /** Default value: `15` */ "momentum.mom.display": number; /** Default value: `0` */ "momentum.mom.linestyle": number; /** Default value: `1` */ "momentum.mom.linewidth": number; /** Default value: `line` */ "momentum.mom.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "momentum.mom.trackprice": boolean; /** Default value: `0` */ "momentum.mom.transparency": number; /** Default value: `#2196F3` */ "momentum.mom.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "momentum.length": number; /** * - Default value: `close` * - Input type: `source` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "momentum.source": string; /** Default value: `#7E57C2` */ "money flow index.hlines background.color": string; /** Default value: `90` */ "money flow index.hlines background.transparency": number; /** Default value: `true` */ "money flow index.hlines background.visible": boolean; /** Default value: `#787B86` */ "money flow index.upperlimit.color": string; /** Default value: `2` */ "money flow index.upperlimit.linestyle": number; /** Default value: `1` */ "money flow index.upperlimit.linewidth": number; /** Default value: `true` */ "money flow index.upperlimit.visible": boolean; /** Default value: `80` */ "money flow index.upperlimit.value": number; /** Default value: `#787B86` */ "money flow index.lowerlimit.color": string; /** Default value: `2` */ "money flow index.lowerlimit.linestyle": number; /** Default value: `1` */ "money flow index.lowerlimit.linewidth": number; /** Default value: `true` */ "money flow index.lowerlimit.visible": boolean; /** Default value: `20` */ "money flow index.lowerlimit.value": number; /** Default value: `15` */ "money flow index.plot.display": number; /** Default value: `0` */ "money flow index.plot.linestyle": number; /** Default value: `1` */ "money flow index.plot.linewidth": number; /** Default value: `line` */ "money flow index.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "money flow index.plot.trackprice": boolean; /** Default value: `0` */ "money flow index.plot.transparency": number; /** Default value: `#7E57C2` */ "money flow index.plot.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "money flow index.length": number; /** Default value: `15` */ "moving average.plot.display": number; /** Default value: `0` */ "moving average.plot.linestyle": number; /** Default value: `1` */ "moving average.plot.linewidth": number; /** Default value: `line` */ "moving average.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average.plot.trackprice": boolean; /** Default value: `0` */ "moving average.plot.transparency": number; /** Default value: `#2196F3` */ "moving average.plot.color": string; /** Default value: `0` */ "moving average.smoothed ma.display": number; /** Default value: `0` */ "moving average.smoothed ma.linestyle": number; /** Default value: `1` */ "moving average.smoothed ma.linewidth": number; /** Default value: `line` */ "moving average.smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average.smoothed ma.trackprice": boolean; /** Default value: `0` */ "moving average.smoothed ma.transparency": number; /** * - Default value: `undefined` * - Input type: `symbol` * - Optional: `true` * - IsHidden: `false` */ "moving average.other symbol": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average.length": number; /** * - Default value: `close` * - Input type: `source` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "moving average.source": string; /** * - Default value: `0` * - Input type: `integer` * - Min: `-10000` * - Max: `10000` */ "moving average.offset": number; /** * - Default value: `SMA` * - Input type: `text` * - Options: `["SMA","EMA","WMA"]` */ "moving average.smoothing line": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average.smoothing length": number; /** Default value: `15` */ "moving average adaptive.plot 1.display": number; /** Default value: `0` */ "moving average adaptive.plot 1.linestyle": number; /** Default value: `1` */ "moving average adaptive.plot 1.linewidth": number; /** Default value: `line` */ "moving average adaptive.plot 1.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "moving average adaptive.plot 1.transparency": number; /** Default value: `false` */ "moving average adaptive.plot 1.trackprice": boolean; /** Default value: `#AB47BC` */ "moving average adaptive.plot 1.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `2` * - Max: `10000` */ "moving average adaptive.period": number; /** Default value: `#2196F3` */ "moving average channel.plots background.color": string; /** Default value: `90` */ "moving average channel.plots background.transparency": number; /** Default value: `true` */ "moving average channel.plots background.visible": boolean; /** Default value: `15` */ "moving average channel.upper.display": number; /** Default value: `0` */ "moving average channel.upper.linestyle": number; /** Default value: `1` */ "moving average channel.upper.linewidth": number; /** Default value: `line` */ "moving average channel.upper.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average channel.upper.trackprice": boolean; /** Default value: `0` */ "moving average channel.upper.transparency": number; /** Default value: `#2196F3` */ "moving average channel.upper.color": string; /** Default value: `15` */ "moving average channel.lower.display": number; /** Default value: `0` */ "moving average channel.lower.linestyle": number; /** Default value: `1` */ "moving average channel.lower.linewidth": number; /** Default value: `line` */ "moving average channel.lower.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average channel.lower.trackprice": boolean; /** Default value: `0` */ "moving average channel.lower.transparency": number; /** Default value: `#FF6D00` */ "moving average channel.lower.color": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average channel.upper length": number; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average channel.lower length": number; /** * - Default value: `0` * - Input type: `integer` * - Min: `-10000` * - Max: `10000` */ "moving average channel.upper offset": number; /** * - Default value: `0` * - Input type: `integer` * - Min: `-10000` * - Max: `10000` */ "moving average channel.lower offset": number; /** Default value: `15` */ "moving average double.plot 1.display": number; /** Default value: `0` */ "moving average double.plot 1.linestyle": number; /** Default value: `1` */ "moving average double.plot 1.linewidth": number; /** Default value: `line` */ "moving average double.plot 1.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average double.plot 1.trackprice": boolean; /** Default value: `0` */ "moving average double.plot 1.transparency": number; /** Default value: `#FF6D00` */ "moving average double.plot 1.color": string; /** Default value: `15` */ "moving average double.plot 2.display": number; /** Default value: `0` */ "moving average double.plot 2.linestyle": number; /** Default value: `1` */ "moving average double.plot 2.linewidth": number; /** Default value: `line` */ "moving average double.plot 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average double.plot 2.trackprice": boolean; /** Default value: `0` */ "moving average double.plot 2.transparency": number; /** Default value: `#2196F3` */ "moving average double.plot 2.color": string; /** * - Default value: `undefined` * - Input type: `symbol` * - Optional: `true` * - IsHidden: `false` */ "moving average double.another symbol": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average double.1st period": number; /** * - Default value: `21` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average double.2nd period": number; /** * - Default value: `Simple` * - Input type: `text` * - Options: `["Simple","Exponential","Weighted"]` */ "moving average double.method": string; /** Default value: `15` */ "moving average exponential.plot.display": number; /** Default value: `0` */ "moving average exponential.plot.linestyle": number; /** Default value: `1` */ "moving average exponential.plot.linewidth": number; /** Default value: `line` */ "moving average exponential.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average exponential.plot.trackprice": boolean; /** Default value: `0` */ "moving average exponential.plot.transparency": number; /** Default value: `#2196F3` */ "moving average exponential.plot.color": string; /** Default value: `0` */ "moving average exponential.smoothed ma.display": number; /** Default value: `0` */ "moving average exponential.smoothed ma.linestyle": number; /** Default value: `1` */ "moving average exponential.smoothed ma.linewidth": number; /** Default value: `line` */ "moving average exponential.smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average exponential.smoothed ma.trackprice": boolean; /** Default value: `0` */ "moving average exponential.smoothed ma.transparency": number; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average exponential.length": number; /** * - Default value: `close` * - Input type: `source` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "moving average exponential.source": string; /** * - Default value: `0` * - Input type: `integer` * - Min: `-10000` * - Max: `10000` */ "moving average exponential.offset": number; /** * - Default value: `SMA` * - Input type: `text` * - Options: `["SMA","EMA","WMA"]` */ "moving average exponential.smoothing line": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average exponential.smoothing length": number; /** Default value: `15` */ "moving average hamming.plot 1.display": number; /** Default value: `0` */ "moving average hamming.plot 1.linestyle": number; /** Default value: `1` */ "moving average hamming.plot 1.linewidth": number; /** Default value: `line` */ "moving average hamming.plot 1.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "moving average hamming.plot 1.transparency": number; /** Default value: `false` */ "moving average hamming.plot 1.trackprice": boolean; /** Default value: `#4CAF50` */ "moving average hamming.plot 1.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average hamming.period": number; /** Default value: `15` */ "moving average multiple.plot 1.display": number; /** Default value: `0` */ "moving average multiple.plot 1.linestyle": number; /** Default value: `1` */ "moving average multiple.plot 1.linewidth": number; /** Default value: `line` */ "moving average multiple.plot 1.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "moving average multiple.plot 1.transparency": number; /** Default value: `false` */ "moving average multiple.plot 1.trackprice": boolean; /** Default value: `#9C27B0` */ "moving average multiple.plot 1.color": string; /** Default value: `15` */ "moving average multiple.plot 2.display": number; /** Default value: `0` */ "moving average multiple.plot 2.linestyle": number; /** Default value: `1` */ "moving average multiple.plot 2.linewidth": number; /** Default value: `0` */ "moving average multiple.plot 2.transparency": number; /** Default value: `line` */ "moving average multiple.plot 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average multiple.plot 2.trackprice": boolean; /** Default value: `#FF6D00` */ "moving average multiple.plot 2.color": string; /** Default value: `15` */ "moving average multiple.plot 3.display": number; /** Default value: `0` */ "moving average multiple.plot 3.linestyle": number; /** Default value: `1` */ "moving average multiple.plot 3.linewidth": number; /** Default value: `0` */ "moving average multiple.plot 3.transparency": number; /** Default value: `line` */ "moving average multiple.plot 3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average multiple.plot 3.trackprice": boolean; /** Default value: `#43A047` */ "moving average multiple.plot 3.color": string; /** Default value: `15` */ "moving average multiple.plot 4.display": number; /** Default value: `0` */ "moving average multiple.plot 4.linestyle": number; /** Default value: `1` */ "moving average multiple.plot 4.linewidth": number; /** Default value: `0` */ "moving average multiple.plot 4.transparency": number; /** Default value: `line` */ "moving average multiple.plot 4.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average multiple.plot 4.trackprice": boolean; /** Default value: `#26C6DA` */ "moving average multiple.plot 4.color": string; /** Default value: `15` */ "moving average multiple.plot 5.display": number; /** Default value: `0` */ "moving average multiple.plot 5.linestyle": number; /** Default value: `1` */ "moving average multiple.plot 5.linewidth": number; /** Default value: `0` */ "moving average multiple.plot 5.transparency": number; /** Default value: `line` */ "moving average multiple.plot 5.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average multiple.plot 5.trackprice": boolean; /** Default value: `#F50057` */ "moving average multiple.plot 5.color": string; /** Default value: `15` */ "moving average multiple.plot 6.display": number; /** Default value: `0` */ "moving average multiple.plot 6.linestyle": number; /** Default value: `1` */ "moving average multiple.plot 6.linewidth": number; /** Default value: `0` */ "moving average multiple.plot 6.transparency": number; /** Default value: `line` */ "moving average multiple.plot 6.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average multiple.plot 6.trackprice": boolean; /** Default value: `#2196F3` */ "moving average multiple.plot 6.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average multiple.1st period": number; /** * - Default value: `21` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average multiple.2nd period": number; /** * - Default value: `35` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average multiple.3rd period": number; /** * - Default value: `50` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average multiple.4th period": number; /** * - Default value: `100` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average multiple.5th period": number; /** * - Default value: `200` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average multiple.6th period": number; /** * - Default value: `Simple` * - Input type: `text` * - Options: `["Simple","Exponential","Weighted"]` */ "moving average multiple.method": string; /** Default value: `15` */ "moving average triple.plot 1.display": number; /** Default value: `0` */ "moving average triple.plot 1.linestyle": number; /** Default value: `1` */ "moving average triple.plot 1.linewidth": number; /** Default value: `line` */ "moving average triple.plot 1.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "moving average triple.plot 1.transparency": number; /** Default value: `false` */ "moving average triple.plot 1.trackprice": boolean; /** Default value: `#FF6D00` */ "moving average triple.plot 1.color": string; /** Default value: `15` */ "moving average triple.plot 2.display": number; /** Default value: `0` */ "moving average triple.plot 2.linestyle": number; /** Default value: `1` */ "moving average triple.plot 2.linewidth": number; /** Default value: `0` */ "moving average triple.plot 2.transparency": number; /** Default value: `line` */ "moving average triple.plot 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average triple.plot 2.trackprice": boolean; /** Default value: `#2196F3` */ "moving average triple.plot 2.color": string; /** Default value: `15` */ "moving average triple.plot 3.display": number; /** Default value: `0` */ "moving average triple.plot 3.linestyle": number; /** Default value: `1` */ "moving average triple.plot 3.linewidth": number; /** Default value: `0` */ "moving average triple.plot 3.transparency": number; /** Default value: `line` */ "moving average triple.plot 3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average triple.plot 3.trackprice": boolean; /** Default value: `#26C6DA` */ "moving average triple.plot 3.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average triple.1st period": number; /** * - Default value: `21` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average triple.2nd period": number; /** * - Default value: `35` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "moving average triple.3rd period": number; /** * - Default value: `Simple` * - Input type: `text` * - Options: `["Simple","Exponential","Weighted"]` */ "moving average triple.method": string; /** Default value: `15` */ "moving average weighted.plot.display": number; /** Default value: `0` */ "moving average weighted.plot.linestyle": number; /** Default value: `1` */ "moving average weighted.plot.linewidth": number; /** Default value: `line` */ "moving average weighted.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "moving average weighted.plot.trackprice": boolean; /** Default value: `0` */ "moving average weighted.plot.transparency": number; /** Default value: `#2196F3` */ "moving average weighted.plot.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "moving average weighted.length": number; /** * - Default value: `close` * - Input type: `source` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "moving average weighted.source": string; /** * - Default value: `0` * - Input type: `integer` * - Min: `-10000` * - Max: `10000` */ "moving average weighted.offset": number; /** Default value: `15` */ "net volume.plot.display": number; /** Default value: `0` */ "net volume.plot.linestyle": number; /** Default value: `1` */ "net volume.plot.linewidth": number; /** Default value: `line` */ "net volume.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "net volume.plot.trackprice": boolean; /** Default value: `0` */ "net volume.plot.transparency": number; /** Default value: `#2196F3` */ "net volume.plot.color": string; /** Default value: `15` */ "on balance volume.plot.display": number; /** Default value: `0` */ "on balance volume.plot.linestyle": number; /** Default value: `1` */ "on balance volume.plot.linewidth": number; /** Default value: `line` */ "on balance volume.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "on balance volume.plot.trackprice": boolean; /** Default value: `0` */ "on balance volume.plot.transparency": number; /** Default value: `#2196F3` */ "on balance volume.plot.color": string; /** Default value: `0` */ "on balance volume.smoothed ma.display": number; /** Default value: `0` */ "on balance volume.smoothed ma.linestyle": number; /** Default value: `1` */ "on balance volume.smoothed ma.linewidth": number; /** Default value: `line` */ "on balance volume.smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "on balance volume.smoothed ma.trackprice": boolean; /** Default value: `0` */ "on balance volume.smoothed ma.transparency": number; /** * - Default value: `SMA` * - Input type: `text` * - Options: `["SMA","EMA","WMA"]` */ "on balance volume.smoothing line": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "on balance volume.smoothing length": number; /** * - Default value: `undefined` * - Input type: `symbol` * - IsHidden: `true` */ "overlay.symbol": string; /** * - Default value: `false` * - Input type: `boolean` * - IsHidden: `true` */ "overlay.extendtimescale": boolean; /** Default value: `15` */ "parabolic sar.plot.display": number; /** Default value: `0` */ "parabolic sar.plot.linestyle": number; /** Default value: `1` */ "parabolic sar.plot.linewidth": number; /** Default value: `cross` */ "parabolic sar.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "parabolic sar.plot.trackprice": boolean; /** Default value: `0` */ "parabolic sar.plot.transparency": number; /** Default value: `#2196F3` */ "parabolic sar.plot.color": string; /** * - Default value: `0.02` * - Input type: `float` * - Min: `-1000000000000` * - Max: `1000000000000` */ "parabolic sar.start": number; /** * - Default value: `0.02` * - Input type: `float` * - Min: `-1000000000000` * - Max: `1000000000000` */ "parabolic sar.increment": number; /** * - Default value: `0.2` * - Input type: `float` * - Min: `-1000000000000` * - Max: `1000000000000` */ "parabolic sar.maximum": number; /** * - Default value: `undefined` * - Input type: `symbol` * - Optional: `true` * - IsHidden: `false` */ "parabolic sar.other symbol": string; /** * - Default value: `Traditional` * - Input type: `text` * - Options: `["Traditional","Fibonacci","Woodie","Classic","DeMark","Camarilla","Floor"]` */ "pivot points standard.type": string; /** * - Default value: `15` * - Input type: `integer` * - Max: `5000` * - Min: `1` */ "pivot points standard.number of pivots back": number; /** * - Default value: `Auto` * - Input type: `text` * - Options: `["Auto","Daily","Weekly","Monthly","Yearly"]` */ "pivot points standard.pivots timeframe": string; /** * - Default value: `true` * - Input type: `bool` */ "pivot points standard.show historical pivots": boolean; /** Default value: `15` */ "price channel.highprice line.display": number; /** Default value: `0` */ "price channel.highprice line.linestyle": number; /** Default value: `1` */ "price channel.highprice line.linewidth": number; /** Default value: `line` */ "price channel.highprice line.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "price channel.highprice line.trackprice": boolean; /** Default value: `0` */ "price channel.highprice line.transparency": number; /** Default value: `#F50057` */ "price channel.highprice line.color": string; /** Default value: `15` */ "price channel.lowprice line.display": number; /** Default value: `0` */ "price channel.lowprice line.linestyle": number; /** Default value: `1` */ "price channel.lowprice line.linewidth": number; /** Default value: `line` */ "price channel.lowprice line.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "price channel.lowprice line.trackprice": boolean; /** Default value: `0` */ "price channel.lowprice line.transparency": number; /** Default value: `#F50057` */ "price channel.lowprice line.color": string; /** Default value: `15` */ "price channel.centerprice line.display": number; /** Default value: `0` */ "price channel.centerprice line.linestyle": number; /** Default value: `1` */ "price channel.centerprice line.linewidth": number; /** Default value: `line` */ "price channel.centerprice line.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "price channel.centerprice line.trackprice": boolean; /** Default value: `0` */ "price channel.centerprice line.transparency": number; /** Default value: `#2196F3` */ "price channel.centerprice line.color": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "price channel.length": number; /** * - Default value: `0` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "price channel.offset length": number; /** Default value: `15` */ "price oscillator.plot.display": number; /** Default value: `0` */ "price oscillator.plot.linestyle": number; /** Default value: `1` */ "price oscillator.plot.linewidth": number; /** Default value: `line` */ "price oscillator.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "price oscillator.plot.trackprice": boolean; /** Default value: `0` */ "price oscillator.plot.transparency": number; /** Default value: `#089981` */ "price oscillator.plot.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "price oscillator.shortlen": number; /** * - Default value: `21` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "price oscillator.longlen": number; /** Default value: `15` */ "price volume trend.pvt.display": number; /** Default value: `0` */ "price volume trend.pvt.linestyle": number; /** Default value: `1` */ "price volume trend.pvt.linewidth": number; /** Default value: `line` */ "price volume trend.pvt.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "price volume trend.pvt.trackprice": boolean; /** Default value: `0` */ "price volume trend.pvt.transparency": number; /** Default value: `#2196F3` */ "price volume trend.pvt.color": string; /** Default value: `#787B86` */ "rank correlation index.zero line.color": string; /** Default value: `2` */ "rank correlation index.zero line.linestyle": number; /** Default value: `1` */ "rank correlation index.zero line.linewidth": number; /** Default value: `true` */ "rank correlation index.zero line.visible": boolean; /** Default value: `0` */ "rank correlation index.zero line.value": number; /** Default value: `15` */ "rank correlation index.rci.display": number; /** Default value: `0` */ "rank correlation index.rci.linestyle": number; /** Default value: `1` */ "rank correlation index.rci.linewidth": number; /** Default value: `line` */ "rank correlation index.rci.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "rank correlation index.rci.trackprice": boolean; /** Default value: `0` */ "rank correlation index.rci.transparency": number; /** Default value: `#2196F3` */ "rank correlation index.rci.color": string; /** * - Default value: `12` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "rank correlation index.length": number; /** Default value: `#787B86` */ "rate of change.zero line.color": string; /** Default value: `2` */ "rate of change.zero line.linestyle": number; /** Default value: `1` */ "rate of change.zero line.linewidth": number; /** Default value: `true` */ "rate of change.zero line.visible": boolean; /** Default value: `0` */ "rate of change.zero line.value": number; /** Default value: `15` */ "rate of change.roc.display": number; /** Default value: `0` */ "rate of change.roc.linestyle": number; /** Default value: `1` */ "rate of change.roc.linewidth": number; /** Default value: `line` */ "rate of change.roc.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "rate of change.roc.trackprice": boolean; /** Default value: `0` */ "rate of change.roc.transparency": number; /** Default value: `#2196F3` */ "rate of change.roc.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "rate of change.length": number; /** Default value: `undefined` */ "ratio.negativefill.color": string; /** Default value: `0` */ "ratio.negativefill.transparency": number; /** Default value: `true` */ "ratio.negativefill.visible": boolean; /** Default value: `undefined` */ "ratio.positivefill.color": string; /** Default value: `0` */ "ratio.positivefill.transparency": number; /** Default value: `true` */ "ratio.positivefill.visible": boolean; /** Default value: `0` */ "ratio.plot.linestyle": number; /** Default value: `2` */ "ratio.plot.linewidth": number; /** Default value: `line` */ "ratio.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ratio.plot.trackprice": boolean; /** Default value: `35` */ "ratio.plot.transparency": number; /** Default value: `#800080` */ "ratio.plot.color": string; /** Default value: `15` */ "ratio.plot.display": number; /** Default value: `0` */ "ratio.baseline.linestyle": number; /** Default value: `2` */ "ratio.baseline.linewidth": number; /** Default value: `line` */ "ratio.baseline.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ratio.baseline.trackprice": boolean; /** Default value: `0` */ "ratio.baseline.transparency": number; /** Default value: `rgba(0, 0, 0, 0)` */ "ratio.baseline.color": string; /** Default value: `0` */ "ratio.baseline.display": number; /** * - Default value: `close` * - Input type: `text` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "ratio.source": string; /** * - Default value: `undefined` * - Input type: `symbol` * - Confirm: `true` */ "ratio.symbol": string; /** * - Default value: `0` * - Input type: `time` * - IsHidden: `true` * - Max: `253370764800` * - Min: `-253370764800` */ "regression trend.first bar time": number; /** * - Default value: `0` * - Input type: `time` * - IsHidden: `true` * - Max: `253370764800` * - Min: `-253370764800` */ "regression trend.last bar time": number; /** * - Default value: `-2` * - Input type: `float` * - Max: `500` * - Min: `-500` */ "regression trend.lower deviation": number; /** * - Default value: `close` * - Input type: `source` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "regression trend.source": string; /** * - Default value: `2` * - Input type: `float` * - Max: `500` * - Min: `-500` */ "regression trend.upper deviation": number; /** * - Default value: `true` * - Input type: `bool` */ "regression trend.use lower deviation": boolean; /** * - Default value: `true` * - Input type: `bool` */ "regression trend.use upper deviation": boolean; /** Default value: `#7E57C2` */ "relative strength index.hlines background.color": string; /** Default value: `90` */ "relative strength index.hlines background.transparency": number; /** Default value: `true` */ "relative strength index.hlines background.visible": boolean; /** Default value: `#787B86` */ "relative strength index.upperlimit.color": string; /** Default value: `2` */ "relative strength index.upperlimit.linestyle": number; /** Default value: `1` */ "relative strength index.upperlimit.linewidth": number; /** Default value: `true` */ "relative strength index.upperlimit.visible": boolean; /** Default value: `70` */ "relative strength index.upperlimit.value": number; /** Default value: `-1.1` */ "relative strength index.upperlimit.zorder": number; /** Default value: `#787B86` */ "relative strength index.middlelimit.color": string; /** Default value: `2` */ "relative strength index.middlelimit.linestyle": number; /** Default value: `1` */ "relative strength index.middlelimit.linewidth": number; /** Default value: `true` */ "relative strength index.middlelimit.visible": boolean; /** Default value: `50` */ "relative strength index.middlelimit.value": number; /** Default value: `-1.11` */ "relative strength index.middlelimit.zorder": number; /** Default value: `#787B86` */ "relative strength index.lowerlimit.color": string; /** Default value: `2` */ "relative strength index.lowerlimit.linestyle": number; /** Default value: `1` */ "relative strength index.lowerlimit.linewidth": number; /** Default value: `true` */ "relative strength index.lowerlimit.visible": boolean; /** Default value: `30` */ "relative strength index.lowerlimit.value": number; /** Default value: `-1.111` */ "relative strength index.lowerlimit.zorder": number; /** Default value: `15` */ "relative strength index.plot.display": number; /** Default value: `0` */ "relative strength index.plot.linestyle": number; /** Default value: `1` */ "relative strength index.plot.linewidth": number; /** Default value: `line` */ "relative strength index.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "relative strength index.plot.trackprice": boolean; /** Default value: `0` */ "relative strength index.plot.transparency": number; /** Default value: `#7E57C2` */ "relative strength index.plot.color": string; /** Default value: `0` */ "relative strength index.smoothed ma.display": number; /** Default value: `0` */ "relative strength index.smoothed ma.linestyle": number; /** Default value: `1` */ "relative strength index.smoothed ma.linewidth": number; /** Default value: `line` */ "relative strength index.smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "relative strength index.smoothed ma.trackprice": boolean; /** Default value: `0` */ "relative strength index.smoothed ma.transparency": number; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "relative strength index.length": number; /** * - Default value: `SMA` * - Input type: `text` * - Options: `["SMA","EMA","WMA"]` */ "relative strength index.smoothing line": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "relative strength index.smoothing length": number; /** Default value: `15` */ "relative vigor index.rvgi.display": number; /** Default value: `0` */ "relative vigor index.rvgi.linestyle": number; /** Default value: `1` */ "relative vigor index.rvgi.linewidth": number; /** Default value: `line` */ "relative vigor index.rvgi.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "relative vigor index.rvgi.trackprice": boolean; /** Default value: `0` */ "relative vigor index.rvgi.transparency": number; /** Default value: `#089981` */ "relative vigor index.rvgi.color": string; /** Default value: `15` */ "relative vigor index.signal.display": number; /** Default value: `0` */ "relative vigor index.signal.linestyle": number; /** Default value: `1` */ "relative vigor index.signal.linewidth": number; /** Default value: `line` */ "relative vigor index.signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "relative vigor index.signal.trackprice": boolean; /** Default value: `0` */ "relative vigor index.signal.transparency": number; /** Default value: `#F23645` */ "relative vigor index.signal.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "relative vigor index.length": number; /** Default value: `#7E57C2` */ "relative volatility index.hlines background.color": string; /** Default value: `90` */ "relative volatility index.hlines background.transparency": number; /** Default value: `true` */ "relative volatility index.hlines background.visible": boolean; /** Default value: `#787B86` */ "relative volatility index.upperlimit.color": string; /** Default value: `2` */ "relative volatility index.upperlimit.linestyle": number; /** Default value: `1` */ "relative volatility index.upperlimit.linewidth": number; /** Default value: `true` */ "relative volatility index.upperlimit.visible": boolean; /** Default value: `80` */ "relative volatility index.upperlimit.value": number; /** Default value: `#787B86` */ "relative volatility index.lowerlimit.color": string; /** Default value: `2` */ "relative volatility index.lowerlimit.linestyle": number; /** Default value: `1` */ "relative volatility index.lowerlimit.linewidth": number; /** Default value: `true` */ "relative volatility index.lowerlimit.visible": boolean; /** Default value: `20` */ "relative volatility index.lowerlimit.value": number; /** Default value: `15` */ "relative volatility index.plot.display": number; /** Default value: `0` */ "relative volatility index.plot.linestyle": number; /** Default value: `1` */ "relative volatility index.plot.linewidth": number; /** Default value: `line` */ "relative volatility index.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "relative volatility index.plot.trackprice": boolean; /** Default value: `0` */ "relative volatility index.plot.transparency": number; /** Default value: `#7E57C2` */ "relative volatility index.plot.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "relative volatility index.length": number; /** Default value: `15` */ "smi ergodic indicator/oscillator.indicator.display": number; /** Default value: `0` */ "smi ergodic indicator/oscillator.indicator.linestyle": number; /** Default value: `1` */ "smi ergodic indicator/oscillator.indicator.linewidth": number; /** Default value: `line` */ "smi ergodic indicator/oscillator.indicator.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "smi ergodic indicator/oscillator.indicator.trackprice": boolean; /** Default value: `0` */ "smi ergodic indicator/oscillator.indicator.transparency": number; /** Default value: `#2196F3` */ "smi ergodic indicator/oscillator.indicator.color": string; /** Default value: `15` */ "smi ergodic indicator/oscillator.signal.display": number; /** Default value: `0` */ "smi ergodic indicator/oscillator.signal.linestyle": number; /** Default value: `1` */ "smi ergodic indicator/oscillator.signal.linewidth": number; /** Default value: `line` */ "smi ergodic indicator/oscillator.signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "smi ergodic indicator/oscillator.signal.trackprice": boolean; /** Default value: `0` */ "smi ergodic indicator/oscillator.signal.transparency": number; /** Default value: `#FF6D00` */ "smi ergodic indicator/oscillator.signal.color": string; /** Default value: `15` */ "smi ergodic indicator/oscillator.oscillator.display": number; /** Default value: `0` */ "smi ergodic indicator/oscillator.oscillator.linestyle": number; /** Default value: `1` */ "smi ergodic indicator/oscillator.oscillator.linewidth": number; /** Default value: `histogram` */ "smi ergodic indicator/oscillator.oscillator.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "smi ergodic indicator/oscillator.oscillator.trackprice": boolean; /** Default value: `0` */ "smi ergodic indicator/oscillator.oscillator.transparency": number; /** Default value: `#FF5252` */ "smi ergodic indicator/oscillator.oscillator.color": string; /** * - Default value: `5` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "smi ergodic indicator/oscillator.shortlen": number; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "smi ergodic indicator/oscillator.longlen": number; /** * - Default value: `5` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "smi ergodic indicator/oscillator.siglen": number; /** Default value: `15` */ "smoothed moving average.plot.display": number; /** Default value: `0` */ "smoothed moving average.plot.linestyle": number; /** Default value: `1` */ "smoothed moving average.plot.linewidth": number; /** Default value: `line` */ "smoothed moving average.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "smoothed moving average.plot.trackprice": boolean; /** Default value: `0` */ "smoothed moving average.plot.transparency": number; /** Default value: `#673AB7` */ "smoothed moving average.plot.color": string; /** * - Default value: `7` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "smoothed moving average.length": number; /** * - Default value: `close` * - Input type: `source` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "smoothed moving average.source": string; /** Default value: `undefined` */ "spread.negative fill.color": string; /** Default value: `0` */ "spread.negative fill.transparency": number; /** Default value: `true` */ "spread.negative fill.visible": boolean; /** Default value: `undefined` */ "spread.positive fill.color": string; /** Default value: `0` */ "spread.positive fill.transparency": number; /** Default value: `true` */ "spread.positive fill.visible": boolean; /** Default value: `0` */ "spread.plot.linestyle": number; /** Default value: `2` */ "spread.plot.linewidth": number; /** Default value: `line` */ "spread.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "spread.plot.trackprice": boolean; /** Default value: `35` */ "spread.plot.transparency": number; /** Default value: `#800080` */ "spread.plot.color": string; /** Default value: `15` */ "spread.plot.display": number; /** Default value: `0` */ "spread.baseline.linestyle": number; /** Default value: `2` */ "spread.baseline.linewidth": number; /** Default value: `line` */ "spread.baseline.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "spread.baseline.trackprice": boolean; /** Default value: `0` */ "spread.baseline.transparency": number; /** Default value: `rgba(0, 0, 0, 0)` */ "spread.baseline.color": string; /** Default value: `0` */ "spread.baseline.display": number; /** * - Default value: `close` * - Input type: `text` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "spread.source": string; /** * - Default value: `undefined` * - Input type: `symbol` * - Confirm: `true` */ "spread.symbol": string; /** Default value: `15` */ "standard deviation.plot.display": number; /** Default value: `0` */ "standard deviation.plot.linestyle": number; /** Default value: `1` */ "standard deviation.plot.linewidth": number; /** Default value: `line` */ "standard deviation.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "standard deviation.plot.trackprice": boolean; /** Default value: `0` */ "standard deviation.plot.transparency": number; /** Default value: `#089981` */ "standard deviation.plot.color": string; /** * - Default value: `5` * - Input type: `integer` */ "standard deviation.periods": number; /** * - Default value: `1` * - Input type: `float` */ "standard deviation.deviations": number; /** Default value: `15` */ "standard error.plot.display": number; /** Default value: `0` */ "standard error.plot.linestyle": number; /** Default value: `1` */ "standard error.plot.linewidth": number; /** Default value: `line` */ "standard error.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "standard error.plot.trackprice": boolean; /** Default value: `0` */ "standard error.plot.transparency": number; /** Default value: `#FF6D00` */ "standard error.plot.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `3` */ "standard error.length": number; /** Default value: `#2196F3` */ "standard error bands.background.color": string; /** Default value: `95` */ "standard error bands.background.transparency": number; /** Default value: `true` */ "standard error bands.background.visible": boolean; /** Default value: `15` */ "standard error bands.plot 1.display": number; /** Default value: `0` */ "standard error bands.plot 1.linestyle": number; /** Default value: `1` */ "standard error bands.plot 1.linewidth": number; /** Default value: `line` */ "standard error bands.plot 1.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "standard error bands.plot 1.transparency": number; /** Default value: `false` */ "standard error bands.plot 1.trackprice": boolean; /** Default value: `#2196F3` */ "standard error bands.plot 1.color": string; /** Default value: `15` */ "standard error bands.plot 2.display": number; /** Default value: `0` */ "standard error bands.plot 2.linestyle": number; /** Default value: `1` */ "standard error bands.plot 2.linewidth": number; /** Default value: `0` */ "standard error bands.plot 2.transparency": number; /** Default value: `line` */ "standard error bands.plot 2.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "standard error bands.plot 2.trackprice": boolean; /** Default value: `#FF6D00` */ "standard error bands.plot 2.color": string; /** Default value: `15` */ "standard error bands.plot 3.display": number; /** Default value: `0` */ "standard error bands.plot 3.linestyle": number; /** Default value: `1` */ "standard error bands.plot 3.linewidth": number; /** Default value: `0` */ "standard error bands.plot 3.transparency": number; /** Default value: `line` */ "standard error bands.plot 3.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "standard error bands.plot 3.trackprice": boolean; /** Default value: `#2196F3` */ "standard error bands.plot 3.color": string; /** * - Default value: `21` * - Input type: `integer` */ "standard error bands.periods": number; /** * - Default value: `2` * - Input type: `float` */ "standard error bands.standard errors": number; /** * - Default value: `Simple` * - Input type: `text` * - Options: `["Simple","Exponential","Weighted"]` */ "standard error bands.method": string; /** * - Default value: `3` * - Input type: `integer` */ "standard error bands.averaging periods": number; /** Default value: `#2196F3` */ "stochastic.hlines background.color": string; /** Default value: `90` */ "stochastic.hlines background.transparency": number; /** Default value: `true` */ "stochastic.hlines background.visible": boolean; /** Default value: `#787B86` */ "stochastic.upperlimit.color": string; /** Default value: `2` */ "stochastic.upperlimit.linestyle": number; /** Default value: `1` */ "stochastic.upperlimit.linewidth": number; /** Default value: `true` */ "stochastic.upperlimit.visible": boolean; /** Default value: `80` */ "stochastic.upperlimit.value": number; /** Default value: `#787B86` */ "stochastic.lowerlimit.color": string; /** Default value: `2` */ "stochastic.lowerlimit.linestyle": number; /** Default value: `1` */ "stochastic.lowerlimit.linewidth": number; /** Default value: `true` */ "stochastic.lowerlimit.visible": boolean; /** Default value: `20` */ "stochastic.lowerlimit.value": number; /** Default value: `15` */ "stochastic.%k.display": number; /** Default value: `0` */ "stochastic.%k.linestyle": number; /** Default value: `1` */ "stochastic.%k.linewidth": number; /** Default value: `line` */ "stochastic.%k.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "stochastic.%k.trackprice": boolean; /** Default value: `0` */ "stochastic.%k.transparency": number; /** Default value: `#2196F3` */ "stochastic.%k.color": string; /** Default value: `15` */ "stochastic.%d.display": number; /** Default value: `0` */ "stochastic.%d.linestyle": number; /** Default value: `1` */ "stochastic.%d.linewidth": number; /** Default value: `line` */ "stochastic.%d.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "stochastic.%d.trackprice": boolean; /** Default value: `0` */ "stochastic.%d.transparency": number; /** Default value: `#FF6D00` */ "stochastic.%d.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "stochastic.%k length": number; /** * - Default value: `1` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "stochastic.%k smoothing": number; /** * - Default value: `3` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "stochastic.%d smoothing": number; /** Default value: `#2196F3` */ "stochastic rsi.hlines background.color": string; /** Default value: `90` */ "stochastic rsi.hlines background.transparency": number; /** Default value: `true` */ "stochastic rsi.hlines background.visible": boolean; /** Default value: `#787B86` */ "stochastic rsi.upperlimit.color": string; /** Default value: `2` */ "stochastic rsi.upperlimit.linestyle": number; /** Default value: `1` */ "stochastic rsi.upperlimit.linewidth": number; /** Default value: `true` */ "stochastic rsi.upperlimit.visible": boolean; /** Default value: `80` */ "stochastic rsi.upperlimit.value": number; /** Default value: `#787B86` */ "stochastic rsi.lowerlimit.color": string; /** Default value: `2` */ "stochastic rsi.lowerlimit.linestyle": number; /** Default value: `1` */ "stochastic rsi.lowerlimit.linewidth": number; /** Default value: `true` */ "stochastic rsi.lowerlimit.visible": boolean; /** Default value: `20` */ "stochastic rsi.lowerlimit.value": number; /** Default value: `15` */ "stochastic rsi.%k.display": number; /** Default value: `0` */ "stochastic rsi.%k.linestyle": number; /** Default value: `1` */ "stochastic rsi.%k.linewidth": number; /** Default value: `line` */ "stochastic rsi.%k.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "stochastic rsi.%k.trackprice": boolean; /** Default value: `0` */ "stochastic rsi.%k.transparency": number; /** Default value: `#2196F3` */ "stochastic rsi.%k.color": string; /** Default value: `15` */ "stochastic rsi.%d.display": number; /** Default value: `0` */ "stochastic rsi.%d.linestyle": number; /** Default value: `1` */ "stochastic rsi.%d.linewidth": number; /** Default value: `line` */ "stochastic rsi.%d.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "stochastic rsi.%d.trackprice": boolean; /** Default value: `0` */ "stochastic rsi.%d.transparency": number; /** Default value: `#FF6D00` */ "stochastic rsi.%d.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "stochastic rsi.lengthrsi": number; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "stochastic rsi.lengthstoch": number; /** * - Default value: `3` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "stochastic rsi.smoothk": number; /** * - Default value: `3` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "stochastic rsi.smoothd": number; /** Default value: `15` */ "supertrend.supertrend.display": number; /** Default value: `0` */ "supertrend.supertrend.linestyle": number; /** Default value: `3` */ "supertrend.supertrend.linewidth": number; /** Default value: `line` */ "supertrend.supertrend.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "supertrend.supertrend.trackprice": boolean; /** Default value: `35` */ "supertrend.supertrend.transparency": number; /** Default value: `#000080` */ "supertrend.supertrend.color": string; /** Default value: `15` */ "supertrend.up arrow.display": number; /** Default value: `0` */ "supertrend.up arrow.linestyle": number; /** Default value: `3` */ "supertrend.up arrow.linewidth": number; /** Default value: `shape_arrow_up` */ "supertrend.up arrow.plottype": string; /** Default value: `false` */ "supertrend.up arrow.trackprice": boolean; /** Default value: `BelowBar` */ "supertrend.up arrow.location": string; /** Default value: `35` */ "supertrend.up arrow.transparency": number; /** Default value: `#00FF00` */ "supertrend.up arrow.color": string; /** Default value: `15` */ "supertrend.down arrow.display": number; /** Default value: `0` */ "supertrend.down arrow.linestyle": number; /** Default value: `3` */ "supertrend.down arrow.linewidth": number; /** Default value: `shape_arrow_down` */ "supertrend.down arrow.plottype": string; /** Default value: `false` */ "supertrend.down arrow.trackprice": boolean; /** Default value: `AboveBar` */ "supertrend.down arrow.location": string; /** Default value: `35` */ "supertrend.down arrow.transparency": number; /** Default value: `#FF0000` */ "supertrend.down arrow.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `100` */ "supertrend.length": number; /** * - Default value: `3` * - Input type: `float` * - Min: `1` * - Max: `100` */ "supertrend.factor": number; /** Default value: `#787B86` */ "trix.zero.color": string; /** Default value: `2` */ "trix.zero.linestyle": number; /** Default value: `1` */ "trix.zero.linewidth": number; /** Default value: `true` */ "trix.zero.visible": boolean; /** Default value: `0` */ "trix.zero.value": number; /** Default value: `15` */ "trix.trix.display": number; /** Default value: `0` */ "trix.trix.linestyle": number; /** Default value: `1` */ "trix.trix.linewidth": number; /** Default value: `line` */ "trix.trix.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "trix.trix.trackprice": boolean; /** Default value: `0` */ "trix.trix.transparency": number; /** Default value: `#F23645` */ "trix.trix.color": string; /** * - Default value: `18` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "trix.length": number; /** Default value: `15` */ "trend strength index.plot.display": number; /** Default value: `0` */ "trend strength index.plot.linestyle": number; /** Default value: `1` */ "trend strength index.plot.linewidth": number; /** Default value: `line` */ "trend strength index.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "trend strength index.plot.trackprice": boolean; /** Default value: `0` */ "trend strength index.plot.transparency": number; /** Default value: `#FF5252` */ "trend strength index.plot.color": string; /** * - Default value: `14` * - Input type: `integer` */ "trend strength index.periods": number; /** Default value: `15` */ "triple ema.plot.display": number; /** Default value: `0` */ "triple ema.plot.linestyle": number; /** Default value: `1` */ "triple ema.plot.linewidth": number; /** Default value: `line` */ "triple ema.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "triple ema.plot.trackprice": boolean; /** Default value: `0` */ "triple ema.plot.transparency": number; /** Default value: `#2196F3` */ "triple ema.plot.color": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "triple ema.length": number; /** Default value: `#787B86` */ "true strength index.zero.color": string; /** Default value: `2` */ "true strength index.zero.linestyle": number; /** Default value: `1` */ "true strength index.zero.linewidth": number; /** Default value: `true` */ "true strength index.zero.visible": boolean; /** Default value: `0` */ "true strength index.zero.value": number; /** Default value: `15` */ "true strength index.true strength index.display": number; /** Default value: `0` */ "true strength index.true strength index.linestyle": number; /** Default value: `1` */ "true strength index.true strength index.linewidth": number; /** Default value: `line` */ "true strength index.true strength index.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "true strength index.true strength index.trackprice": boolean; /** Default value: `0` */ "true strength index.true strength index.transparency": number; /** Default value: `#2196F3` */ "true strength index.true strength index.color": string; /** Default value: `15` */ "true strength index.signal.display": number; /** Default value: `0` */ "true strength index.signal.linestyle": number; /** Default value: `1` */ "true strength index.signal.linewidth": number; /** Default value: `line` */ "true strength index.signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "true strength index.signal.trackprice": boolean; /** Default value: `0` */ "true strength index.signal.transparency": number; /** Default value: `#E91E63` */ "true strength index.signal.color": string; /** * - Default value: `25` * - Input type: `integer` * - Min: `1` * - Max: `4999` */ "true strength index.long": number; /** * - Default value: `13` * - Input type: `integer` * - Min: `1` * - Max: `4999` */ "true strength index.short": number; /** * - Default value: `13` * - Input type: `integer` * - Min: `1` * - Max: `4999` */ "true strength index.siglen": number; /** Default value: `15` */ "typical price.plot.display": number; /** Default value: `0` */ "typical price.plot.linestyle": number; /** Default value: `1` */ "typical price.plot.linewidth": number; /** Default value: `line` */ "typical price.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "typical price.plot.trackprice": boolean; /** Default value: `0` */ "typical price.plot.transparency": number; /** Default value: `#FF6D00` */ "typical price.plot.color": string; /** Default value: `15` */ "ultimate oscillator.uo.display": number; /** Default value: `0` */ "ultimate oscillator.uo.linestyle": number; /** Default value: `1` */ "ultimate oscillator.uo.linewidth": number; /** Default value: `line` */ "ultimate oscillator.uo.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "ultimate oscillator.uo.trackprice": boolean; /** Default value: `0` */ "ultimate oscillator.uo.transparency": number; /** Default value: `#F23645` */ "ultimate oscillator.uo.color": string; /** * - Default value: `7` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "ultimate oscillator.length7": number; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "ultimate oscillator.length14": number; /** * - Default value: `28` * - Input type: `integer` * - Min: `1` * - Max: `1000000000000` */ "ultimate oscillator.length28": number; /** Default value: `15` */ "vwap.vwap.display": number; /** Default value: `0` */ "vwap.vwap.linestyle": number; /** Default value: `1` */ "vwap.vwap.linewidth": number; /** Default value: `line` */ "vwap.vwap.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "vwap.vwap.trackprice": number; /** Default value: `0` */ "vwap.vwap.transparency": number; /** Default value: `#2196F3` */ "vwap.vwap.color": string; /** * - Default value: `hlc3` * - Input type: `source` * - Options: `["open","high","low","close","hl2","hlc3","ohlc4"]` */ "vwap.source": string; /** * - Default value: `Session` * - Input type: `text` * - Options: `["Session","Week","Month","Quarter","Year","Decade","Century"]` */ "vwap.anchor period": string; /** Default value: `15` */ "vwma.plot.display": number; /** Default value: `0` */ "vwma.plot.linestyle": number; /** Default value: `1` */ "vwma.plot.linewidth": number; /** Default value: `line` */ "vwma.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "vwma.plot.trackprice": boolean; /** Default value: `0` */ "vwma.plot.transparency": number; /** Default value: `#2196F3` */ "vwma.plot.color": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "vwma.len": number; /** Default value: `15` */ "volatility close-to-close.plot.display": number; /** Default value: `0` */ "volatility close-to-close.plot.linestyle": number; /** Default value: `1` */ "volatility close-to-close.plot.linewidth": number; /** Default value: `line` */ "volatility close-to-close.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volatility close-to-close.plot.trackprice": boolean; /** Default value: `0` */ "volatility close-to-close.plot.transparency": number; /** Default value: `#2196F3` */ "volatility close-to-close.plot.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `2` */ "volatility close-to-close.periods": number; /** * - Default value: `252` * - Input type: `integer` * - Min: `1` * - Max: `366` */ "volatility close-to-close.days per year": number; /** Default value: `15` */ "volatility index.plot.display": number; /** Default value: `0` */ "volatility index.plot.linestyle": number; /** Default value: `1` */ "volatility index.plot.linewidth": number; /** Default value: `line` */ "volatility index.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volatility index.plot.trackprice": boolean; /** Default value: `0` */ "volatility index.plot.transparency": number; /** Default value: `#FF5252` */ "volatility index.plot.color": string; /** * - Default value: `10` * - Input type: `integer` */ "volatility index.periods": number; /** * - Default value: `3` * - Input type: `float` */ "volatility index.atr mult": number; /** * - Default value: `Wilder Smoothing` * - Input type: `text` * - Options: `["Exponential","Wilder Smoothing"]` */ "volatility index.method": string; /** Default value: `15` */ "volatility o-h-l-c.plot.display": number; /** Default value: `0` */ "volatility o-h-l-c.plot.linestyle": number; /** Default value: `1` */ "volatility o-h-l-c.plot.linewidth": number; /** Default value: `line` */ "volatility o-h-l-c.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volatility o-h-l-c.plot.trackprice": boolean; /** Default value: `0` */ "volatility o-h-l-c.plot.transparency": number; /** Default value: `#FF5252` */ "volatility o-h-l-c.plot.color": string; /** * - Default value: `10` * - Input type: `integer` */ "volatility o-h-l-c.periods": number; /** * - Default value: `0` * - Input type: `float` * - Min: `0` * - Max: `0.999` */ "volatility o-h-l-c.market closed percentage": number; /** * - Default value: `252` * - Input type: `integer` */ "volatility o-h-l-c.days per year": number; /** Default value: `15` */ "volatility zero trend close-to-close.plot.display": number; /** Default value: `0` */ "volatility zero trend close-to-close.plot.linestyle": number; /** Default value: `1` */ "volatility zero trend close-to-close.plot.linewidth": number; /** Default value: `line` */ "volatility zero trend close-to-close.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volatility zero trend close-to-close.plot.trackprice": boolean; /** Default value: `0` */ "volatility zero trend close-to-close.plot.transparency": number; /** Default value: `#2196F3` */ "volatility zero trend close-to-close.plot.color": string; /** * - Default value: `10` * - Input type: `integer` * - Min: `0` * - Max: `10000` */ "volatility zero trend close-to-close.periods": number; /** * - Default value: `252` * - Input type: `integer` */ "volatility zero trend close-to-close.days per year": number; /** Default value: `15` */ "volume.volume.display": number; /** Default value: `0` */ "volume.volume.linestyle": number; /** Default value: `1` */ "volume.volume.linewidth": number; /** Default value: `columns` */ "volume.volume.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume.volume.trackprice": boolean; /** Default value: `50` */ "volume.volume.transparency": number; /** Default value: `#000080` */ "volume.volume.color": string; /** Default value: `0` */ "volume.volume ma:plot.display": number; /** Default value: `0` */ "volume.volume ma:plot.linestyle": number; /** Default value: `1` */ "volume.volume ma:plot.linewidth": number; /** Default value: `line` */ "volume.volume ma:plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume.volume ma:plot.trackprice": boolean; /** Default value: `0` */ "volume.volume ma:plot.transparency": number; /** Default value: `#2196F3` */ "volume.volume ma:plot.color": string; /** Default value: `0` */ "volume.smoothed ma.display": number; /** Default value: `0` */ "volume.smoothed ma.linestyle": number; /** Default value: `1` */ "volume.smoothed ma.linewidth": number; /** Default value: `line` */ "volume.smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume.smoothed ma.trackprice": boolean; /** Default value: `0` */ "volume.smoothed ma.transparency": number; /** Default value: `#2196F3` */ "volume.smoothed ma.color": string; /** * - Default value: `false` * - Input type: `bool` * - IsHidden: `true` */ "volume.show ma": boolean; /** * - Default value: `SMA` * - Input type: `text` * - Options: `["SMA","EMA","WMA"]` */ "volume.volume ma:input": string; /** * - Default value: `20` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "volume.ma length": number; /** * - Default value: `false` * - Input type: `bool` */ "volume.color based on previous close": boolean; /** * - Default value: `undefined` * - Input type: `symbol` * - Optional: `true` * - IsHidden: `false` */ "volume.other symbol": string; /** * - Default value: `SMA` * - Input type: `text` * - Options: `["SMA","EMA","WMA"]` */ "volume.smoothing line": string; /** * - Default value: `9` * - Input type: `integer` * - Min: `1` * - Max: `10000` */ "volume.smoothing length": number; /** Default value: `#787B86` */ "volume oscillator.zero.color": string; /** Default value: `2` */ "volume oscillator.zero.linestyle": number; /** Default value: `1` */ "volume oscillator.zero.linewidth": number; /** Default value: `true` */ "volume oscillator.zero.visible": boolean; /** Default value: `0` */ "volume oscillator.zero.value": number; /** Default value: `15` */ "volume oscillator.plot.display": number; /** Default value: `0` */ "volume oscillator.plot.linestyle": number; /** Default value: `1` */ "volume oscillator.plot.linewidth": number; /** Default value: `line` */ "volume oscillator.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume oscillator.plot.trackprice": boolean; /** Default value: `0` */ "volume oscillator.plot.transparency": number; /** Default value: `#2196F3` */ "volume oscillator.plot.color": string; /** * - Default value: `5` * - Input type: `integer` * - Min: `1` * - Max: `4999` */ "volume oscillator.shortlen": number; /** * - Default value: `10` * - Input type: `integer` * - Min: `1` * - Max: `4999` */ "volume oscillator.longlen": number; /** Default value: `undefined` */ "volume profile fixed range.developing poc.color": string; /** Default value: `0` */ "volume profile fixed range.developing poc.linestyle": number; /** Default value: `1` */ "volume profile fixed range.developing poc.linewidth": number; /** Default value: `step_line` */ "volume profile fixed range.developing poc.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume profile fixed range.developing poc.trackprice": boolean; /** Default value: `0` */ "volume profile fixed range.developing poc.transparency": number; /** Default value: `0` */ "volume profile fixed range.developing poc.display": number; /** Default value: `undefined` */ "volume profile fixed range.developing va high.color": string; /** Default value: `0` */ "volume profile fixed range.developing va high.linestyle": number; /** Default value: `1` */ "volume profile fixed range.developing va high.linewidth": number; /** Default value: `step_line` */ "volume profile fixed range.developing va high.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume profile fixed range.developing va high.trackprice": boolean; /** Default value: `0` */ "volume profile fixed range.developing va high.transparency": number; /** Default value: `0` */ "volume profile fixed range.developing va high.display": number; /** Default value: `undefined` */ "volume profile fixed range.developing va low.color": string; /** Default value: `0` */ "volume profile fixed range.developing va low.linestyle": number; /** Default value: `1` */ "volume profile fixed range.developing va low.linewidth": number; /** Default value: `step_line` */ "volume profile fixed range.developing va low.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume profile fixed range.developing va low.trackprice": boolean; /** Default value: `0` */ "volume profile fixed range.developing va low.transparency": number; /** Default value: `0` */ "volume profile fixed range.developing va low.display": number; /** * - Default value: `0` * - Input type: `time` * - IsHidden: `true` * - Max: `253370764800` * - Min: `-253370764800` */ "volume profile fixed range.first bar time": number; /** * - Default value: `0` * - Input type: `time` * - IsHidden: `true` * - Max: `253370764800` * - Min: `-253370764800` */ "volume profile fixed range.last bar time": number; /** * - Default value: `24` * - Input type: `integer` * - Max: `1000000` * - Min: `1` */ "volume profile fixed range.row size": number; /** * - Default value: `Number Of Rows` * - Input type: `text` * - Options: `["Number Of Rows","Ticks Per Row"]` */ "volume profile fixed range.rows layout": string; /** * - Default value: `true` * - Input type: `bool` * - IsHidden: `true` */ "volume profile fixed range.subscriberealtime": boolean; /** * - Default value: `70` * - Input type: `integer` * - Max: `100` * - Min: `0` */ "volume profile fixed range.value area volume": number; /** * - Default value: `Up/Down` * - Input type: `text` * - Options: `["Up/Down","Total","Delta"]` */ "volume profile fixed range.volume": string; /** Default value: `undefined` */ "volume profile visible range.developing poc.color": string; /** Default value: `0` */ "volume profile visible range.developing poc.linestyle": number; /** Default value: `1` */ "volume profile visible range.developing poc.linewidth": number; /** Default value: `step_line` */ "volume profile visible range.developing poc.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume profile visible range.developing poc.trackprice": boolean; /** Default value: `0` */ "volume profile visible range.developing poc.transparency": number; /** Default value: `0` */ "volume profile visible range.developing poc.display": number; /** Default value: `undefined` */ "volume profile visible range.developing va high.color": string; /** Default value: `0` */ "volume profile visible range.developing va high.linestyle": number; /** Default value: `1` */ "volume profile visible range.developing va high.linewidth": number; /** Default value: `step_line` */ "volume profile visible range.developing va high.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume profile visible range.developing va high.trackprice": boolean; /** Default value: `0` */ "volume profile visible range.developing va high.transparency": number; /** Default value: `0` */ "volume profile visible range.developing va high.display": number; /** Default value: `undefined` */ "volume profile visible range.developing va low.color": string; /** Default value: `0` */ "volume profile visible range.developing va low.linestyle": number; /** Default value: `1` */ "volume profile visible range.developing va low.linewidth": number; /** Default value: `step_line` */ "volume profile visible range.developing va low.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume profile visible range.developing va low.trackprice": boolean; /** Default value: `0` */ "volume profile visible range.developing va low.transparency": number; /** Default value: `0` */ "volume profile visible range.developing va low.display": number; /** * - Default value: `0` * - Input type: `time` * - IsHidden: `true` * - Max: `253370764800` * - Min: `-253370764800` */ "volume profile visible range.first visible bar time": number; /** * - Default value: `0` * - Input type: `time` * - IsHidden: `true` * - Max: `253370764800` * - Min: `-253370764800` */ "volume profile visible range.last visible bar time": number; /** * - Default value: `24` * - Input type: `integer` * - Max: `1000000` * - Min: `1` */ "volume profile visible range.row size": number; /** * - Default value: `Number Of Rows` * - Input type: `text` * - Options: `["Number Of Rows","Ticks Per Row"]` */ "volume profile visible range.rows layout": string; /** * - Default value: `70` * - Input type: `integer` * - Max: `100` * - Min: `0` */ "volume profile visible range.value area volume": number; /** * - Default value: `Up/Down` * - Input type: `text` * - Options: `["Up/Down","Total","Delta"]` */ "volume profile visible range.volume": string; /** Default value: `15` */ "vortex indicator.vi +.display": number; /** Default value: `0` */ "vortex indicator.vi +.linestyle": number; /** Default value: `1` */ "vortex indicator.vi +.linewidth": number; /** Default value: `line` */ "vortex indicator.vi +.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "vortex indicator.vi +.trackprice": boolean; /** Default value: `0` */ "vortex indicator.vi +.transparency": number; /** Default value: `#2196F3` */ "vortex indicator.vi +.color": string; /** Default value: `15` */ "vortex indicator.vi -.display": number; /** Default value: `0` */ "vortex indicator.vi -.linestyle": number; /** Default value: `1` */ "vortex indicator.vi -.linewidth": number; /** Default value: `line` */ "vortex indicator.vi -.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "vortex indicator.vi -.trackprice": boolean; /** Default value: `0` */ "vortex indicator.vi -.transparency": number; /** Default value: `#E91E63` */ "vortex indicator.vi -.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `2` * - Max: `1000000000000` */ "vortex indicator.period": number; /** Default value: `#7E57C2` */ "williams %r.hlines background.color": string; /** Default value: `90` */ "williams %r.hlines background.transparency": number; /** Default value: `true` */ "williams %r.hlines background.visible": boolean; /** Default value: `#787B86` */ "williams %r.upperlimit.color": string; /** Default value: `2` */ "williams %r.upperlimit.linestyle": number; /** Default value: `1` */ "williams %r.upperlimit.linewidth": number; /** Default value: `true` */ "williams %r.upperlimit.visible": boolean; /** Default value: `-20` */ "williams %r.upperlimit.value": number; /** Default value: `#787B86` */ "williams %r.lowerlimit.color": string; /** Default value: `2` */ "williams %r.lowerlimit.linestyle": number; /** Default value: `1` */ "williams %r.lowerlimit.linewidth": number; /** Default value: `true` */ "williams %r.lowerlimit.visible": boolean; /** Default value: `-80` */ "williams %r.lowerlimit.value": number; /** Default value: `15` */ "williams %r.plot.display": number; /** Default value: `0` */ "williams %r.plot.linestyle": number; /** Default value: `1` */ "williams %r.plot.linewidth": number; /** Default value: `line` */ "williams %r.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "williams %r.plot.trackprice": boolean; /** Default value: `0` */ "williams %r.plot.transparency": number; /** Default value: `#7E57C2` */ "williams %r.plot.color": string; /** * - Default value: `14` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "williams %r.length": number; /** Default value: `15` */ "williams alligator.jaw.display": number; /** Default value: `0` */ "williams alligator.jaw.linestyle": number; /** Default value: `1` */ "williams alligator.jaw.linewidth": number; /** Default value: `line` */ "williams alligator.jaw.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "williams alligator.jaw.trackprice": boolean; /** Default value: `0` */ "williams alligator.jaw.transparency": number; /** Default value: `#2196F3` */ "williams alligator.jaw.color": string; /** Default value: `15` */ "williams alligator.teeth.display": number; /** Default value: `0` */ "williams alligator.teeth.linestyle": number; /** Default value: `1` */ "williams alligator.teeth.linewidth": number; /** Default value: `line` */ "williams alligator.teeth.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "williams alligator.teeth.trackprice": boolean; /** Default value: `0` */ "williams alligator.teeth.transparency": number; /** Default value: `#E91E63` */ "williams alligator.teeth.color": string; /** Default value: `15` */ "williams alligator.lips.display": number; /** Default value: `0` */ "williams alligator.lips.linestyle": number; /** Default value: `1` */ "williams alligator.lips.linewidth": number; /** Default value: `line` */ "williams alligator.lips.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "williams alligator.lips.trackprice": boolean; /** Default value: `0` */ "williams alligator.lips.transparency": number; /** Default value: `#66BB6A` */ "williams alligator.lips.color": string; /** * - Default value: `21` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "williams alligator.jaw length": number; /** * - Default value: `13` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "williams alligator.teeth length": number; /** * - Default value: `8` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "williams alligator.lips length": number; /** * - Default value: `8` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "williams alligator.jaw offset": number; /** * - Default value: `5` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "williams alligator.teeth offset": number; /** * - Default value: `3` * - Input type: `integer` * - Min: `1` * - Max: `2000` */ "williams alligator.lips offset": number; /** Default value: `15` */ "williams fractal.down fractals.display": number; /** Default value: `shape_triangle_down` */ "williams fractal.down fractals.plottype": string; /** Default value: `BelowBar` */ "williams fractal.down fractals.location": string; /** Default value: `0` */ "williams fractal.down fractals.transparency": number; /** Default value: `#F23645` */ "williams fractal.down fractals.color": string; /** Default value: `15` */ "williams fractal.up fractals.display": number; /** Default value: `shape_triangle_up` */ "williams fractal.up fractals.plottype": string; /** Default value: `AboveBar` */ "williams fractal.up fractals.location": string; /** Default value: `0` */ "williams fractal.up fractals.transparency": number; /** Default value: `#089981` */ "williams fractal.up fractals.color": string; /** * - Default value: `2` * - Input type: `integer` * - Min: `2` * - Max: `1000000000000` */ "williams fractal.periods": number; /** Default value: `15` */ "zig zag.plot.display": number; /** Default value: `0` */ "zig zag.plot.linestyle": number; /** Default value: `2` */ "zig zag.plot.linewidth": number; /** Default value: `line` */ "zig zag.plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "zig zag.plot.trackprice": boolean; /** Default value: `0` */ "zig zag.plot.transparency": number; /** Default value: `#2196F3` */ "zig zag.plot.color": string; /** * - Default value: `5` * - Input type: `float` * - Min: `0.001` * - Max: `100` */ "zig zag.deviation": number; /** * - Default value: `10` * - Input type: `integer` * - Min: `2` * - Max: `1000` */ "zig zag.depth": number; "barStyle.upColor": string; "barStyle.downColor": string; "barStyle.barColorsOnPrevClose": boolean; "barStyle.dontDrawOpen": boolean; "barStyle.thinBars": boolean; "candleStyle.upColor": string; "candleStyle.downColor": string; "candleStyle.drawWick": boolean; "candleStyle.drawBorder": boolean; "candleStyle.drawBody": boolean; "candleStyle.borderColor": string; "candleStyle.borderUpColor": string; "candleStyle.borderDownColor": string; "candleStyle.wickColor": string; "candleStyle.wickUpColor": string; "candleStyle.wickDownColor": string; "candleStyle.barColorsOnPrevClose": boolean; "areaStyle.color1": string; "areaStyle.color2": string; "areaStyle.linecolor": string; "areaStyle.linestyle": number; "areaStyle.linewidth": number; "areaStyle.transparency": number; "baselineStyle.topFillColor1": string; "baselineStyle.topFillColor2": string; "baselineStyle.bottomFillColor1": string; "baselineStyle.bottomFillColor2": string; "baselineStyle.topLineColor": string; "baselineStyle.bottomLineColor": string; "baselineStyle.baselineColor": string; "baselineStyle.topLineWidth": number; "baselineStyle.bottomLineWidth": number; "baselineStyle.transparency": number; "baselineStyle.baseLevelPercentage": number; "hiLoStyle.color": string; "hiLoStyle.showBorders": boolean; "hiLoStyle.borderColor": string; "hiLoStyle.showLabels": boolean; "hiLoStyle.labelColor": string; "hiLoStyle.drawBody": boolean; "columnStyle.upColor": string; "columnStyle.downColor": string; "columnStyle.barColorsOnPrevClose": boolean; "columnStyle.baselinePosition": string; "lineWithMarkersStyle.highLineColor": string; "lineWithMarkersStyle.highLineStyle": number; "lineWithMarkersStyle.highLineWidth": number; "lineWithMarkersStyle.lowLineColor": string; "lineWithMarkersStyle.lowLineStyle": number; "lineWithMarkersStyle.lowLineWidth": number; "lineWithMarkersStyle.closeLineColor": string; "lineWithMarkersStyle.closeLineStyle": number; "lineWithMarkersStyle.closeLineWidth": number; "lineWithMarkersStyle.highCloseFillColor": string; "lineWithMarkersStyle.closeLowFillColor": string; [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; /** Visibility */ 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 { /** Input type is Price */ readonly type: StudyInputType.Price; /** Default value */ readonly defval: number; /** Maximum value */ readonly max?: number; /** Minimum value */ readonly min?: number; /** Step size for value */ readonly step?: number; } export interface StudyResolutionInputInfo extends StudyInputBaseInfo { /** Input type is Resolution */ readonly type: StudyInputType.Resolution; /** Default value */ readonly defval: ResolutionString; /** Source Input Options */ readonly options?: string[]; /** Options for Input Titles */ readonly optionsTitles?: StudyInputOptionsTitles; /** Is Monday to Friday Resolution */ 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 { /** Input type is Session */ readonly type: StudyInputType.Session; /** Default value */ readonly defval: string; /** Source Input Options */ readonly options?: string[]; /** Options for Input Titles */ 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; } export interface StudySourceInputInfo extends StudyInputBaseInfo { /** Input type is Source */ readonly type: StudyInputType.Source; /** Default value */ readonly defval: StudyPriceSource | string; /** Source Input Options */ readonly options?: (StudyPriceSource | string)[]; /** Options for Input Titles */ 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?: Record | undefined>; /** * 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 { /** * 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 | number; /** * Char to display with the plot. Applicable only to chars plot types. */ readonly char?: string; /** * 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; /** * Info about the Price Scale formatting */ readonly format?: Partial; /** * optional flag to indicate the plot should be drawn on main page */ readonly forceOverlay?: boolean; } export interface StudySymbolInputInfo extends StudyInputBaseInfo { /** Input type is Symbol */ readonly type: StudyInputType.Symbol; /** Default value for the input */ readonly defval?: string; /** Is the input optional */ 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 { /** Input type is Text */ readonly type: StudyInputType.Text; /** Default value for the input */ readonly defval: string; /** Options for the text input */ readonly options?: string[]; /** Options for the titles of the text input */ readonly optionsTitles?: StudyInputOptionsTitles; } export interface StudyTextareaInputInfo extends StudyInputBaseInfo { /** Input type is TextArea */ readonly type: StudyInputType.Textarea; /** Default value for the input */ readonly defval: string; } export interface StudyTimeInputInfo extends StudyInputBaseInfo { /** Input type is Time */ readonly type: StudyInputType.Time; /** Default value for the input */ readonly defval: number; /** Maximum time */ readonly max: number; /** Minimum time */ readonly min: number; } /** * A description of a up colorer plot. */ export interface StudyUpColorerPlotInfo extends StudyPalettedPlotInfo, StudyTargetedPlotInfo { /** @inheritDoc */ readonly type: StudyPlotType.UpColorer; } /** * Text with styles */ export interface StyledText { /** * Text */ text: string; /** * Font */ font?: string; /** * Font family */ fontFamily?: string; /** * Font feature settings */ fontFeatureSettings?: string; /** * Font kerning */ fontKerning?: string; /** * Font optical sizing */ fontOpticalSizing?: string; /** * Font palette */ fontPalette?: string; /** * Font size */ fontSize?: string; /** * Font size adjust */ fontSizeAdjust?: string; /** * Font stretch */ fontStretch?: string; /** * Font style */ fontStyle?: string; /** * Font synthesis */ fontSynthesis?: string; /** * Font variant */ fontVariant?: string; /** * Font variant alternates */ fontVariantAlternates?: string; /** * Font variant caps */ fontVariantCaps?: string; /** * Font variant east asian */ fontVariantEastAsian?: string; /** * Font variant ligatures */ fontVariantLigatures?: string; /** * Font variant numerics */ fontVariantNumeric?: string; /** * Font variant position */ fontVariantPosition?: string; /** * Font variation settings */ fontVariationSettings?: string; /** * Font weight */ fontWeight?: string; /** * Color */ color?: string; /** * Line height */ lineHeight?: string; /** * Letter spacing */ letterSpacing?: string; } export interface SubLayoutSizesState { percent: number; substate?: SubLayoutSizesState[]; } 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](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale#quick-trading). * @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 Platform. * @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 Platform. */ layout_changed: EmptyCallback; /** * Active chart has changed. * **Note:** this event is only applicable to Trading Platform. * @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: EmptyCallback; /** * Panes' order has changed. */ panes_order_changed: EmptyCallback; /** * Chart's widget bar is shown/hidden. * @param {boolean} isVisible - if the widget bar is currently hidden */ widgetbar_visibility_changed: (isVisible: boolean) => void; /** * The _Save as default_ option is selected in the drop-down menu of the indicator settings. * @param {EntityId} id - entity ID */ study_dialog_save_defaults: (id: EntityId) => void; /** * Time interval has been changed. * Can come from either the bottom toolbar or the {@link setTimeFrame} API. * @param {RangeOptions} range - Object that represents a selected time frame. */ timeframe_interval: (range: RangeOptions) => void; /** * Drag start * @param {boolean} enabled - if drag export is currently enabled */ dragStart: (params: DragStartParams) => void; /** * Drag end */ dragEnd: EmptyCallback; /** * Fired when the chart theme is updated. This event can be triggered in several ways: * - When a user applies a saved [chart template](https://www.tradingview.com/charting-library-docs/latest/saving_loading/saving_loading#chart-templates). * - When the chart theme is reset to the default settings. (`isStandardTheme` parameter will be true) * - When the {@link IChartingLibraryWidget.changeTheme} method is called. * - When the {@link IChartWidgetApi.loadChartTemplate} method is called. * * @param {string} themeName - The name of the chart theme or template that was applied. * @param {boolean} isStandardTheme - `true` if the default built-in theme was restored; `false`, if a custom chart template was applied. * @param {boolean} onlyActiveChart - `false`, when applied to all charts */ chart_theme_changed: (themeName: string, isStandardTheme: boolean, onlyActiveChart: boolean) => 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; } /** * Overrides for the 'SuperTrend' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface SuperTrendIndicatorOverrides { /** Default value: `15` */ "supertrend.display": number; /** Default value: `0` */ "supertrend.linestyle": number; /** Default value: `3` */ "supertrend.linewidth": number; /** Default value: `line` */ "supertrend.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "supertrend.trackprice": boolean; /** Default value: `35` */ "supertrend.transparency": number; /** Default value: `#000080` */ "supertrend.color": string; /** Default value: `15` */ "up arrow.display": number; /** Default value: `0` */ "up arrow.linestyle": number; /** Default value: `3` */ "up arrow.linewidth": number; /** Default value: `shape_arrow_up` */ "up arrow.plottype": string; /** Default value: `false` */ "up arrow.trackprice": boolean; /** Default value: `BelowBar` */ "up arrow.location": string; /** Default value: `35` */ "up arrow.transparency": number; /** Default value: `#00FF00` */ "up arrow.color": string; /** Default value: `15` */ "down arrow.display": number; /** Default value: `0` */ "down arrow.linestyle": number; /** Default value: `3` */ "down arrow.linewidth": number; /** Default value: `shape_arrow_down` */ "down arrow.plottype": string; /** Default value: `false` */ "down arrow.trackprice": boolean; /** Default value: `AboveBar` */ "down arrow.location": string; /** Default value: `35` */ "down arrow.transparency": number; /** Default value: `#FF0000` */ "down arrow.color": string; [key: string]: StudyOverrideValueType; } export interface SymbolExt extends LibrarySymbolInfo { } export interface SymbolFormatterProperties { base: [ brokerSymbolProperty: string, symbolProperty: string ]; withMessage: [ brokerSymbolProperty: string, symbolProperty: string, messageProperty: string ]; } export interface SymbolInfoPriceSource { /** Unique ID */ id: string; /** Short name */ name: string; } export interface SymbolInputOptions extends CommonInputOptions { } export interface SymbolInputSymbolSource { /** Input type is Symbol Source */ type: "symbolInputSymbolSource"; /** Input ID */ 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#enable-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; /** * Trading session type, such as `"regular"` or `"extended"`, that the chart should currently display. */ 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 SymbolSpecificTradingOptions { /** Array of strings with valid duration values. You can check that in Order Ticket. */ allowedDurations?: string[]; /** Supported order types for the instrument. */ allowedOrderTypes?: OrderType[]; /** * Whether order brackets are supported for the symbol. * Defaults to the value in the config. */ supportOrderBrackets?: boolean; /** * Whether brackets could be set in ticks/pips. * @default true */ supportBracketsInPips?: boolean; /** * Using this flag you can disable adding brackets to the existing order. */ supportAddBracketsToExistingOrder?: boolean; /** * Using this flag you can disable existing order's brackets modification. If you set it to `false`, * additional fields will be disabled in Order Ticket on the chart, */ supportModifyBrackets?: boolean; /** * Whether position brackets are supported for the symbol. * Defaults to the value in the config. */ supportPositionBrackets?: boolean; /** * Whether trade brackets are supported for the symbol. * Defaults to the value in the config. */ supportIndividualPositionBrackets?: boolean; /** * Whether position reversing is supported for the symbol. * Defaults to the value in the config. */ supportReversePosition?: boolean; /** * A symbol-specific message that can be used to warn users. */ warningMessage?: string; /** * Whether the integration supports the modification of existing position brackets. */ supportModifyPositionBrackets?: boolean; /** * Whether the integration supports the modification of existing order brackets. */ supportModifyOrderBrackets?: boolean; /** * Whether the risk controls and order info should be shown. */ supportRiskControlsAndInfo?: boolean; } export interface SymbolValueFormatterFormatOptions extends NumberFormatterFormatOptions { /** Add plus sign to result string */ signPositive?: boolean; } export interface TAFunctions { change(source: IPineSeries): IPineSeries; correlation(source1: IPineSeries, source2: IPineSeries, length: number): IPineSeries; cum(source: IPineSeries): IPineSeries; ema(source: IPineSeries, length: number): IPineSeries; rma(source: IPineSeries, length: number): IPineSeries; sma(source: IPineSeries, length: number): IPineSeries; vwap(source: IPineSeries, anchor: boolean, stdDevMult: number): [ IPineSeries, IPineSeries, IPineSeries ]; wma(source: IPineSeries, length: number): IPineSeries; } /** * Overrides for the 'TRIX' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface TRIXIndicatorOverrides { /** Default value: `#787B86` */ "zero.color": string; /** Default value: `2` */ "zero.linestyle": number; /** Default value: `1` */ "zero.linewidth": number; /** Default value: `true` */ "zero.visible": boolean; /** Default value: `0` */ "zero.value": number; /** Default value: `15` */ "trix.display": number; /** Default value: `0` */ "trix.linestyle": number; /** Default value: `1` */ "trix.linewidth": number; /** Default value: `line` */ "trix.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "trix.trackprice": boolean; /** Default value: `0` */ "trix.transparency": number; /** Default value: `#F23645` */ "trix.color": string; [key: string]: StudyOverrideValueType; } 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; } export interface TextFieldMetaInfo extends CustomInputFieldMetaInfo { /** @inheritDoc */ inputType: "TextField"; /** @inheritDoc */ value: string; /** @inheritDoc */ validator?: TextInputFieldValidator; /** @inheritDoc */ maskWithAsterisk?: boolean; } /** * Override properties for the Text drawing tool. */ export interface TextLineToolOverrides { /** Default value: `rgba(91, 133, 191, 0.3)` */ "linetooltext.backgroundColor": string; /** Default value: `70` */ "linetooltext.backgroundTransparency": number; /** Default value: `false` */ "linetooltext.bold": boolean; /** Default value: `#667b8b` */ "linetooltext.borderColor": string; /** Default value: `#2962FF` */ "linetooltext.color": string; /** Default value: `false` */ "linetooltext.drawBorder": boolean; /** Default value: `false` */ "linetooltext.fillBackground": boolean; /** Default value: `true` */ "linetooltext.fixedSize": boolean; /** Default value: `14` */ "linetooltext.fontsize": number; /** Default value: `false` */ "linetooltext.italic": boolean; /** Default value: `false` */ "linetooltext.wordWrap": boolean; /** Default value: `200` */ "linetooltext.wordWrapWidth": number; } 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; } /** * Override properties for the Textabsolute drawing tool. */ export interface TextabsoluteLineToolOverrides { /** Default value: `rgba(155, 190, 213, 0.3)` */ "linetooltextabsolute.backgroundColor": string; /** Default value: `70` */ "linetooltextabsolute.backgroundTransparency": number; /** Default value: `false` */ "linetooltextabsolute.bold": boolean; /** Default value: `#667b8b` */ "linetooltextabsolute.borderColor": string; /** Default value: `#2962FF` */ "linetooltextabsolute.color": string; /** Default value: `false` */ "linetooltextabsolute.drawBorder": boolean; /** Default value: `false` */ "linetooltextabsolute.fillBackground": boolean; /** Default value: `false` */ "linetooltextabsolute.fixedSize": boolean; /** Default value: `14` */ "linetooltextabsolute.fontsize": number; /** Default value: `false` */ "linetooltextabsolute.italic": boolean; /** Default value: `false` */ "linetooltextabsolute.wordWrap": boolean; /** Default value: `200` */ "linetooltextabsolute.wordWrapWidth": number; } /** * Override properties for the Threedrivers drawing tool. */ export interface ThreedriversLineToolOverrides { /** Default value: `rgba(149, 40, 204, 0.5)` */ "linetoolthreedrivers.backgroundColor": string; /** Default value: `false` */ "linetoolthreedrivers.bold": boolean; /** Default value: `#673ab7` */ "linetoolthreedrivers.color": string; /** Default value: `true` */ "linetoolthreedrivers.fillBackground": boolean; /** Default value: `12` */ "linetoolthreedrivers.fontsize": number; /** Default value: `false` */ "linetoolthreedrivers.italic": boolean; /** Default value: `2` */ "linetoolthreedrivers.linewidth": number; /** Default value: `#ffffff` */ "linetoolthreedrivers.textcolor": string; /** Default value: `50` */ "linetoolthreedrivers.transparency": number; } export interface TickerFunctions { modify(symbol: string, session?: SessionId): TickerId; } /** * 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 time frames 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; /** Time frame string. For example `'1D'` or `'6M'`. */ 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 [bar spacing](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#bar-spacing). Should be greater than 0. * * ```javascript * time_scale: { * min_bar_spacing: 0.01 * }, * ``` * Note that using this property forces the library to perform more calculations. This may lead to the following issues: * * - The chart UI may update slowly because the browser thread is blocked. * * - The browser may use excessive memory or even run out of memory due to the large number of bars on the screen. * * Use this option carefully and only when necessary. */ min_bar_spacing?: number; } /** * Override properties for the Timecycles drawing tool. */ export interface TimecyclesLineToolOverrides { /** Default value: `rgba(106, 168, 79, 0.5)` */ "linetooltimecycles.backgroundColor": string; /** Default value: `true` */ "linetooltimecycles.fillBackground": boolean; /** Default value: `#159980` */ "linetooltimecycles.linecolor": string; /** Default value: `0` */ "linetooltimecycles.linestyle": number; /** Default value: `2` */ "linetooltimecycles.linewidth": number; /** Default value: `50` */ "linetooltimecycles.transparency": number; } export interface TimeframeFunctions { change(resolution: ResolutionString): boolean; isDWM(): boolean; } export interface TimescaleMark { /** ID of the timescale mark */ id: string | number; /** * Time for the mark. * Unix timestamp in seconds. */ 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 */ get 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 TradableSolutionsTypes { changeAccountSolution: ChangeAccountSolution; changeSymbolSolution: ChangeSymbolSolution; openUrlSolution: OpenUrlSolution; } 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; } /** * Represents the structure of {@link TradingTerminalWidgetOptions.trading_customization}. */ export interface TradingCustomization { /** Overrides for position lines created using the {@link IChartWidgetApi.createPositionLine} method. */ position?: Partial; /** Overrides for order lines created using the {@link IChartWidgetApi.createOrderLine} method. */ order?: Partial; /** Overrides for order lines created using the [Broker API](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts#broker-api). */ brokerOrder?: Partial; /** Overrides for position lines created using the [Broker API](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts#broker-api). */ brokerPosition?: Partial; } export interface TradingDialogOptions { /** Custom fields that are displayed in the Order Ticket. * Refer to the [Add custom fields](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#add-custom-fields) section for more information. * * **Example** * ```javascript * customFields: [ * { * inputType: 'TextWithCheckBox', * id: '2410', * title: 'Digital Signature', * placeHolder: 'Enter your personal digital signature', * value: { * text: '', * checked: false, * }, * customInfo: { * asterix: true, * checkboxTitle: 'Save', * }, * } * ] * ``` * */ 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 { /** * 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 in [Featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets). * * Example: * ```javascript * disabled_features: ["header_widget", "left_toolbar"], * ``` */ disabled_features?: TradingTerminalFeatureset[]; /** * 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 in [Featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets). * * Example: * ```javascript * enabled_features: ["move_logo_to_main_pane"], * ``` */ enabled_features?: TradingTerminalFeatureset[]; /** * See {@link ChartingLibraryWidgetOptions.favorites} */ favorites?: Favorites; /** * @deprecated * Defines the [configuration flags](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-features-configuration) for the Trading Platform. */ brokerConfig?: SingleBrokerMetaInfo; /** Defines the [configuration flags](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-features-configuration) for the Trading Platform. */ 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 connect a RSS feed to the _News_ widget. To do this, specify a {@link RssNewsFeedParams} object that should contain at least the default RSS configuration. * You can specify a different RSS for each symbol type or use only one for all symbols. For more information, refer to the [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news) article. * Note that if both `rss_news_feed` and {@link news_provider} properties are specified, `rss_news_feed` is ignored. * * @example * ```javascript * rss_news_feed: { * "default": { * url: "https://articlefeeds.nasdaq.com/nasdaq/symbols?symbol={SYMBOL}", * name: "NASDAQ" * } * } * ``` */ rss_news_feed?: RssNewsFeedParams; /** * Title for the News Widget */ rss_news_title?: string; /** * Use this property to connect any custom news source to the _News_ widget. To do this, you should specify {@link GetNewsFunction} that the library calls to request data for the widget. * In response, you should pass a {@link GetNewsResponse} object to the callback function. * In this object, specify an array of {@link NewsItem} objects that contain data for each news item. * For more information, refer to the [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news) article. * Note that if both {@link rss_news_feed} and `news_provider` properties are specified, `rss_news_feed` is ignored. * * Consider the following example. An API endpoint returns news items represented in JSON and the format matches the `NewsItem` interface. * In this case, you implement `GetNewsFunction` as follows: * * ```javascript * const jsonNewsApiUrl = 'https://www.example.com'; * new TradingView.widget({ * // ... * news_provider: function getNews(symbol, callback) { * const requestUrl = new URL('/news/', jsonNewsApiUrl); * requestUrl.searchParams.append('symbol', symbol); * fetch(requestUrl) * .then(res => res.json()) * .then(json => { * callback({ * newsItems: json, * }); * }); * } * }); * ``` */ news_provider?: GetNewsFunction; /** Overrides order and position lines created either using the [Broker API](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts#broker-api) or {@link IChartWidgetApi.createOrderLine} and {@link IChartWidgetApi.createPositionLine} methods. */ trading_customization?: TradingCustomization; /** * 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): IBrokerTerminal; /** * Setting this property makes the library write detailed [Broker API](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts#broker-api) and [Trading Host](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-concepts#trading-host) logs into the browser console. * * ```javascript * debug_broker: 'normal', * ``` * * The logs include the calls and return values for methods invoked on the * host ({@link IBrokerConnectionAdapterHost}) and broker ({@link IBrokerTerminal}). * Since the method calls can be asynchronous, you can use the ID numbers in each message to match * the calls to responses. */ debug_broker?: BrokerDebugMode; } /** * Overrides for the 'Trend Strength Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface TrendStrengthIndexIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#FF5252` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Override properties for the Trendangle drawing tool. */ export interface TrendangleLineToolOverrides { /** Default value: `false` */ "linetooltrendangle.alwaysShowStats": boolean; /** Default value: `false` */ "linetooltrendangle.bold": boolean; /** Default value: `false` */ "linetooltrendangle.extendLeft": boolean; /** Default value: `false` */ "linetooltrendangle.extendRight": boolean; /** Default value: `12` */ "linetooltrendangle.fontsize": number; /** Default value: `false` */ "linetooltrendangle.italic": boolean; /** Default value: `#2962FF` */ "linetooltrendangle.linecolor": string; /** Default value: `0` */ "linetooltrendangle.linestyle": number; /** Default value: `2` */ "linetooltrendangle.linewidth": number; /** Default value: `false` */ "linetooltrendangle.showBarsRange": boolean; /** Default value: `false` */ "linetooltrendangle.showMiddlePoint": boolean; /** Default value: `false` */ "linetooltrendangle.showPercentPriceRange": boolean; /** Default value: `false` */ "linetooltrendangle.showPipsPriceRange": boolean; /** Default value: `false` */ "linetooltrendangle.showPriceLabels": boolean; /** Default value: `false` */ "linetooltrendangle.showPriceRange": boolean; /** Default value: `2` */ "linetooltrendangle.statsPosition": number; } /** * Override properties for the Trendbasedfibextension drawing tool. */ export interface TrendbasedfibextensionLineToolOverrides { /** Default value: `false` */ "linetooltrendbasedfibextension.coeffsAsPercents": boolean; /** Default value: `false` */ "linetooltrendbasedfibextension.extendLines": boolean; /** Default value: `false` */ "linetooltrendbasedfibextension.extendLinesLeft": boolean; /** Default value: `false` */ "linetooltrendbasedfibextension.fibLevelsBasedOnLogScale": boolean; /** Default value: `true` */ "linetooltrendbasedfibextension.fillBackground": boolean; /** Default value: `left` */ "linetooltrendbasedfibextension.horzLabelsAlign": string; /** Default value: `center` */ "linetooltrendbasedfibextension.horzTextAlign": string; /** Default value: `12` */ "linetooltrendbasedfibextension.labelFontSize": number; /** Default value: `0` */ "linetooltrendbasedfibextension.level1.coeff": number; /** Default value: `#808080` */ "linetooltrendbasedfibextension.level1.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level1.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level1.visible": boolean; /** Default value: `3.618` */ "linetooltrendbasedfibextension.level10.coeff": number; /** Default value: `#9c27b0` */ "linetooltrendbasedfibextension.level10.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level10.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level10.visible": boolean; /** Default value: `4.236` */ "linetooltrendbasedfibextension.level11.coeff": number; /** Default value: `#e91e63` */ "linetooltrendbasedfibextension.level11.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level11.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level11.visible": boolean; /** Default value: `1.272` */ "linetooltrendbasedfibextension.level12.coeff": number; /** Default value: `#FF9800` */ "linetooltrendbasedfibextension.level12.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level12.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level12.visible": boolean; /** Default value: `1.414` */ "linetooltrendbasedfibextension.level13.coeff": number; /** Default value: `#F23645` */ "linetooltrendbasedfibextension.level13.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level13.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level13.visible": boolean; /** Default value: `2.272` */ "linetooltrendbasedfibextension.level14.coeff": number; /** Default value: `#FF9800` */ "linetooltrendbasedfibextension.level14.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level14.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level14.visible": boolean; /** Default value: `2.414` */ "linetooltrendbasedfibextension.level15.coeff": number; /** Default value: `#4caf50` */ "linetooltrendbasedfibextension.level15.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level15.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level15.visible": boolean; /** Default value: `2` */ "linetooltrendbasedfibextension.level16.coeff": number; /** Default value: `#089981` */ "linetooltrendbasedfibextension.level16.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level16.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level16.visible": boolean; /** Default value: `3` */ "linetooltrendbasedfibextension.level17.coeff": number; /** Default value: `#00bcd4` */ "linetooltrendbasedfibextension.level17.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level17.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level17.visible": boolean; /** Default value: `3.272` */ "linetooltrendbasedfibextension.level18.coeff": number; /** Default value: `#808080` */ "linetooltrendbasedfibextension.level18.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level18.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level18.visible": boolean; /** Default value: `3.414` */ "linetooltrendbasedfibextension.level19.coeff": number; /** Default value: `#2962FF` */ "linetooltrendbasedfibextension.level19.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level19.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level19.visible": boolean; /** Default value: `0.236` */ "linetooltrendbasedfibextension.level2.coeff": number; /** Default value: `#F23645` */ "linetooltrendbasedfibextension.level2.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level2.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level2.visible": boolean; /** Default value: `4` */ "linetooltrendbasedfibextension.level20.coeff": number; /** Default value: `#F23645` */ "linetooltrendbasedfibextension.level20.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level20.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level20.visible": boolean; /** Default value: `4.272` */ "linetooltrendbasedfibextension.level21.coeff": number; /** Default value: `#9c27b0` */ "linetooltrendbasedfibextension.level21.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level21.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level21.visible": boolean; /** Default value: `4.414` */ "linetooltrendbasedfibextension.level22.coeff": number; /** Default value: `#e91e63` */ "linetooltrendbasedfibextension.level22.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level22.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level22.visible": boolean; /** Default value: `4.618` */ "linetooltrendbasedfibextension.level23.coeff": number; /** Default value: `#FF9800` */ "linetooltrendbasedfibextension.level23.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level23.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level23.visible": boolean; /** Default value: `4.764` */ "linetooltrendbasedfibextension.level24.coeff": number; /** Default value: `#089981` */ "linetooltrendbasedfibextension.level24.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level24.text": string; /** Default value: `false` */ "linetooltrendbasedfibextension.level24.visible": boolean; /** Default value: `0.382` */ "linetooltrendbasedfibextension.level3.coeff": number; /** Default value: `#FF9800` */ "linetooltrendbasedfibextension.level3.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level3.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level3.visible": boolean; /** Default value: `0.5` */ "linetooltrendbasedfibextension.level4.coeff": number; /** Default value: `#4caf50` */ "linetooltrendbasedfibextension.level4.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level4.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level4.visible": boolean; /** Default value: `0.618` */ "linetooltrendbasedfibextension.level5.coeff": number; /** Default value: `#089981` */ "linetooltrendbasedfibextension.level5.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level5.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level5.visible": boolean; /** Default value: `0.786` */ "linetooltrendbasedfibextension.level6.coeff": number; /** Default value: `#00bcd4` */ "linetooltrendbasedfibextension.level6.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level6.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level6.visible": boolean; /** Default value: `1` */ "linetooltrendbasedfibextension.level7.coeff": number; /** Default value: `#808080` */ "linetooltrendbasedfibextension.level7.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level7.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level7.visible": boolean; /** Default value: `1.618` */ "linetooltrendbasedfibextension.level8.coeff": number; /** Default value: `#2962FF` */ "linetooltrendbasedfibextension.level8.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level8.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level8.visible": boolean; /** Default value: `2.618` */ "linetooltrendbasedfibextension.level9.coeff": number; /** Default value: `#F23645` */ "linetooltrendbasedfibextension.level9.color": string; /** Default value: `undefined` */ "linetooltrendbasedfibextension.level9.text": string; /** Default value: `true` */ "linetooltrendbasedfibextension.level9.visible": boolean; /** Default value: `0` */ "linetooltrendbasedfibextension.levelsStyle.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibextension.levelsStyle.linewidth": number; /** Default value: `false` */ "linetooltrendbasedfibextension.reverse": boolean; /** Default value: `true` */ "linetooltrendbasedfibextension.showCoeffs": boolean; /** Default value: `true` */ "linetooltrendbasedfibextension.showPrices": boolean; /** Default value: `true` */ "linetooltrendbasedfibextension.showText": boolean; /** Default value: `80` */ "linetooltrendbasedfibextension.transparency": number; /** Default value: `#808080` */ "linetooltrendbasedfibextension.trendline.color": string; /** Default value: `2` */ "linetooltrendbasedfibextension.trendline.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibextension.trendline.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibextension.trendline.visible": boolean; /** Default value: `middle` */ "linetooltrendbasedfibextension.vertLabelsAlign": string; /** Default value: `middle` */ "linetooltrendbasedfibextension.vertTextAlign": string; } /** * Override properties for the Trendbasedfibtime drawing tool. */ export interface TrendbasedfibtimeLineToolOverrides { /** Default value: `true` */ "linetooltrendbasedfibtime.fillBackground": boolean; /** Default value: `right` */ "linetooltrendbasedfibtime.horzLabelsAlign": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level1.coeff": number; /** Default value: `#808080` */ "linetooltrendbasedfibtime.level1.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level1.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level1.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.level1.visible": boolean; /** Default value: `2.618` */ "linetooltrendbasedfibtime.level10.coeff": number; /** Default value: `#9c27b0` */ "linetooltrendbasedfibtime.level10.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level10.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level10.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.level10.visible": boolean; /** Default value: `3` */ "linetooltrendbasedfibtime.level11.coeff": number; /** Default value: `#673ab7` */ "linetooltrendbasedfibtime.level11.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level11.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level11.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.level11.visible": boolean; /** Default value: `0.382` */ "linetooltrendbasedfibtime.level2.coeff": number; /** Default value: `#F23645` */ "linetooltrendbasedfibtime.level2.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level2.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level2.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.level2.visible": boolean; /** Default value: `0.5` */ "linetooltrendbasedfibtime.level3.coeff": number; /** Default value: `#81c784` */ "linetooltrendbasedfibtime.level3.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level3.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level3.linewidth": number; /** Default value: `false` */ "linetooltrendbasedfibtime.level3.visible": boolean; /** Default value: `0.618` */ "linetooltrendbasedfibtime.level4.coeff": number; /** Default value: `#4caf50` */ "linetooltrendbasedfibtime.level4.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level4.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level4.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.level4.visible": boolean; /** Default value: `1` */ "linetooltrendbasedfibtime.level5.coeff": number; /** Default value: `#089981` */ "linetooltrendbasedfibtime.level5.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level5.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level5.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.level5.visible": boolean; /** Default value: `1.382` */ "linetooltrendbasedfibtime.level6.coeff": number; /** Default value: `#00bcd4` */ "linetooltrendbasedfibtime.level6.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level6.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level6.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.level6.visible": boolean; /** Default value: `1.618` */ "linetooltrendbasedfibtime.level7.coeff": number; /** Default value: `#808080` */ "linetooltrendbasedfibtime.level7.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level7.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level7.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.level7.visible": boolean; /** Default value: `2` */ "linetooltrendbasedfibtime.level8.coeff": number; /** Default value: `#2962FF` */ "linetooltrendbasedfibtime.level8.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level8.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level8.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.level8.visible": boolean; /** Default value: `2.382` */ "linetooltrendbasedfibtime.level9.coeff": number; /** Default value: `#e91e63` */ "linetooltrendbasedfibtime.level9.color": string; /** Default value: `0` */ "linetooltrendbasedfibtime.level9.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.level9.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.level9.visible": boolean; /** Default value: `true` */ "linetooltrendbasedfibtime.showCoeffs": boolean; /** Default value: `80` */ "linetooltrendbasedfibtime.transparency": number; /** Default value: `#808080` */ "linetooltrendbasedfibtime.trendline.color": string; /** Default value: `2` */ "linetooltrendbasedfibtime.trendline.linestyle": number; /** Default value: `2` */ "linetooltrendbasedfibtime.trendline.linewidth": number; /** Default value: `true` */ "linetooltrendbasedfibtime.trendline.visible": boolean; /** Default value: `bottom` */ "linetooltrendbasedfibtime.vertLabelsAlign": string; } /** * Override properties for the Trendline drawing tool. */ export interface TrendlineLineToolOverrides { /** Default value: `false` */ "linetooltrendline.alwaysShowStats": boolean; /** Default value: `false` */ "linetooltrendline.bold": boolean; /** Default value: `false` */ "linetooltrendline.extendLeft": boolean; /** Default value: `false` */ "linetooltrendline.extendRight": boolean; /** Default value: `14` */ "linetooltrendline.fontsize": number; /** Default value: `center` */ "linetooltrendline.horzLabelsAlign": string; /** Default value: `false` */ "linetooltrendline.italic": boolean; /** Default value: `0` */ "linetooltrendline.leftEnd": number; /** Default value: `#2962FF` */ "linetooltrendline.linecolor": string; /** Default value: `0` */ "linetooltrendline.linestyle": number; /** Default value: `2` */ "linetooltrendline.linewidth": number; /** Default value: `0` */ "linetooltrendline.rightEnd": number; /** Default value: `false` */ "linetooltrendline.showAngle": boolean; /** Default value: `false` */ "linetooltrendline.showBarsRange": boolean; /** Default value: `false` */ "linetooltrendline.showDateTimeRange": boolean; /** Default value: `false` */ "linetooltrendline.showDistance": boolean; /** Default value: `false` */ "linetooltrendline.showMiddlePoint": boolean; /** Default value: `false` */ "linetooltrendline.showPercentPriceRange": boolean; /** Default value: `false` */ "linetooltrendline.showPipsPriceRange": boolean; /** Default value: `false` */ "linetooltrendline.showPriceLabels": boolean; /** Default value: `false` */ "linetooltrendline.showPriceRange": boolean; /** Default value: `2` */ "linetooltrendline.statsPosition": number; /** Default value: `#2962FF` */ "linetooltrendline.textcolor": string; /** Default value: `bottom` */ "linetooltrendline.vertLabelsAlign": string; } /** * Override properties for the Triangle drawing tool. */ export interface TriangleLineToolOverrides { /** Default value: `rgba(8, 153, 129, 0.2)` */ "linetooltriangle.backgroundColor": string; /** Default value: `#089981` */ "linetooltriangle.color": string; /** Default value: `true` */ "linetooltriangle.fillBackground": boolean; /** Default value: `2` */ "linetooltriangle.linewidth": number; /** Default value: `80` */ "linetooltriangle.transparency": number; } /** * Override properties for the Trianglepattern drawing tool. */ export interface TrianglepatternLineToolOverrides { /** Default value: `#673ab7` */ "linetooltrianglepattern.backgroundColor": string; /** Default value: `false` */ "linetooltrianglepattern.bold": boolean; /** Default value: `#673ab7` */ "linetooltrianglepattern.color": string; /** Default value: `true` */ "linetooltrianglepattern.fillBackground": boolean; /** Default value: `12` */ "linetooltrianglepattern.fontsize": number; /** Default value: `false` */ "linetooltrianglepattern.italic": boolean; /** Default value: `2` */ "linetooltrianglepattern.linewidth": number; /** Default value: `#ffffff` */ "linetooltrianglepattern.textcolor": string; /** Default value: `85` */ "linetooltrianglepattern.transparency": number; } /** * Overrides for the 'Triple EMA' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface TripleEMAIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'True Strength Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface TrueStrengthIndexIndicatorOverrides { /** Default value: `#787B86` */ "zero.color": string; /** Default value: `2` */ "zero.linestyle": number; /** Default value: `1` */ "zero.linewidth": number; /** Default value: `true` */ "zero.visible": boolean; /** Default value: `0` */ "zero.value": number; /** Default value: `15` */ "true strength index.display": number; /** Default value: `0` */ "true strength index.linestyle": number; /** Default value: `1` */ "true strength index.linewidth": number; /** Default value: `line` */ "true strength index.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "true strength index.trackprice": boolean; /** Default value: `0` */ "true strength index.transparency": number; /** Default value: `#2196F3` */ "true strength index.color": string; /** Default value: `15` */ "signal.display": number; /** Default value: `0` */ "signal.linestyle": number; /** Default value: `1` */ "signal.linewidth": number; /** Default value: `line` */ "signal.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "signal.trackprice": boolean; /** Default value: `0` */ "signal.transparency": number; /** Default value: `#E91E63` */ "signal.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Typical Price' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface TypicalPriceIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#FF6D00` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Ultimate Oscillator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface UltimateOscillatorIndicatorOverrides { /** Default value: `15` */ "uo.display": number; /** Default value: `0` */ "uo.linestyle": number; /** Default value: `1` */ "uo.linewidth": number; /** Default value: `line` */ "uo.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "uo.trackprice": boolean; /** Default value: `0` */ "uo.transparency": number; /** Default value: `#F23645` */ "uo.color": string; [key: string]: StudyOverrideValueType; } /** * 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; } export interface UnitInfo { /** Unit displayed on the price scale if any is specified */ selectedUnit: string | null; /** Original units for price scale */ originalUnits: string[]; /** Groups of units (for example weight, energy, ...) */ availableGroups: string[]; /** * Symbols on the price scale */ symbols: 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"; } /** * Overrides for the 'VWAP' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VWAPIndicatorOverrides { /** Default value: `15` */ "vwap.display": number; /** Default value: `0` */ "vwap.linestyle": number; /** Default value: `1` */ "vwap.linewidth": number; /** Default value: `line` */ "vwap.plottype": LineStudyPlotStyleName; /** Default value: `0` */ "vwap.trackprice": number; /** Default value: `0` */ "vwap.transparency": number; /** Default value: `#2196F3` */ "vwap.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'VWMA' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VWMAIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } export interface ValueByStyleId { [styleId: string]: TValue | undefined; } /** * Vertical Line Preferences */ 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; } /** * Override properties for the Vertline drawing tool. */ export interface VertlineLineToolOverrides { /** Default value: `false` */ "linetoolvertline.bold": boolean; /** Default value: `true` */ "linetoolvertline.extendLine": boolean; /** Default value: `14` */ "linetoolvertline.fontsize": number; /** Default value: `center` */ "linetoolvertline.horzLabelsAlign": string; /** Default value: `false` */ "linetoolvertline.italic": boolean; /** Default value: `#2962FF` */ "linetoolvertline.linecolor": string; /** Default value: `0` */ "linetoolvertline.linestyle": number; /** Default value: `2` */ "linetoolvertline.linewidth": number; /** Default value: `true` */ "linetoolvertline.showTime": boolean; /** Default value: `#2962FF` */ "linetoolvertline.textcolor": string; /** Default value: `vertical` */ "linetoolvertline.textOrientation": string; /** Default value: `middle` */ "linetoolvertline.vertLabelsAlign": string; } /** * Boundaries of the price scale visible range in main series area */ export interface VisiblePriceRange { /** * The start of the range. */ from: number; /** * 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; } /** * Overrides for the 'Volatility Close-to-Close' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VolatilityClosetoCloseIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Volatility Index' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VolatilityIndexIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#FF5252` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Volatility O-H-L-C' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VolatilityOHLCIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#FF5252` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Volatility Zero Trend Close-to-Close' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VolatilityZeroTrendClosetoCloseIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Volume' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VolumeIndicatorOverrides { /** Default value: `15` */ "volume.display": number; /** Default value: `0` */ "volume.linestyle": number; /** Default value: `1` */ "volume.linewidth": number; /** Default value: `columns` */ "volume.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume.trackprice": boolean; /** Default value: `50` */ "volume.transparency": number; /** Default value: `#000080` */ "volume.color": string; /** Default value: `0` */ "volume ma:plot.display": number; /** Default value: `0` */ "volume ma:plot.linestyle": number; /** Default value: `1` */ "volume ma:plot.linewidth": number; /** Default value: `line` */ "volume ma:plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "volume ma:plot.trackprice": boolean; /** Default value: `0` */ "volume ma:plot.transparency": number; /** Default value: `#2196F3` */ "volume ma:plot.color": string; /** Default value: `0` */ "smoothed ma.display": number; /** Default value: `0` */ "smoothed ma.linestyle": number; /** Default value: `1` */ "smoothed ma.linewidth": number; /** Default value: `line` */ "smoothed ma.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "smoothed ma.trackprice": boolean; /** Default value: `0` */ "smoothed ma.transparency": number; /** Default value: `#2196F3` */ "smoothed ma.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Volume Oscillator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VolumeOscillatorIndicatorOverrides { /** Default value: `#787B86` */ "zero.color": string; /** Default value: `2` */ "zero.linestyle": number; /** Default value: `1` */ "zero.linewidth": number; /** Default value: `true` */ "zero.visible": boolean; /** Default value: `0` */ "zero.value": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Volume Profile Fixed Range' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VolumeProfileFixedRangeIndicatorOverrides { /** Default value: `undefined` */ "developing poc.color": string; /** Default value: `0` */ "developing poc.linestyle": number; /** Default value: `1` */ "developing poc.linewidth": number; /** Default value: `step_line` */ "developing poc.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "developing poc.trackprice": boolean; /** Default value: `0` */ "developing poc.transparency": number; /** Default value: `0` */ "developing poc.display": number; /** Default value: `undefined` */ "developing va high.color": string; /** Default value: `0` */ "developing va high.linestyle": number; /** Default value: `1` */ "developing va high.linewidth": number; /** Default value: `step_line` */ "developing va high.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "developing va high.trackprice": boolean; /** Default value: `0` */ "developing va high.transparency": number; /** Default value: `0` */ "developing va high.display": number; /** Default value: `undefined` */ "developing va low.color": string; /** Default value: `0` */ "developing va low.linestyle": number; /** Default value: `1` */ "developing va low.linewidth": number; /** Default value: `step_line` */ "developing va low.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "developing va low.trackprice": boolean; /** Default value: `0` */ "developing va low.transparency": number; /** Default value: `0` */ "developing va low.display": number; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Volume Profile Visible Range' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VolumeProfileVisibleRangeIndicatorOverrides { /** Default value: `undefined` */ "developing poc.color": string; /** Default value: `0` */ "developing poc.linestyle": number; /** Default value: `1` */ "developing poc.linewidth": number; /** Default value: `step_line` */ "developing poc.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "developing poc.trackprice": boolean; /** Default value: `0` */ "developing poc.transparency": number; /** Default value: `0` */ "developing poc.display": number; /** Default value: `undefined` */ "developing va high.color": string; /** Default value: `0` */ "developing va high.linestyle": number; /** Default value: `1` */ "developing va high.linewidth": number; /** Default value: `step_line` */ "developing va high.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "developing va high.trackprice": boolean; /** Default value: `0` */ "developing va high.transparency": number; /** Default value: `0` */ "developing va high.display": number; /** Default value: `undefined` */ "developing va low.color": string; /** Default value: `0` */ "developing va low.linestyle": number; /** Default value: `1` */ "developing va low.linewidth": number; /** Default value: `step_line` */ "developing va low.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "developing va low.trackprice": boolean; /** Default value: `0` */ "developing va low.transparency": number; /** Default value: `0` */ "developing va low.display": number; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Vortex Indicator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface VortexIndicatorIndicatorOverrides { /** Default value: `15` */ "vi +.display": number; /** Default value: `0` */ "vi +.linestyle": number; /** Default value: `1` */ "vi +.linewidth": number; /** Default value: `line` */ "vi +.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "vi +.trackprice": boolean; /** Default value: `0` */ "vi +.transparency": number; /** Default value: `#2196F3` */ "vi +.color": string; /** Default value: `15` */ "vi -.display": number; /** Default value: `0` */ "vi -.linestyle": number; /** Default value: `1` */ "vi -.linewidth": number; /** Default value: `line` */ "vi -.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "vi -.trackprice": boolean; /** Default value: `0` */ "vi -.transparency": number; /** Default value: `#E91E63` */ "vi -.color": string; [key: string]: StudyOverrideValueType; } 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 WatchlistSettings { /** * Sets the list of default symbols for watchlist. * Any item in the list which is prefixed with `###` will be considered a section divider in the watchlist. * @default [] * * **Example:** * ```js * default_symbols: ['###TOP SECTION', 'AAPL', 'IBM', '###SECOND SECTION', 'MSFT'] * ``` */ default_symbols: string[]; /** * Enables read-only mode for the watchlist. * @default false */ readonly?: boolean; } /** * Data provided to the {@link WatermarkContentProvider}. */ export interface WatermarkContentData { /** * Symbol Information. */ symbolInfo: LibrarySymbolInfo; /** * Current interval string. */ interval: string; } /** * Defines the text and font properties for a line of the watermark. */ export interface WatermarkLine { /** * Text to be displayed. */ text: string; /** * Font size to be used (defined in pixels). */ fontSize: number; /** * Line height (defined in pixels). */ lineHeight: number; /** * Vertical offset distance (defined in pixels). */ vertOffset: number; } 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?: WatchlistSettings; } /** * Overrides for the 'Williams Alligator' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface WilliamsAlligatorIndicatorOverrides { /** Default value: `15` */ "jaw.display": number; /** Default value: `0` */ "jaw.linestyle": number; /** Default value: `1` */ "jaw.linewidth": number; /** Default value: `line` */ "jaw.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "jaw.trackprice": boolean; /** Default value: `0` */ "jaw.transparency": number; /** Default value: `#2196F3` */ "jaw.color": string; /** Default value: `15` */ "teeth.display": number; /** Default value: `0` */ "teeth.linestyle": number; /** Default value: `1` */ "teeth.linewidth": number; /** Default value: `line` */ "teeth.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "teeth.trackprice": boolean; /** Default value: `0` */ "teeth.transparency": number; /** Default value: `#E91E63` */ "teeth.color": string; /** Default value: `15` */ "lips.display": number; /** Default value: `0` */ "lips.linestyle": number; /** Default value: `1` */ "lips.linewidth": number; /** Default value: `line` */ "lips.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "lips.trackprice": boolean; /** Default value: `0` */ "lips.transparency": number; /** Default value: `#66BB6A` */ "lips.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Williams Fractal' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface WilliamsFractalIndicatorOverrides { /** Default value: `15` */ "down fractals.display": number; /** Default value: `shape_triangle_down` */ "down fractals.plottype": string; /** Default value: `BelowBar` */ "down fractals.location": string; /** Default value: `0` */ "down fractals.transparency": number; /** Default value: `#F23645` */ "down fractals.color": string; /** Default value: `15` */ "up fractals.display": number; /** Default value: `shape_triangle_up` */ "up fractals.plottype": string; /** Default value: `AboveBar` */ "up fractals.location": string; /** Default value: `0` */ "up fractals.transparency": number; /** Default value: `#089981` */ "up fractals.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Williams %R' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface WilliamsRIndicatorOverrides { /** Default value: `#7E57C2` */ "hlines background.color": string; /** Default value: `90` */ "hlines background.transparency": number; /** Default value: `true` */ "hlines background.visible": boolean; /** Default value: `#787B86` */ "upperlimit.color": string; /** Default value: `2` */ "upperlimit.linestyle": number; /** Default value: `1` */ "upperlimit.linewidth": number; /** Default value: `true` */ "upperlimit.visible": boolean; /** Default value: `-20` */ "upperlimit.value": number; /** Default value: `#787B86` */ "lowerlimit.color": string; /** Default value: `2` */ "lowerlimit.linestyle": number; /** Default value: `1` */ "lowerlimit.linewidth": number; /** Default value: `true` */ "lowerlimit.visible": boolean; /** Default value: `-80` */ "lowerlimit.value": number; /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `1` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#7E57C2` */ "plot.color": string; [key: string]: StudyOverrideValueType; } /** * Overrides for the 'Zig Zag' indicator. * * Use these properties to customize indicator via {@link IChartWidgetApi.createStudy} and {@link IStudyApi.applyOverrides}. */ export interface ZigZagIndicatorOverrides { /** Default value: `15` */ "plot.display": number; /** Default value: `0` */ "plot.linestyle": number; /** Default value: `2` */ "plot.linewidth": number; /** Default value: `line` */ "plot.plottype": LineStudyPlotStyleName; /** Default value: `false` */ "plot.trackprice": boolean; /** Default value: `0` */ "plot.transparency": number; /** Default value: `#2196F3` */ "plot.color": string; [key: string]: StudyOverrideValueType; } 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"; /** * Sets the debug level for {@link TradingTerminalWidgetOptions.debug_broker }. * * - `host-only`: logs only messages related to the {@link IBrokerConnectionAdapterHost} interface. * - `broker-only`: logs only messages related to the {@link IBrokerTerminal} interface. * - `normal`: logs messages for the broker and host but excludes frequently called methods, such as `connectionStatus`. * - `all`: logs all possible debug messages. */ export type BrokerDebugMode = "all" | "normal" | "host-only" | "broker-only"; 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"; /** * Function to provide a description of the chart described by the context data */ export type ChartDescriptorFunction = (context: ChartDescriptionContext) => Promise; /** * Chart type names for use within the `favorites` Widget Constructor option. This type is for Advanced Charts, if you are looking for the Trading Platform type then please see {@link TradingTerminalChartTypeFavorites}. * * See {@link Favorites} for the Widget Constructor option where you can define these favorites, and {@link ChartingLibraryWidgetOptions.favorites} for the Widget Constructor option. */ export type ChartTypeFavorites = "Area" | "Bars" | "Candles" | "Heiken Ashi" | "Hollow Candles" | "Line" | "Line Break" | "Baseline" | "LineWithMarkers" | "Stepline" | "Columns" | "High-low"; /** This is the list of all [featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) that work in Advanced Charts */ 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 Advanced Charts and Watchlist symbols and some panels states in the Trading Platform @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" | /** * Enables or disables the ability for users to enter arbitrary input in the [_Symbol Search_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search) dialog. * * When this feature is disabled (default behavior), pressing the _Enter_ key without selecting a search result * will automatically select the top search result as the input value. If no results are available, pressing * _Enter_ will have no effect. * * When this feature is enabled, the user's direct input will be used as the selected value, regardless of * whether it matches any search results. This input will then be passed to the data feed for resolution and * loading. * * @default false */ "allow_arbitrary_symbol_search_input" | /** 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 quick search button from the header @default true */ "header_quick_search" | /** 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 Platform 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" | /** * Lock the visible range when adjusting the percentage right margin via the settings dialog. * This applies when the chart is already at the current default margin position. * @default false */ "lock_visible_time_range_when_adjusting_percentage_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" | /** Enable saving/loading of chart templates. */ "chart_template_storage" | /** * When chart data is reset, then re-request data for just the visible range (instead of the entire range of the existing data loaded). * @default false */ "request_only_visible_range_on_reset" | /** Clear pane price scales when the main series has an error or has no bars. @default true */ "clear_price_scale_on_error_or_empty_bars" | /** Enables the ability to in-place edit of studies or series in legend. @default true */ "legend_inplace_edit" | /** * Display logos for the symbols within the symbol search dialog, and the watchlist widget. The datafeed should provide the image url within the search result item, and the SymbolInfo. {@link LibrarySymbolInfo.logo_urls}, {@link SearchSymbolResultItem.logo_urls} * @default false */ "show_symbol_logos" | /** * Display logos for the exchanges within the symbol search dialog. The datafeed should provide the image url within the search result item. {@link SearchSymbolResultItem.exchange_logo} * @default false */ "show_exchange_logos" | /** * Display the main symbol's logo within the legend. This requires that `show_symbol_logos` is enabled. * @default true */ "show_symbol_logo_in_legend" | /** * Display the symbol's logo within the legend for compare studies. This requires that `show_symbol_logos` and `show_symbol_logo_in_legend` are enabled. * @default true */ "show_symbol_logo_for_compare_studies" | /** * Display legend values when on mobile. * @default false */ "always_show_legend_values_on_mobile" | /** Enable studies to extend the time scale, if enabled in the study metainfo */ "studies_extend_time_scale" | /** Replace Alt + Z with Tab, Tab with Shift + Arrow right, Shift + Tab with Shift + Arrow left @default false */ "accessible_keyboard_shortcuts" | /** * Generates a more detailed ARIA description of the chart for screen readers when the active chart is changed * by the user. The more detailed description includes a brief description of the price values for the main series. * ARIA descriptions are currently only provided for the English language, however you can use the * {@link ChartingLibraryWidgetOptions.custom_chart_description_function} constructor option if you wish to add * support for additional languages. * @default false */ "aria_detailed_chart_descriptions" | /** * Announces, via the screen reader, the price when the crosshair is moved on the chart. * Currently only supported for the English language. * @default false */ "aria_crosshair_price_description" | /** * Enables an [alternative saving and loading mode](https://www.tradingview.com/charting-library-docs/latest/saving_loading/saving_loading#saving-drawings-separately) for the library. This mode saves the state of the drawings separately from the chart layout. * @default false */ "saveload_separate_drawings_storage" | /** * Disables the pulse animation when chart type is set to Line. * @default false */ "disable_pulse_animation" | /** * Enables an alternative loading mode for the library, which can be used when the iframe content must be served from the same origin. * * Loads the initial library iframe content from `library_path + 'sameorigin.html`. * @default false */ "iframe_loading_same_origin" | /** * Enables custom color themes features. * @default true */ "library_custom_color_themes" | /** * Uses the name of a symbol rather than its ticker name in the Symbol Search dialog and header button. * @default false */ "use_symbol_name_for_header_toolbar" | /** * Enables the ability to display inactivity gaps on charts. These gaps represent periods when there has been no trading activity, resulting in missing bars on the chart. * * With this feature enabled, users can visually identify periods of market inactivity within intraday sessions on the chart. * * **Behaviour** * - **Chart Settings Dialog:** When this featureset is enabled (`true`), a checkbox appears in the chart settings dialog, allowing users to toggle the visibility of inactivity gaps on or off. * - **Widget API Integration:** The featureset also exposes the `inactivityGaps` watched value through the Widget API. This allows programmatic control over inactivity gap behavior, enabling or disabling it via API calls. * @default false */ "inactivity_gaps"; /** * A color gradient from lightest to darkest to override one of the default color theme colors. */ export type ColorGradient = [ lightness50: string, lightness100: string, lightness150: string, lightness200: string, lightness250: string, lightness300: string, lightness350: string, lightness400: string, lightness450: string, lightness500: string, lightness550: string, lightness600: string, lightness650: string, lightness700: string, lightness750: string, lightness800: string, lightness850: string, lightness900: string, lightness950: string ]; /** These are defining the types for a background */ export type ColorTypes = "solid" | "gradient"; /** * Determines the baseline position for column series, either at the bottom of the pane or aligned with the price scale's zero value. */ export type ColumnStyleBaselinePosition = "bottom" | "zero"; /** * 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. * @param {CreateContextMenuParams} params - an object representing additional information about the context menu, such as the menu name. */ export type ContextMenuItemsProcessor = (items: readonly IActionVariant[], actionsFactory: ActionsFactory, params: CreateContextMenuParams) => 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 * @returns {Promise} - promise for a renderer or null. If the promise resolves with null, default chart menu is used */ 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, precision: string | undefined) => 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/Casablanca" | "Africa/Johannesburg" | "Africa/Lagos" | "Africa/Nairobi" | "Africa/Tunis" | "America/Anchorage" | "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/Dhaka" | "Asia/Dubai" | "Asia/Ho_Chi_Minh" | "Asia/Hong_Kong" | "Asia/Jakarta" | "Asia/Jerusalem" | "Asia/Kabul" | "Asia/Karachi" | "Asia/Kathmandu" | "Asia/Kolkata" | "Asia/Kuala_Lumpur" | "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/Azores" | "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/Prague" | "Europe/Riga" | "Europe/Rome" | "Europe/Stockholm" | "Europe/Tallinn" | "Europe/Vienna" | "Europe/Vilnius" | "Europe/Warsaw" | "Europe/Zurich" | "Pacific/Auckland" | "Pacific/Chatham" | "Pacific/Fakaofo" | "Pacific/Honolulu" | "Pacific/Norfolk" | "US/Mountain"; /** * Custom translation function * @param {string} originalText - original raw text taking into account pluralization rules * @param {string} singularOriginalText - originalText in singular * @param {string} [translatedText] - translated originalText */ export type CustomTranslateFunction = (originalText: string, singularOriginalText: string, translatedText?: string) => string | null; export type DOMCallback = (data: DOMData) => void; export type DatafeedErrorCallback = (reason: string) => void; 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 DisplayOption = "all" | "data_window" | "none"; /** * 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"; /** * Override properties for drawings. * Refer to the [Drawing Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Drawings-Overrides) article for information on how to customize drawings. * * The following constants are used within the default properties. You cannot use these names directly. * * - LINESTYLE * - SOLID = 0 * - DOTTED = 1 * - DASHED = 2 * - LARGE_DASHED = 3 * - LINEEND * - NORMAL = 0 * - ARROW = 1 * - CIRCLE = 2 * - MODE * - BARS = 0 * - LINE = 1 * - OPENCLOSE = 2; * - LINEOPEN = 3; * - LINEHIGH = 4; * - LINELOW = 5; * - LINEHL2 = 6; * - PITCHFORK_STYLE * - ORIGINAL = 0 * - SCHIFF = 1 * - SCHIFF2 = 2 * - INSIDE = 3 * - STATS_POSITION * - LEFT = 0 * - CENTER = 1 * - RIGHT = 2 * - RISK_DISPLAY_MODE * - PERCENTAGE = 'percents' * - MONEY = 'money' */ export type DrawingOverrides = FivepointspatternLineToolOverrides | AbcdLineToolOverrides | AnchoredvpLineToolOverrides | AnchoredvwapLineToolOverrides | ArcLineToolOverrides | ArrowLineToolOverrides | ArrowmarkdownLineToolOverrides | ArrowmarkerLineToolOverrides | ArrowmarkleftLineToolOverrides | ArrowmarkrightLineToolOverrides | ArrowmarkupLineToolOverrides | BalloonLineToolOverrides | BarspatternLineToolOverrides | BeziercubicLineToolOverrides | BezierquadroLineToolOverrides | BrushLineToolOverrides | CalloutLineToolOverrides | CircleLineToolOverrides | CommentLineToolOverrides | CrosslineLineToolOverrides | CypherpatternLineToolOverrides | DisjointangleLineToolOverrides | ElliottcorrectionLineToolOverrides | ElliottdoublecomboLineToolOverrides | ElliottimpulseLineToolOverrides | ElliotttriangleLineToolOverrides | ElliotttriplecomboLineToolOverrides | EllipseLineToolOverrides | EmojiLineToolOverrides | ExecutionLineToolOverrides | ExtendedLineToolOverrides | FibchannelLineToolOverrides | FibcirclesLineToolOverrides | FibretracementLineToolOverrides | FibspeedresistancearcsLineToolOverrides | FibspeedresistancefanLineToolOverrides | FibtimezoneLineToolOverrides | FibwedgeLineToolOverrides | FlagmarkLineToolOverrides | FlatbottomLineToolOverrides | GanncomplexLineToolOverrides | GannfanLineToolOverrides | GannfixedLineToolOverrides | GannsquareLineToolOverrides | GhostfeedLineToolOverrides | HeadandshouldersLineToolOverrides | HighlighterLineToolOverrides | HorzlineLineToolOverrides | HorzrayLineToolOverrides | IconLineToolOverrides | ImageLineToolOverrides | InfolineLineToolOverrides | InsidepitchforkLineToolOverrides | OrderLineToolOverrides | ParallelchannelLineToolOverrides | PathLineToolOverrides | PitchfanLineToolOverrides | PitchforkLineToolOverrides | PolylineLineToolOverrides | PositionLineToolOverrides | PredictionLineToolOverrides | PricelabelLineToolOverrides | ProjectionLineToolOverrides | RayLineToolOverrides | RegressiontrendLineToolOverrides | RiskrewardlongLineToolOverrides | RiskrewardshortLineToolOverrides | RotatedrectangleLineToolOverrides | SchiffpitchforkLineToolOverrides | Schiffpitchfork2LineToolOverrides | SignpostLineToolOverrides | SinelineLineToolOverrides | StickerLineToolOverrides | TextLineToolOverrides | TextabsoluteLineToolOverrides | ThreedriversLineToolOverrides | TimecyclesLineToolOverrides | TrendangleLineToolOverrides | TrendbasedfibextensionLineToolOverrides | TrendbasedfibtimeLineToolOverrides | TrendlineLineToolOverrides | TriangleLineToolOverrides | TrianglepatternLineToolOverrides | VertlineLineToolOverrides; 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" | "LineToolTextNote" | "LineToolPriceRange" | "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; /** * Description of each field of exported data from the chart */ export type FieldDescriptor = TimeFieldDescriptor | UserTimeFieldDescriptor | SeriesFieldDescriptor | StudyFieldDescriptor; export type FillOptions = SolidFillOptions | GradientFillOptions; 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 GridLinesMode = "both" | "vert" | "horz" | "none"; 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; 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 ]; /** * An array of bar values. * * [time, open, high, low, close, volume, updatetime, isBarClosed, emptyBars, emptyBarsPrice] */ export type ISeriesStudyResult = [ time: number, open: number, high: number, low: number, close: number, volume: number, updatetime: number | undefined, isBarClosed: boolean | undefined, emptyBars: number[] | undefined, emptyBarsPrice: number | 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" | "ca_ES" | "en" | "fr" | "de" | "he_IL" | "id_ID" | "it" | "ja" | "ko" | "pl" | "pt" | "ru" | "es" | "sv" | "th" | "tr" | "vi" | "ms_MY" | "zh_TW"; export type LayoutSizes = Record; export type LayoutSizesState = SubLayoutSizesState[]; export type LayoutType = SingleChartLayoutType | MultipleChartsLayoutType; export type LegendMode = "horizontal" | "vertical"; export type LibrarySessionId = "regular" | "extended" | "premarket" | "postmarket"; /** * Plot Style. Used for `plottype` properties within [Indicator overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides). */ export type LineStudyPlotStyleName = "line" | "histogram" | "cross" | "area" | "columns" | "circles" | "line_with_breaks" | "area_with_breaks" | "step_line" | "step_line_with_breaks" | "step_line_with_diamonds"; /** * The type of data being requested from the {@link IExternalSaveLoadAdapter.loadLineToolsAndGroups} method. * * Usually, the 'mainSeriesLineTools' is the requested type that is important for implementing the restoration of drawings associated with a chart. */ export type LineToolsAndGroupsLoadRequestType = "allLineTools" | "lineToolsWithoutSymbol" | "studiesLineTools" | "mainSeriesLineTools"; export type MarkConstColors = "red" | "green" | "blue" | "yellow"; export type MarkupText = (string | HyperlinkInfo)[]; export type MultipleChartsLayoutType = "2h" | "2v" | "3h" | "3v" | "3s" | "3r" | "2-1" | "1-2" | "4" | "4v" | "4h" | "4s" | "4s-l" | "1-3" | "3-1" | "2-2-l" | "2-2-r" | "2-2" | "1-4" | "5h" | "5v" | "5s" | "5s-l" | "2-3" | "3-2" | "4-1" | "2-3-l" | "2-3-r" | "6" | "6h" | "6v" | "6c" | "2-4" | "4-2" | "4-3" | "7h" | "7s" | "8" | "8c" | "8h" | "8v"; export type ObservableCallback = (value: T) => void; export type OmitActionId = Omit; 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 OrderLineLengthUnit = "pixel" | "percentage"; export type OrderPreviewMessage = string | MarkupText; 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 OverlayIndicatorOverridesAll = OverlayIndicatorOverridesBar | OverlayIndicatorOverridesCandle | OverlayIndicatorOverridesLine | OverlayIndicatorOverridesArea | OverlayIndicatorOverridesHollowCandle | OverlayIndicatorOverridesBaseline | OverlayIndicatorOverridesHiLo | OverlayIndicatorOverridesColumn | OverlayIndicatorOverridesHLCArea | OverlayIndicatorOverridesLineWithMarkers | OverlayIndicatorOverridesStepline; export type OverlayIndicatorStyleExclusions = ChartStyle.Renko | ChartStyle.Kagi | ChartStyle.PnF | ChartStyle.LineBreak | ChartStyle.HeikinAshi | ChartStyle.VolCandle; 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 PositionLineLengthUnit = "pixel" | "percentage"; 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 & { /** array with study plots info. See dedicated article: [Custom Studies Plots](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Plots) */ readonly plots?: readonly Readonly[]; /** an object containing settings that are applied when user clicks 'Apply Defaults'. See dedicated article: [Custom Studies Defaults](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/Custom-Studies-Defaults) */ readonly defaults?: Readonly>; }; /** * Resolution or time interval is a time period of one bar. Advanced Charts 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, `5T` — five ticks, `100T` — one hundred ticks * 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; export type SessionId = Nominal; /** * 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 SingleIndicatorOverrides = FiftyTwoWeekHighLowIndicatorOverrides | AcceleratorOscillatorIndicatorOverrides | AccumulationDistributionIndicatorOverrides | AccumulativeSwingIndexIndicatorOverrides | AdvanceDeclineIndicatorOverrides | AnchoredVWAPIndicatorOverrides | ArnaudLegouxMovingAverageIndicatorOverrides | AroonIndicatorOverrides | AverageDirectionalIndexIndicatorOverrides | AveragePriceIndicatorOverrides | AverageTrueRangeIndicatorOverrides | AwesomeOscillatorIndicatorOverrides | BalanceofPowerIndicatorOverrides | BollingerBandsIndicatorOverrides | BollingerBandsBIndicatorOverrides | BollingerBandsWidthIndicatorOverrides | ChaikinMoneyFlowIndicatorOverrides | ChaikinOscillatorIndicatorOverrides | ChaikinVolatilityIndicatorOverrides | ChandeKrollStopIndicatorOverrides | ChandeMomentumOscillatorIndicatorOverrides | ChopZoneIndicatorOverrides | ChoppinessIndexIndicatorOverrides | CommodityChannelIndexIndicatorOverrides | CompareIndicatorOverrides | ConnorsRSIIndicatorOverrides | CoppockCurveIndicatorOverrides | CorrelationLogIndicatorOverrides | CorrelationCoefficientIndicatorOverrides | DetrendedPriceOscillatorIndicatorOverrides | DirectionalMovementIndicatorOverrides | DonchianChannelsIndicatorOverrides | DoubleEMAIndicatorOverrides | EMACrossIndicatorOverrides | EaseOfMovementIndicatorOverrides | EldersForceIndexIndicatorOverrides | EnvelopesIndicatorOverrides | FisherTransformIndicatorOverrides | FixedRangeIndicatorOverrides | GuppyMultipleMovingAverageIndicatorOverrides | HistoricalVolatilityIndicatorOverrides | HullMovingAverageIndicatorOverrides | IchimokuCloudIndicatorOverrides | KeltnerChannelsIndicatorOverrides | KlingerOscillatorIndicatorOverrides | KnowSureThingIndicatorOverrides | LeastSquaresMovingAverageIndicatorOverrides | LinearRegressionCurveIndicatorOverrides | LinearRegressionSlopeIndicatorOverrides | MACrossIndicatorOverrides | MAwithEMACrossIndicatorOverrides | MACDIndicatorOverrides | MajorityRuleIndicatorOverrides | MassIndexIndicatorOverrides | McGinleyDynamicIndicatorOverrides | MedianPriceIndicatorOverrides | MomentumIndicatorOverrides | MoneyFlowIndexIndicatorOverrides | MovingAverageIndicatorOverrides | MovingAverageAdaptiveIndicatorOverrides | MovingAverageChannelIndicatorOverrides | MovingAverageDoubleIndicatorOverrides | MovingAverageExponentialIndicatorOverrides | MovingAverageHammingIndicatorOverrides | MovingAverageMultipleIndicatorOverrides | MovingAverageTripleIndicatorOverrides | MovingAverageWeightedIndicatorOverrides | NetVolumeIndicatorOverrides | OnBalanceVolumeIndicatorOverrides | OverlayIndicatorOverrides | ParabolicSARIndicatorOverrides | PivotPointsStandardIndicatorOverrides | PriceChannelIndicatorOverrides | PriceOscillatorIndicatorOverrides | PriceVolumeTrendIndicatorOverrides | RankCorrelationIndexIndicatorOverrides | RateOfChangeIndicatorOverrides | RatioIndicatorOverrides | RegressionTrendIndicatorOverrides | RelativeStrengthIndexIndicatorOverrides | RelativeVigorIndexIndicatorOverrides | RelativeVolatilityIndexIndicatorOverrides | SMIErgodicIndicatorOscillatorIndicatorOverrides | SessionsIndicatorOverrides | SmoothedMovingAverageIndicatorOverrides | SpreadIndicatorOverrides | StandardDeviationIndicatorOverrides | StandardErrorIndicatorOverrides | StandardErrorBandsIndicatorOverrides | StochasticIndicatorOverrides | StochasticRSIIndicatorOverrides | SuperTrendIndicatorOverrides | TRIXIndicatorOverrides | TrendStrengthIndexIndicatorOverrides | TripleEMAIndicatorOverrides | TrueStrengthIndexIndicatorOverrides | TypicalPriceIndicatorOverrides | UltimateOscillatorIndicatorOverrides | VWAPIndicatorOverrides | VWMAIndicatorOverrides | VolatilityClosetoCloseIndicatorOverrides | VolatilityIndexIndicatorOverrides | VolatilityOHLCIndicatorOverrides | VolatilityZeroTrendClosetoCloseIndicatorOverrides | VolumeIndicatorOverrides | VolumeOscillatorIndicatorOverrides | VolumeProfileFixedRangeIndicatorOverrides | VolumeProfileVisibleRangeIndicatorOverrides | VortexIndicatorIndicatorOverrides | WilliamsRIndicatorOverrides | WilliamsAlligatorIndicatorOverrides | WilliamsFractalIndicatorOverrides | ZigZagIndicatorOverrides | OverlayIndicatorOverridesAll; /** An event related to a study. */ export type StudyEventType = "create" | "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 & { /** Identifier for the Study */ 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 StudyPriceSource = "open" | "high" | "low" | "close" | "hl2" | "hlc3" | "ohlc4" | "hlcc4"; export type StudyPrimitiveResult = (number | StudyResultValueWithOffset)[]; export type StudyScript = (ctx: ScriptContext) => void; export type SubscribeBarsCallback = (bar: Bar) => void; export type SuggestedQtyChangedListener = (newQty: number) => void; export type SupportedLineTools = "text" | "anchored_text" | "note" | "anchored_note" | "signpost" | "double_curve" | "arc" | "icon" | "emoji" | "sticker" | "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" | "anchored_vwap" | "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" | "text_note" | "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" | "table"; /** * 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" | "commodity" | "fundamental" | "spot" | "swap" | "option" | "ndf"; /** * 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" /** * A time with milliseconds. */ | "TimeWithMilliseconds"; export type TickerId = Nominal; /** * 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 * - `openUrl` - the object with URL to be opened and text for solution button */ export type TradableSolutions = TradableSolutionsTypes[keyof TradableSolutionsTypes]; export type TradingDialogCustomField = CheckboxFieldMetaInfo | TextWithCheckboxFieldMetaInfo | CustomComboBoxMetaInfo | TextFieldMetaInfo; /** * Chart type names for use within the `favorites` Widget Constructor option. This type is for Trading Platform, if you are looking for the Advanced Charts type then please see {@link ChartTypeFavorites}. * * See {@link Favorites} for the Widget Constructor option where you can define these favorites, and {@link TradingTerminalWidgetOptions.favorites} for the Widget Constructor option. */ export type TradingTerminalChartTypeFavorites = ChartTypeFavorites | "Renko" | "Kagi" | "Point & figure" | "Line Break"; /** This is the list of all featuresets that work on Trading Platform (which is an extension of Advanced Charts) */ 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. If disabled users will still be able to apply the default settings for their selection. @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 Ticket @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. If the right toolbar is not enabled this feature will have no effect. @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" | /** Adds the _Last day change values_ option to the _Chart Settings_ dialog in the UI. This option allows users to show/hide the last day change values in the main series legend. @default false */ "legend_last_day_change" | /** Enable context menu support in the watchlist. */ "watchlist_context_menu " | /** Hide the right_toolbar when initialising the chart. Can be expanded using the widgetBar API {@link IWidgetbarApi} @default false */ "hide_right_toolbar" | /** Hide the tabs within the right toolbar @default false */ "hide_right_toolbar_tabs" | /** Hide price scales when all sources attached to the price scale are hidden. */ "hide_price_scale_if_all_sources_hidden" | /** * Display the symbol's logo within the account manager panel. This requires that `show_symbol_logos` is enabled. * @default true */ "show_symbol_logo_in_account_manager" | /** * Display UI (buttons and context menu options) for creating sections within the watchlist. * @default true */ "watchlist_sections" | /** * Uses the symbol name instead of the `exchange:name` combination throughout the UI. * @default true */ "prefer_symbol_name_over_fullname" | /** * Displays the {@link DatafeedQuoteValues.short_name} value as a symbol name in the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) and [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details). If disabled, the [`ticker`]() value will be used instead. * @default true */ "prefer_quote_short_name" | /** * EXPERIMENTAL. Enables the Image drawing. * * By default images have no size limit and are saved in the chart layout which may not be suitable, depending on your chart storage implementation. * * @default false */ "image_drawingtool" | /** * Enables the pre-/post-market price line. * * To enable the pre-/post-market lines, you need to provide {@link DatafeedQuoteValues.rtc} to the quote object. * * @default false */ "pre_post_market_price_line" | /** * Enables cross-tab synchronization for [watchlists](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List). * @default true */ "watchlist_cross_tab_sync"; export type VisiblePlotsSet = "ohlcv" | "ohlc" | "c" | "hlc"; 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; /** * Custom watermark content provider which should return an array of watermark lines to be displayed. * Return `null` if you would like to use the default content. */ export type WatermarkContentProvider = (data: WatermarkContentData) => WatermarkLine[] | null; export type WidgetOverrides = DrawingOverrides & { [key: string]: string | number | boolean; }; export as namespace TradingView; export {}; declare type DeepPartial = { [P in keyof T]?: T[P] extends (infer U)[] ? DeepPartial[] : T[P] extends readonly (infer X)[] ? readonly DeepPartial[] : DeepPartial; }; File: datafeed-api.d.ts ======================== /** * Datafeed JS API for TradingView Advanced Charts * @packageDocumentation * @module Datafeed */ // Generated by dts-bundle-generator v9.5.1 export declare const enum SearchInitiationPoint { SymbolSearch = "symbolSearch", Watchlist = "watchlist", Compare = "compare", IndicatorInputs = "indicatorInputs" } /** * 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; }; /** * Bar data point */ export interface Bar { /** Bar time. * Amount of **milliseconds** since Unix epoch start in **UTC** timezone. * `time` for daily, weekly, and monthly bars is expected to be a trading day (not session start day) at 00:00 UTC. * The 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 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; } /** * 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; } /** * Datafeed configuration data. * Pass the resulting array of properties as a parameter to {@link OnReadyCallback} of the [`onReady`](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#onready) method. */ 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 [resolutions](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution) that the chart should support. * Each item of the array is expected to be a string that has a specific [format](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-format). * If you set this property to `undefined` or an empty array, the _Resolution_ drop-down menu displays the list of resolutions available for * the current symbol ({@link LibrarySymbolInfo.supported_resolutions}). * * @example * `["1", "15", "240", "D", "6M"]` will give you "1 minute, 15 minutes, 4 hours, 1 day, 6 months" in the _Resolution_ drop-down menu. */ 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](https://www.tradingview.com/charting-library-docs/latest/ui_elements/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. * Refer to [Symbol grouping](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search#symbol-grouping) for more information. */ symbols_grouping?: Record; } /** * This object contains symbol quote values, where a [quote](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/quotes) represents a set of data describing the current price. * The library uses quote data for various trading functionalities, including the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket), [Legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend), * and widgets, such as [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List), [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details), * [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news), and [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#depth-of-market). * * While all properties in this object are marked as optional, populating most of them is required for supporting trading functionalities. * Providing values that do not match the expected data types can cause issues such as UI [loading delays](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues#delays-in-trading-platform-ui-elements) or [missing data](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues#quotes-are-not-displayed-or-refreshed). * See property descriptions for more information. */ export interface DatafeedQuoteValues { /** * Price change. It is usually calculated as a difference between the current price and close price of the previous day (regular session). * In the UI, `ch` and {@link chp} are represented as the last day change parameter in *Data Window*. * You can also display these values in the [legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#last-day-change-values). * If `ch` and `chp` are not provided, `0.00 (0.00%)` is displayed instead. * * Note that `ch` and `chp` are **required** for mobile apps. Otherwise, [`NaN` values](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#nan-values-in-legend) will appear in the legend. */ ch?: number; /** * Price change percentage. In the UI, `chp` and {@link ch} are represented as the last day change parameter in *Data Window*. * You can also display these values in the [Legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#last-day-change-values). * If `ch` and `chp` are not provided, `0.00 (0.00%)` is displayed instead. * * Note that `ch` and `chp` are **required** for mobile apps. Otherwise, [`NaN` values](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#nan-values-in-legend) will appear in the Legend. */ chp?: number; /** Short name for a symbol. Short name is used in the title for the [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news), [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) and [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widgets. You can disable the [`prefer_quote_short_name`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#prefer_quote_short_name) to use the {@link LibrarySymbolInfo.ticker} value instead. */ short_name?: string; /** The name of the exchange. The exchange name is displayed in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ exchange?: string; /** A short description of the symbol. This description is displayed in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget and the tooltip of the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) widget. */ description?: string; /** * The price at which the most recent trade of a security occurred, regardless of whether it was a buy or sell. * Required for the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket), [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#depth-of-market), [Buy/Sell buttons](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#buysell-buttons-and-lines), and [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) and [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) widgets. */ lp?: number; /** Ask price – the lowest price a seller is willing to accept for a security. The value is displayed in the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) and [Buy/Sell buttons](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#buysell-buttons-and-lines). */ ask?: number; /** Bid price – the highest price a buyer is willing to pay for a security. The value is displayed in the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) and [Buy/Sell buttons](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#buysell-buttons-and-lines). */ bid?: number; /** Spread – the difference between the ask and bid prices. The value is displayed between [Buy/Sell buttons](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#buysell-buttons-and-lines). */ spread?: number; /** Today's opening price */ open_price?: number; /** Today's high price. The value is displayed in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ high_price?: number; /** Today's low price. The value is displayed in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ low_price?: number; /** * Closing price of the symbol from the previous regular market session. * * Required for mobile apps. Otherwise, `NaN` values will appear in the [Legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend). */ prev_close_price?: number; /** Today's trading volume. This value is displayed in the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) widget. */ volume?: number; /** Original name */ original_name?: string; /** Pre-/post-market price. This value is required to display the [pre-/post-market price line](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions#enable-the-price-line) on the chart and information on the extended session in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ rtc?: number; /** Pre-/post-market price update time. This value is required to display information on the [extended session](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions) in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ rtc_time?: number; /** Pre-/post-market price change. This value is required to display information on the [extended session](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions) in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ rch?: number; /** Pre-/post-market price change percentage. This value is required to display information on the [extended session](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions) the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading_terminal#details) widget. */ rchp?: number; [valueName: string]: string | number | 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; } /** 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; } /** * 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; /** * The time of the next available bar in history. The time value should be represented with a Unix timestamp in milliseconds. * * You can pass the `nextTime` value to the library if there is no data in the time range that the library requests. * Therefore, you notify the library about available data before the requested range and ensure that the next data request is for the right range. * For more information, refer to the [How nextTime works](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF#how-nexttime-works) section. */ nextTime?: number | null; } 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 the `supports_time` configuration flag is `true` when the chart needs to know the server time. * The library expects a callback to be called once. * The time is provided without milliseconds. Example: `1445324591`. * * `getServerTime` is used to display countdown on the price scale. * Note that the countdown can be displayed only for [intraday](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-minutes-intraday) resolutions. */ 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 * @param searchSource The source of the search ({@link SearchInitiationPoint}). */ searchSymbols(userInput: string, exchange: string, symbolType: string, onResult: SearchSymbolsCallback, searchSource?: SearchInitiationPoint): 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: DatafeedErrorCallback, 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. If using special characters, please consider `encodeURIComponent`. */ getBars(symbolInfo: LibrarySymbolInfo, resolution: ResolutionString, periodParams: PeriodParams, onResult: HistoryCallback, onError: DatafeedErrorCallback): void; /** * The 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; /** * The library calls this function when it wants to receive real-time symbol data in the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) (DOM) widget. * Note that you should set the {@link BrokerConfigFlags.supportLevel2Data} configuration flag to `true`. * * @param symbol A SymbolInfo object * @param callback A function returning an object to update DOM data * @returns A unique identifier that will be used to unsubscribe from the data */ subscribeDepth?(symbol: string, callback: DOMCallback): string; /** * The library calls this function to stop receiving real-time updates for the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) listener. * Note that you should set the {@link BrokerConfigFlags.supportLevel2Data} configuration flag to `true`. * * @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 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 Platform 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 Platform 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 IExternalDatafeed { /** * This call is intended to provide the object filled with the configuration data. * The lib 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 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; /** * Session to display. See {@link LibrarySymbolInfo.session_display}. */ "session-display"?: string; } export interface LibrarySymbolInfo { /** * It is a symbol name within an exchange, such as `AAPL` or `9988` (Hong Kong). * Note that it should not contain the exchange name. * This symbol name is visible to users and can be repeated. * * By default, `name` is used to resolve symbols in the [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api). * If you use {@link LibrarySymbolInfo.ticker}, the library will use the ticker for Datafeed API requests. */ name: string; /** * Array of base symbols * Example: for `AAPL*MSFT` it is `['NASDAQ:AAPL', 'NASDAQ:MSFT']` */ base_name?: string[]; /** * It is an unique identifier for a particular symbol in your [symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology). * If you specify this property, 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. * * You should avoid using colons (":") in ticker values unless you are following the TradingView format: "NYSE:IBM". Using colons may cause unexpected behaviour and display bugs. */ 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 the symbol. The time should be in the **exchange** time zone specified in the {@link LibrarySymbolInfo.timezone} property. Refer to the [Trading sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessions) article for more information. * @example "1700-0200" */ session: string; /** * The session value to display in the UI. If not specified, then `session` is used. */ session_display?: string; /** * A string that contains a list of non-trading holidays for the symbol. * Holiday dates should be in the `YYYYMMDD` format. * These dates are not displayed on the chart. * * You can specify a correction for a holiday using {@link LibrarySymbolInfo.corrections}. * @example "20181105,20181107,20181112" */ session_holidays?: string; /** * List of corrections for a symbol. The corrections are days when the trading session differs from the default one set in {@link LibrarySymbolInfo.session}. * The `corrections` value is a string in the following format: `SESSION:YYYYMMDD`. * For more information, refer to [corrections](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#corrections). * * The string below specifies corrections for two trading days: * * - November 13, 2018. This trading day is split into two sessions. The first session starts at 19:00 four days before (November 9, 2018) and ends at 23:50 four days before. The second session starts at 10:00 and ends at 18:45. * - November 14, 2018. The session starts at 10:00 and ends at 14:00. * * @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; /** * The time zone of the **exchange** where the symbol is listed. The time zone value should be in the OlsonDB format. * Refer to [Time zones](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezones) for a full list of supported time zones. */ 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 format](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; /** * A number of decimal places or fractions that the price has. * * The `pricescale` value depends on the [price format](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#price-format). * If you want to display the price in the decimal format, `pricescale` should be `10^n`, where `n` is the number of decimal places. * **Examples:** `1`, `10`, `10000000`. * * If you want to display the price in the fractional format, `pricescale` should be `2^n`. * This value represents the number of fractions. * **Examples:** `8`, `16`, `256`. */ pricescale: number; /** * The number of units that make up one tick. * For example, U.S. equities are quotes in decimals, and tick in decimals, and can go up +/- `.01`. * Therefore, the tick increment is 1 and `minmov = 1`. But the e-mini S&P futures contract, though quoted in decimals, goes up in `.25` increments, so the tick increment is 25 and `minmov = 25`. * Refer to [Price format](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#price-format) for more information. */ 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; /** * This property is used to display prices in the [fraction of a fraction](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#fraction-of-a-fraction-format) format. * For example, the ZBM2023 tick size is 1/4 of a 32nd. To display this security, set `minmov = 1`, `pricescale = 128`, `minmove2 = 4`. * * For common prices, `minmove2` can be skipped or set to `0`. */ minmove2?: number; /** * 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 the tick size is 0.01 for a price less than 10, the tick size is 0.02 for a price less than 25, the tick size is 0.05 for a price greater than or equal to 25. */ variable_tick_size?: string; /** * A flag indicating whether your datafeed contains intraday (minutes) data for this symbol. * If `true`, the library requests this data when an intraday resolution is selected. If `false`, _No data here_ is displayed on the chart. * * This property is required to enable intraday resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-minutes-intraday) article for more information. * @default false */ has_intraday?: boolean; /** * An array of [resolutions](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution) which should be enabled in the _Resolution_ drop-down menu for this symbol. * Each item of the array is expected to be a string that has a specific [format](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-format). * * If one changes the symbol and the new symbol does not support the selected resolution, an error message will be shown on the chart. * * **Resolution availability logic (pseudocode):** * ``` * resolutionAvailable = * resolution.isIntraday * ? symbol.has_intraday && symbol.supported_resolutions(resolution) * : symbol.supported_resolutions(resolution); * ``` * * If `supported_resolutions` is `[]` (empty array), all resolutions are disabled in the _Resolution_ drop-down menu. * * If `supported_resolutions` is `undefined`, all resolutions that the chart support ({@link DatafeedConfiguration.supported_resolutions}) and custom resolutions are enabled. * * Note that the list of available time frames depends on supported resolutions. * Time frames that require resolutions that are unavailable for a particular symbol will be hidden. * Refer to [Time frame toolbar](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale#time-frame-toolbar) for more information. */ supported_resolutions?: ResolutionString[]; /** * An array of intraday (minutes) resolutions that your datafeed supports. Items in the array should be listed in ascending order, for example: `["1", "2"]`. * * This property is required to enable intraday resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-minutes-intraday) article for more information. * Note that each resolution in `intraday_multipliers` should be handled in the {@link IDatafeedChartApi.getBars} implementation. * Consider the [example](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#example). * * The library also uses resolutions listed in `intraday_multipliers` to display higher resolution that your datafeed does not explicitly support. If `intraday_multipliers` is not specified, the library cannot build additional resolutions. * * Note that the library **cannot** build daily, weekly, or monthly resolutions using intraday data. * @default [] — specifies that the datafeed can provide data for any requested resolution. */ intraday_multipliers?: string[]; /** * A flag indicating whether your datafeed contains seconds data for this symbol. * If `true`, the library requests this data when a seconds resolution is selected. If `false`, _No data here_ is displayed on the chart. * * You should set `has_seconds` to `true` to enable seconds resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-seconds) article for more information. * @default false */ has_seconds?: boolean; /** * A flag indicating whether your datafeed contains ticks data for this symbol. * If `true`, the library requests this data when a resolution in ticks is selected. If `false`, _No data here_ is displayed on the chart. * * You should set `has_ticks` to `true` to enable ticks resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-ticks) article for more information. * @default false */ has_ticks?: boolean; /** * An array of seconds resolutions that your datafeed supports. Items in the array should be listed in ascending order and **should not** include letters, for example: `["1", "2"]`. * This property is required to enable seconds resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-seconds) article for more information. * * The library also uses resolutions listed in `seconds_multipliers` to display higher resolution that your datafeed does not explicitly support. If `seconds_multipliers` is not specified, the library cannot build additional resolutions. * Consider the example. You need to enable one-second and five-second resolutions but your datafeed contains only one-second data. In this case, you should set `seconds_multipliers` to `["1"]`. * The library will build the five-second resolution from one-second data. */ seconds_multipliers?: string[]; /** * The boolean value showing whether or not seconds bars for this symbol can be built from ticks. Only available in Trading Platform. * * * {@link LibrarySymbolInfo.has_seconds} must also be `true` * * {@link LibrarySymbolInfo.has_ticks} must also be `true` * * {@link LibrarySymbolInfo.seconds_multipliers} must be an empty array or only contain multipliers that the datafeed provides itself * * The library builds resolutions from ticks only if there are no seconds resolutions from the datafeed or the provided resolutions are larger then the required one. For example, the datafeed provides `3S` resolution. In this case, the library can build only `1S` or `2S` resolutions from ticks. Resolutions such as `15S` will be build with seconds bars. * @default false */ build_seconds_from_ticks?: boolean; /** * A flag indicating whether your datafeed contains daily data for this symbol. * If `true`, the library requests this data when a daily resolution is selected. If `false`, _No data here_ is displayed on the chart. * * `has_daily` is set to `true` by default. However, you should also specify {@link daily_multipliers} to enable daily resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-days) article for more information. * @default true */ has_daily?: boolean; /** * An array of daily resolutions that your datafeed supports. Items in the array should be listed in ascending order and **should not** include letters, for example: `["1", "2"]`. * This property is required to enable daily resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-days) article for more information. * * The library also uses resolutions listed in `daily_multipliers` to display higher resolution that your datafeed does not explicitly support. If `daily_multipliers` is not specified, the library cannot build additional resolutions. * @default ["1"] */ daily_multipliers?: string[]; /** * A flag indicating whether your datafeed contains weekly or monthly data for this symbol. If `true`, the library requests this data when the corresponding resolution is selected. * To enable weekly or monthly resolutions, you should also specify the {@link weekly_multipliers} or {@link monthly_multipliers} properties. * Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-weeks--months) article for more information. * * If `has_weekly_and_monthly` is set to `false`, the library attempts to build the resolutions using daily bars. Note that building bars requires a large number of requests to your datafeed. * If the library fails to build bars, _No data here_ is displayed on the chart. * @default false */ has_weekly_and_monthly?: boolean; /** * An array of weekly resolutions that your datafeed supports. Items in the array should be listed in ascending order and **should not** include letters, for example: `["1", "3"]`. * This property is required to enable weekly resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-weeks--months) article for more information. * * The library also uses resolutions listed in `weekly_multipliers` to display higher resolution that your datafeed does not explicitly support. If `weekly_multipliers` is not specified, the library cannot build additional resolutions. * @default ['1'] */ weekly_multipliers?: string[]; /** * An array of monthly resolutions that your datafeed supports. Items in the array should be listed in ascending order and **should not** include letters, for example: `["1", "3", "6", "12"]`. * This property is required to enable monthly resolutions. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution#resolution-in-weeks--months) article for more information. * * The library also uses resolutions listed in `monthly_multipliers` to display higher resolution that your datafeed does not explicitly support. If `monthly_multipliers` is not specified, the library cannot build additional resolutions. * @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; /** * Represents what values are supported by the symbol. Possible values: * * - `ohlcv` — the symbol supports open, high, low, close prices and has volume. * - `ohlc` — the symbol supports open, high, low, close, prices but doesn't have volume. * - `c` — the symbol supports only close price. This makes the chart show the symbol data using only line-based styles. * @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. * For `delayed_streaming` and `endofday` type of data, the status is displayed as an icon and the *Data is delayed* section in the [_Legend_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#display-delayed-data-information), next to the market status icon. * Note that you should also enable the [`display_data_mode`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#display_data_mode) featureset. * * When declaring `delayed_streaming` you also have to specify its {@link LibrarySymbolInfo.delay} in seconds. */ data_status?: "streaming" | "endofday" | "delayed_streaming"; /** * Type of delay that is associated to the data or real delay for real time data. * - `0` for realtime * - `-1` for endofday * - or delay in seconds (for delayed realtime) */ delay?: number; /** * 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`. * The library will request data for this symbol starting from that time point. */ expiration_date?: number; /** Sector for stocks to be displayed in the Security Info. */ sector?: string; /** Industry for stocks to be displayed in the Security 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 Security 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[]; /** * An ID of a subsession specified in {@link subsessions}. The value must match the subsession that is currently displayed on the chart. * For more information, refer to the [Extended sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#extended-sessions) section. */ subsession_id?: string; /** * An array of objects that contain information about certain subsessions within the extended session. * For more information, refer to the [Extended sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#extended-sessions) section. */ subsessions?: LibrarySubsessionInfo[]; /** * Optional ID of a price source for a symbol. Should match one of the price sources from the {@link price_sources} array. * * Note that you should set the [`symbol_info_price_source`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#symbol_info_price_source) featureset to `true` to display the symbol price source in the main series legend. */ price_source_id?: string; /** * Supported price sources for the symbol. * Price sources appear in the series legend and indicate the origin of values represented by symbol bars. * Example price sources: "Spot Price", "Ask", "Bid", etc. * The price source information is valuable when viewing non-OHLC series types. * * Note that you should set the [`symbol_info_price_source`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#symbol_info_price_source) featureset to `true` to display the symbol price source in the main series legend. * @example [{ id: '1', name: 'Spot Price' }, { id: '321', name: 'Bid' }] */ price_sources?: SymbolInfoPriceSource[]; /** * URL of image/s to be displayed as the logo/s for the symbol. The `show_symbol_logos` featureset needs to be enabled for this to be visible in the UI. * * - If a single url is returned then that url will solely be used to display the symbol logo. * - If two urls are provided then the images will be displayed as two partially overlapping * circles with the first url appearing on top. This is typically used for FOREX where you would * like to display two country flags are the symbol logo. * * The image/s should ideally be square in dimension. You can use any image type which * the browser supports natively. * * Examples: * - `https://yourserver.com/apple.svg` * - `/images/myImage.png` * - `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3...` * - `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4...` */ logo_urls?: [ string ] | [ string, string ]; /** * URL of image to be displayed as the logo for the exchange. The `show_exchange_logos` featureset needs to be enabled for this to be visible in the UI. * * The image should ideally be square in dimension. You can use any image type which * the browser supports natively. Simple SVG images are recommended. * * Examples: * - `https://yourserver.com/exchangeLogo.svg` * - `/images/myImage.png` * - `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3...` * - `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4...` */ exchange_logo?: string; /** * Additional metadata to include with the symbol information. * These parameters will not affect existing properties such as 'ticker' or 'name' * and will not be processed by the library. However, they can be accessed later * through the {@link IChartWidgetApi.symbolExt} method, impacting existing * properties such as 'ticker' or 'name'. */ library_custom_fields?: Record; } export interface Mark { /** ID of the mark */ id: string | number; /** * Time for the mark. * Unix timestamp in seconds. */ 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://yourserver.com/adobe.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 { /** Border color */ border: string; /** Background color */ background: string; } /** * 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 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; } /** * [Symbol Search](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search) result item. * Pass the resulting array of symbols as a parameter to {@link SearchSymbolsCallback} of the [`searchSymbols`](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#searchsymbols) method. * * @example * ``` * { * description: 'Apple Inc.', * exchange: 'NasdaqNM', * symbol: 'AAPL', * ticker: 'AAPL', * type: 'stock', * } * ``` */ export interface SearchSymbolResultItem { /** Short symbol name */ symbol: string; /** Description */ description: string; /** Exchange name */ exchange: string; /** * It is a unique identifier for a particular symbol in your [symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology). * * You should avoid using colons (":") in ticker values unless you are following the TradingView format: "NYSE:IBM". Using colons may cause unexpected behaviour and display bugs. * * Corresponds with {@link LibrarySymbolInfo.ticker}. */ ticker?: string; /** * Type of symbol * * 'stock' | 'futures' | 'forex' | 'index' */ type: string; /** * URL of image/s to be displayed as the logo/s for the symbol. The `show_symbol_logos` featureset needs to be enabled for this to be visible in the UI. * * - If a single url is returned then that url will solely be used to display the symbol logo. * - If two urls are provided then the images will be displayed as two partially overlapping * circles with the first url appearing on top. This is typically used for FOREX where you would * like to display two country flags as the symbol logo. * * The image/s should ideally be square in dimension. You can use any image type which * the browser supports natively. Simple SVG images are recommended. * * Examples: * - `https://yourserver.com/symbolName.svg` * - `/images/myImage.png` * - `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3...` * - `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4...` */ logo_urls?: [ string ] | [ string, string ]; /** * URL of image to be displayed as the logo for the exchange. The `show_exchange_logos` featureset needs to be enabled for this to be visible in the UI. * * The image should ideally be square in dimension. You can use any image type which * the browser supports natively. Simple SVG images are recommended. * * Examples: * - `https://yourserver.com/exchangeLogo.svg` * - `/images/myImage.png` * - `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3...` * - `data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4...` */ exchange_logo?: string; } export interface SymbolInfoPriceSource { /** Unique ID */ id: string; /** Short name */ name: string; } /** 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#enable-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; /** * Trading session type, such as `"regular"` or `"extended"`, that the chart should currently display. */ session?: string; } export interface TimescaleMark { /** ID of the timescale mark */ id: string | number; /** * Time for the mark. * Unix timestamp in seconds. */ 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; } export interface Unit { /** Unique ID */ id: string; /** Short name */ name: string; /** Description */ description: string; } export type CustomTimezones = "Africa/Cairo" | "Africa/Casablanca" | "Africa/Johannesburg" | "Africa/Lagos" | "Africa/Nairobi" | "Africa/Tunis" | "America/Anchorage" | "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/Dhaka" | "Asia/Dubai" | "Asia/Ho_Chi_Minh" | "Asia/Hong_Kong" | "Asia/Jakarta" | "Asia/Jerusalem" | "Asia/Kabul" | "Asia/Karachi" | "Asia/Kathmandu" | "Asia/Kolkata" | "Asia/Kuala_Lumpur" | "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/Azores" | "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/Prague" | "Europe/Riga" | "Europe/Rome" | "Europe/Stockholm" | "Europe/Tallinn" | "Europe/Vienna" | "Europe/Vilnius" | "Europe/Warsaw" | "Europe/Zurich" | "Pacific/Auckland" | "Pacific/Chatham" | "Pacific/Fakaofo" | "Pacific/Honolulu" | "Pacific/Norfolk" | "US/Mountain"; export type DOMCallback = (data: DOMData) => void; export type DatafeedErrorCallback = (reason: string) => void; export type GetMarksCallback = (marks: T[]) => void; export type HistoryCallback = (bars: Bar[], meta?: HistoryMetadata) => void; export type LibrarySessionId = "regular" | "extended" | "premarket" | "postmarket"; export type MarkConstColors = "red" | "green" | "blue" | "yellow"; export type OnReadyCallback = (configuration: DatafeedConfiguration) => void; 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; /** * Resolution or time interval is a time period of one bar. Advanced Charts 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, `5T` — five ticks, `100T` — one hundred ticks * 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; export type SearchSymbolsCallback = (items: SearchSymbolResultItem[]) => void; export type SeriesFormat = "price" | "volume"; export type ServerTimeCallback = (serverTime: number) => void; export type SubscribeBarsCallback = (bar: Bar) => void; export type TimeScaleMarkShape = "circle" | "earningUp" | "earningDown" | "earning"; export type Timezone = "Etc/UTC" | CustomTimezones; export type VisiblePlotsSet = "ohlcv" | "ohlc" | "c" | "hlc"; export as namespace TradingView; export {}; URL: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues ============================================================================================== # Datafeed: common issues This article describes common issues that users face when they implement the [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api). :::tip [Enable debug mode] to identify how the library loads, processes, and resolves data. ::: ## getBars is called multiple times The library calls [`getBars`] multiple times if the amount of provided data [is less than requested](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#correct-amount-of-data). To debug this issue, [enable console logs](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#debug). Consider the following example: ```js FEED [AAPL|1D]: Next time received: `2018-03-27T00:00:00.000Z` FEED [AAPL|1D]: Processing pending subscribers, count=2 // The library requests 329 bars from the datafeed FEED [AAPL|1D]: Leftmost subscriber requires 329 bars prior 2022-11-09T00:00:00.000Z FEED [AAPL|1D]: Requesting data: [2016-12-22T00:00:00.000Z ... 2021-08-06T00:00:00.000Z, 329 bars] // The datafeed responds with 157 bars // 157 is less than requested, so the library will request the remaining bars from the datafeed FEED [AAPL|1D]: Receiving bars: total 157 bars in [2017-08-10T00:00:00.000Z ... 2018-03-27T00:00:00.000Z], requested range: [2016-12-22T00:00:00.000Z ... 2021-08-06T00:00:00.000Z, 329 bars] FEED [AAPL|1D]: Processing pending subscribers, count=2 // The library requests 172 bars from the datafeed // It requests 172 bars because 329 - 157 = 172 FEED [AAPL|1D]: Leftmost subscriber requires 172 bars prior 2017-08-10T00:00:00.000Z FEED [AAPL|1D]: Requesting data: [2016-04-26T00:00:00.000Z ... 2016-12-22T00:00:00.000Z, 172 bars] // The datafeed responds with 169 bars // 169 is less than requested, so the library will request the remaining bars from the datafeed FEED [AAPL|1D]: Receiving bars: total 169 bars in [2016-04-26T00:00:00.000Z ... 2016-12-22T00:00:00.000Z], requested range: [2016-04-26T00:00:00.000Z ... 2016-12-22T00:00:00.000Z, 172 bars] FEED [AAPL|1D]: Processing pending subscribers, count=2 // The library requests 3 bars from the datafeed // It requests 3 bars because 172 - 169 = 3 FEED [AAPL|1D]: Leftmost subscriber requires 3 bars prior 2016-04-26T00:00:00.000Z FEED [AAPL|1D]: Requesting data: [2016-04-23T00:00:00.000Z ... 2016-04-26T00:00:00.000Z, 3 bars] // The datafeed responds with 2 bars // 2 is less than requested, so the library will request the remaining bars from the datafeed FEED [AAPL|1D]: Receiving bars: total 2 bars in [2016-04-25T00:00:00.000Z ... 2016-04-26T00:00:00.000Z], requested range: [2016-04-23T00:00:00.000Z ... 2016-04-26T00:00:00.000Z, 3 bars] FEED [AAPL|1D]: Processing pending subscribers, count=2 // The library requests 2 bars from the datafeed // Here the library actually requests 1 more bar than it requires, but that's OK and datafeed implementations should be able to handle it FEED [AAPL|1D]: Leftmost subscriber requires 2 bars prior 2016-04-25T00:00:00.000Z FEED [AAPL|1D]: Requesting data: [2016-04-21T00:00:00.000Z ... 2016-04-23T00:00:00.000Z, 2 bars] FEED [AAPL|1D]: Receiving bars: total 2 bars in [2016-04-21T00:00:00.000Z ... 2016-04-22T00:00:00.000Z], requested range: [2016-04-21T00:00:00.000Z ... 2016-04-23T00:00:00.000Z, 2 bars] FEED [AAPL|1D]: Processing pending subscribers, count=2 ``` To avoid multiple `getBars` requests, you can return bars **before** the [`from`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PeriodParams#from) date until their number matches the [`countBack`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PeriodParams#countback) value. For example, the chart requests 300 bars in the range `[2019-06-01T00:00:00…2020-01-01T00:00:00)`, and your backend has only 250 bars in the requested period. Return these 250 bars and 50 bars prior to `2019-06-01T00:00:00`. ## Bar data is mutable The library may mutate the values of some [`Bar`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Bar) objects that you provide. You can make a copy of your data to avoid potential issues. ## Requested data is outside visible range The `[from, to)` [range](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#correct-amount-of-data) usually matches [`VisibleTimeRange`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.VisibleTimeRange). However, sometimes the library requests more bars than are visible, because indicators require some additional history. ## Time violation The _putToCacheNewBar: time violation_ issue appears if the library receives a bar which timestamp is less than the timestamp of the last bar on the chart. To debug this issue, check that you follow the rules below: - You provide bars in **ascending** time order. Refer to [Bar order](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#bar-order) for more information. - You update only the last bar on a chart or add a new one using the `subsсribeBars` method. Refer to [`subsсribeBars`](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#subscribebars) for more information. - You use different subscribers to update data on different symbols/resolutions and you send updates to the correct subscriber. Refer to [Multiple subscriptions](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#multiple-subscriptions) for more information. - For daily, weekly, and monthly bars, the [`time`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Bar#time) value represents the **beginning of the trading day** at 00:00:00 UTC, not the beginning of the session. ## Maximum call stack size exceeded If the _Uncaught RangeError: Maximum call stack size exceeded_ issue occurs, you should check that you evoke all callbacks asynchronously in your datafeed implementation. Refer to [Asynchronous callbacks](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api#asynchronous-callbacks) for more information. ## Data must have unique times The _Assertion failed: data must have unique times_ issue appears if the library receives a bar whose timestamp matches the timestamp of the bar that was loaded before. To debug this issue, check that you follow the rules below: - When you return data to [`getBars`], you should not include a bar for the [`to`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PeriodParams#to) date because this bar was sent in a previous response. For more information on how to send data, refer to the [Correct amount of data](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#correct-amount-of-data) section. - Your custom indicator [maps](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Studies-Extending-The-Time-Scalemapping-times) the main [series](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryseries) times correctly. If the custom indicator has more times than the main series, you can use the [Extending the time scale feature](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Studies-Extending-The-Time-Scaleextending-the-time-scale-feature) that allows indicators to define their points on a time scale. ## Library shifts bar time If the library considers the bar time incorrect, it shifts the time to the nearest expected value. In this case, the bar time displayed on the chart does not coincide with the bar time your datafeed provides. To debug this issue, check that you follow the rules below: - You correctly specified the following properties in [`LibrarySymbolInfo`]: - [`timezone`] contains a time zone of the symbol's **exchange**. - [`session`] contains trading hours for the symbol. The time zone of the trading hours corresponds to the **`timezone`** value. - The bar time should be inside the trading hours specified in `session`. Otherwise, the library ignores bars with such time values. - Time values of any bars should be represented with Unix timestamps in **UTC**. - For daily, weekly, and monthly bars, the [`time`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Bar#time) value represents the **beginning of the trading day** at 00:00:00 UTC, not the beginning of the session. - If you provide real-time updates, the `time` value should represent the **beginning of the bar**, not the time of the update. For example, for 5-minute bars, all updates between 10:00 and 10:04:59 must use time value representing 10:00. If you instead send updates with their actual time (e.g., 10:02, 10:03), the bar will be misaligned and displayed incorrectly. - The library processes DST. You do not need to adjust time values manually. ### Example - The current symbol is AAPL. - `timezone` is `"America/New_York"`. - `session` is `"0930-1630"`. - The selected resolution is two hours. The table below shows time values that the library expects based on the resolution, timestamps that a datafeed provides, and time values displayed on the chart. Expected time value | Received timestamp | Timestamp value in UTC | Timestamp value in UTC-5 | Displayed time value ---------|----------|--------- |--------- | --------- | 09:30 | `1706106600000` | Wed Jan 24 2024 14:30:00 | Wed Jan 24 2024 09:30:00 | Wed Jan 24 2024 09:30:00 11:30 | `1706113800000` | Wed Jan 24 2024 16:30:00 | Wed Jan 24 2024 11:30:00 | Wed Jan 24 2024 11:30:00 13:30 | `1706122800000` | Wed Jan 24 2024 19:00:00 | Wed Jan 24 2024 **14:00:00** | Wed Jan 24 2024 **13:30:00**

The library shifts the recieved value to the nearest expected one — the beginning of the interval. 15:30 | `1706128200000` | Wed Jan 24 2024 20:30:00 | Wed Jan 24 2024 15:30:00 | Wed Jan 24 2024 15:30:00 Therefore, incorrect `timezone`, `session`, and `time` values can lead to bars being hours behind the expected ones. ## Internet connection issues When users experience internet connection issues, the library may fail to receive data during [`getBars`] calls. The library itself does not restore the connection. Instead, you need to implement the following behavior to ensure reconnection: 1. Call the [`resetCache`] method to clear all cached bar data. 2. Call [`resetData`]. This method makes the library call `getBars`, thereby re-requesting all the data for the deleted symbol. To limit the data request to only the visible range, enable the [`request_only_visible_range_on_reset`] featureset. ### For offline applications Mobile or browser applications designed to work offline have distinct behavior. If the library attempts to resolve a symbol through [`resolveSymbol`] while the user is offline, the library fails to load the data. In this case, users may experience an error or no response from the library. To resolve this issue, you can set a "fake" symbol name. This makes the library request symbol information again. Consider the example below that simulates the network being offline. The example shows how to set a "fake" symbol name while still resolving the desired symbol for the user. ## Quotes are not displayed or refreshed When using [Trading Platform], you may encounter issues where [quotes] do not appear or update correctly in the UI. Follow these steps to troubleshoot: 1. Ensure [`getQuotes`] and [`subscribeQuotes`] are correctly implemented. Some **common mistakes** include: - The symbol name returned in the [`n`] field of the [`QuoteOkData`] object does not match the symbol requested by the library. Make sure the symbol names are exactly the same as in the requests. - Values in the [`DatafeedQuoteValues`] object do not match the expected data types. 2. Verify that the data you send makes logical sense. Some **common mistakes** include: - Sending zero values for bid/ask prices when they should be positive numbers.
- Providing negative or unrealistic values in fields where they are not expected.
- Adding fields that do not exist in the expected interface, which can cause the request to fail. ## Delays in Trading Platform UI elements When using [Trading Platform], you may experience delays in loading UI elements such as [Buy/Sell buttons], [Order Ticket], [Account Manager], or [context menus]. These UI elements depend on real-time [quotes] to display accurate pricing. If the library does not receive valid quotes, it still attempts to fetch them before rendering the UI. This leads to delays — often around 10 seconds, which matches the library's timeout behavior. To fix this issue, ensure [`getQuotes`] and [`subscribeQuotes`] are correctly implemented. Some **common mistakes** include: - The symbol name returned in the [`n`] field of the [`QuoteOkData`] object does not match the symbol requested by the library. Make sure the symbol names are exactly the same as in the requests. - Values in the [`DatafeedQuoteValues`] object do not match the expected data types. ## New bar doesn't appear after the previous one closes This is expected behavior. A new bar is created only after the first update for that interval arrives. At the exact moment the previous bar closes, there is no data yet for the new one, so the library cannot pre-populate it. Once the first update is received, the new bar will appear. [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [Buy/Sell buttons]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal#buysell-buttons-and-lines [context menus]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu [`DatafeedQuoteValues`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.DatafeedQuoteValues [Enable debug mode]: https://www.tradingview.com/charting-library-docs/latest/tutorials/enable-debug-mode#enable-debug-mode-for-data-connection [`getBars`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#getbars [`getQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes [`LibrarySymbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo [`n`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.QuoteOkData#n [Order Ticket]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket [`QuoteOkData`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.QuoteOkData [`resetData`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#resetdata [`resetCache`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#resetCache [`resolveSymbol`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol [`request_only_visible_range_on_reset`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#request_only_visible_range_on_reset [`session`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session [`subscribeBars`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#subscribebars [`subscribeQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribequotes [`timezone`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#timezone [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [quotes]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/quotes URL: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions ================================================================================================ # Extended sessions An extended session is a period beyond the official trading hours of the exchange when trading still occurs. The library allows you to display extended sessions for symbols that support them. Note that extended sessions are only visible on [intraday resolutions](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolutionresolution-in-minutes-intraday). The extended session includes regular, pre-market, and post-market subsessions. Either a pre-market or post-market subsession can be missed. When the chart displays an extended session, the subsessions are represented as colored areas. A chart showing subsessions ## Enable extended sessions To enable extended sessions, do the following: - Add the [`pre_post_market_sessions`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetspre_post_market_sessions) featureset to the [`enabled_features`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#enabled_features) array. - Specify the [`subsession_id`](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologysubsession_id) and [`subsessions`](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologysubsessions) properties in [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) for symbols that support extended sessions. Refer to the [Configure datafeed](#configure-the-datafeed) section for more information. ### Specify the default session type The chart can display regular or extended sessions. To specify the default session type, provide the [`mainSeriesProperties.sessionId`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiessessionid) property within [`overrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#overrides). ```js var widget = window.tvWidget = new TradingView.widget({ // ... overrides: { "mainSeriesProperties.sessionId": "extended", } }); ``` ### Specify subsession colors Subsessions are represented on the chart as colored areas. You can specify default colors for pre-market and post-market subsessions using the [`overrides`] property in the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor). ```js var widget = window.tvWidget = new TradingView.widget({ // ... overrides: { "backgrounds.preMarket.color": "rgba(200,0,0,0.08)", "backgrounds.postMarket.color": "rgba(0,0,200,0.08)", } }); ``` To change the colors on the fly, use the [`applyOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#applyoverrides) method. ```javascript widget.applyOverrides({"backgrounds.outOfSession.color": "rgba(0,0,0,0.2)"}); widget.applyOverrides({"backgrounds.preMarket.color": "rgba(200,0,0,0.08)"}); widget.applyOverrides({"backgrounds.postMarket.color": "rgba(0,0,200,0.08)"}); ``` Users can adjust the subsession colors in the _Chart settings_ dialog in the UI. A chart showing subsessions ## Change the session type You can switch between the sessions in the UI or using the API. ### In UI Users can change the session type in the following ways: - Use the drop-down menu on the bottom toolbar. Bottom toolbar extended session button - Use the drop-down menu in the _Chart settings_ dialog. Bottom toolbar extended session button ### Using API You can use the [`applyOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#applyoverrides) method to change the session type on the fly. ```js widget.applyOverrides({ "mainSeriesProperties.sessionId": "extended" }); ``` ## Configure the datafeed To display extended sessions on the chart, you should provide additional data in [`LibrarySymbolInfo`]. :::tip `LibrarySymbolInfo` is an object that contains information about a certain symbol. You should return this object to the library when it calls the [`resolveSymbol`] method. Refer to [Symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology) for more information on how to implement `LibrarySymbolInfo`. ::: Consider the `LibrarySymbolInfo` object for a symbol that supports a regular session only. ```json { "name": "AAPL", "ticker": "AAPL", "exchange": "NasdaqNM", "timezone": "Etc/UTC", "description": "Apple Inc.", "type": "stock", "pricescale": 100, "minmov": 1, "has_intraday": true, "supported_resolutions": ["60"], "has_daily": false, "intraday_multipliers": ["1"], "format": "price", "session": "0930-1600" } ``` If the symbol supports an extended session, you should additionally specify the [`subsession_id`](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologysubsession_id) and [`subsessions`] properties. The code sample below specifies an extended session that starts at 04:00 and ends at 20:00. It includes a pre-market subsession from 04:00 to 09:30, a regular subsession from 09:30 to 16:00, and a post-market subsession from 16:00 to 20:00. ```json { "name": "AAPL", "ticker": "AAPL", "exchange": "NasdaqNM", "timezone": "Etc/UTC", "description": "Apple Inc.", "type": "stock", "pricescale": 100, "minmov": 1, "has_intraday": true, "supported_resolutions": ["60"], "has_daily": false, "intraday_multipliers": ["1"], "format": "price", "session": "0930-1600", // highlight-start "subsession_id": "regular", "subsessions": [ { "description": "Regular Trading Hours", "id": "regular", "session": "0930-1600" }, { "description": "Extended Trading Hours", "id": "extended", "session": "0400-2000" }, { "description": "Pre-market", "id": "premarket", "session": "0400-0930" }, { "description": "Post-market", "id": "postmarket", "session": "1600-2000" } ] // highlight-end } ``` Note that the `session` and `subsession_id` values depend on the current session type selected on the chart. If the session type is changed either [in the UI](#in-ui) or [using the API](#using-api), you should **update** the [`LibrarySymbolInfo`] object. ### Handle session switch When the session type is changed, the library needs to request all data from scratch. To do this, the library calls [`resolveSymbol`] once again with an additional [`SymbolResolveExtension`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SymbolResolveExtension) parameter. In `SymbolResolveExtension`, the [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SymbolResolveExtension#session) property indicates what session type should be displayed on the chart. In response, you should return the updated [`LibrarySymbolInfo`] object with the following properties changed: - `subsession_id`: the property's value should match the [`SymbolResolveExtension.session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SymbolResolveExtension#session) value. The value is either `"regular"` or `"extended"`. - `session`: the property's value should match the corresponding [`LibrarySubsessionInfo.session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySubsessionInfo#session) value specified in `subsessions`. For example, if the chart displays `"extended"` session, and for this session type `LibrarySubsessionInfo.session` is `"0400-2000"`, the `LibrarySymbolInfo.session` value should also be `"0400-2000"`. :::tip You can use the following expression to make sure that [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session) is correct. The expression should always be `true`: ```javascript symbolInfo.session === symbolInfo.subsessions.find(x => x.id === subsession_id).session ``` ::: #### Example Consider the example. The current symbol on the chart is `AAPL` and the session type is regular. You should return the following [`LibrarySymbolInfo`] object to the library: ```json { "name": "AAPL", "ticker": "AAPL", "exchange": "NasdaqNM", "timezone": "Etc/UTC", "description": "Apple Inc.", "type": "stock", "pricescale": 100, "minmov": 1, "has_intraday": true, "supported_resolutions": ["60"], "has_daily": false, "intraday_multipliers": ["1"], "format": "price", // highlight-start "session": "0930-1600", "subsession_id": "regular", // highlight-end "subsessions": [ // highlight-start { "description": "Regular Trading Hours", "id": "regular", "session": "0930-1600" }, // highlight-end { "description": "Extended Trading Hours", "id": "extended", "session": "0400-2000" }, { "description": "Pre-market", "id": "premarket", "session": "0400-0930" }, { "description": "Post-market", "id": "postmarket", "session": "1600-2000" } ] } ``` Then, the chart is switched to the extended session. The library calls `resolveSymbol` once again. In response, you should update the `subsession_id` and `session` properties, so they match the corresponding values defined for the extended session in `subsessions`: ```json { "name": "AAPL", "ticker": "AAPL", "exchange": "NasdaqNM", "timezone": "Etc/UTC", "description": "Apple Inc.", "type": "stock", "pricescale": 100, "minmov": 1, "has_intraday": true, "supported_resolutions": ["60"], "has_daily": false, "intraday_multipliers": ["1"], "format": "price", // highlight-start "session": "0400-2000", // The value is changed "subsession_id": "extended", // The value is changed // highlight-end "subsessions": [ { "description": "Regular Trading Hours", "id": "regular", "session": "0930-1600" }, // highlight-start { "description": "Extended Trading Hours", "id": "extended", "session": "0400-2000" }, // highlight-end { "description": "Pre-market", "id": "premarket", "session": "0400-0930" }, { "description": "Post-market", "id": "postmarket", "session": "1600-2000" } ] } ``` ### Corrections for extended sessions Corrections are changes in the default trading session for specific days. For regular sessions, you should only specify the [`corrections`](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologycorrections) property in `LibrarySymbolInfo`. However, for extended sessions, you should additionally provide [`session-correction`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySubsessionInfo#session-correction) for each subsession in `subsessions`. For example, you need to display the following sessions: - Regular. The default regular session starts at 09:30 and ends at 17:00. On 2019‑07‑03, 2019‑11‑29, and 2019‑12‑24, the session starts at 09:30 and ends at 13:00. - Extended. The default extended session starts at 04:00 and ends at 20:00. On 2019‑07‑03, 2019‑11‑29, and 2019‑12‑24, the session starts at 04:00 and ends at 21:00. - Pre-market. This session always starts at 04:00 and ends at 09:30. - Post-market. The default post-market session starts at 17:00 and ends at 20:00. However, on 2019‑07‑03, 2019‑11‑29, and 2019‑12-24, the session time shifts because of the changes in the regular and extended sessions. On these days, the post-market session starts at 13:00 and ends at 21:00. ```javascript { // ... "subsessions": [ { "description": "Regular Trading Hours", "id": "regular", "session": "0930-1700", "session-correction": "0930-1300:20190703,20191129,20191224", }, { "description": "Extended Trading Hours", "id": "extended", "session": "0400-2000", "session-correction": "0400-2100:20190703,20191129,20191224", }, { "description": "Pre-market", "id": "premarket", "session": "0400-0930", }, { "description": "Post-market", "id": "postmarket", "session": "1700-2000", "session-correction": "1300-2100:20190703,20191129,20191224", } ], } ``` :::caution Time changes in one session may cause changes in the related sessions. Make sure you specify corrections for all sessions that require them to avoid visual bugs. ::: As mentioned [earlier](#handle-session-switch), you should update the `session` and `session_id` properties in `LibrarySymbolInfo` when the session type is changed. If you specify corrections, you should also update the `corrections` property. This property should contain one of the `session-correction` values, depending on the currently selected session type in the UI. For example, the current type is `"regular"`, therefore, `corrections` is equal to the `session-correction` value specified for the regular session. ```javascript { // ... "session": "0930-1700", "subsession_id": "regular", // highlight-next-line "corrections": "0930-1300:20190703,20191129,20191224", "subsessions": [ // highlight-start { "description": "Regular Trading Hours", "id": "regular", "session": "0930-1700", // highlight-next-line "session-correction": "0930-1300:20190703,20191129,20191224", }, { "description": "Extended Trading Hours", "id": "extended", "session": "0400-2000", "session-correction": "0400-2100:20190703,20191129,20191224", }, // ... ], } ``` If the type is changed to `"extended"`, you should update `corrections` to match the `session-correction` value specified for the extended session. ```javascript { // ... "session": "0400-2000", "subsession_id": "extended", // highlight-next-line "corrections": "0400-2100:20190703,20191129,20191224", "subsessions": [ { "description": "Regular Trading Hours", "id": "regular", "session": "0930-1700", "session-correction": "0930-1300:20190703,20191129,20191224", }, { "description": "Extended Trading Hours", "id": "extended", "session": "0400-2000", // highlight-next-line "session-correction": "0400-2100:20190703,20191129,20191224", }, // ... ], } ``` ## Enable the price line :::info This feature is only available in [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal) as it requires [quote data](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/quotes). ::: The library allows you to display pre-/post-market price lines. These lines appear only during the pre-/post-market sessions when the chart shows only the regular session. However, if the chart is set to display the extended session, the lines will not be visible, as the data is already displayed on the chart. Pre-marker price line To enable the lines, you should do the following: - Enable the [`pre_post_market_price_line`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetspre_post_market_price_line) featureset. - Provide the [`rtc`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.DatafeedQuoteValues#rtc) property in the [`DatafeedQuoteValues`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.DatafeedQuoteValues) object. You can also display information on the pre-/post-market price in [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminaldetails). To do this, you should additionally provide the [`rch`], [`rchp`], and [`rtc_time`] properties in the [`DatafeedQuoteValues`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.DatafeedQuoteValues) object. Pre-market price in Details [`LibrarySymbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo [`resolveSymbol`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol [`subsessions`]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#subsessions [`overrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#overrides [`rch`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.DatafeedQuoteValues#rch [`rchp`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.DatafeedQuoteValues#rchp [`rtc_time`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.DatafeedQuoteValues#rtc_time URL: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology ======================================================================================== # Symbology The library requires information about the symbol to request and process data correctly. This information should be arranged in a specified format and supplied as a [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) object. This article explains the most challenging concepts of the `LibrarySymbolInfo` implementation. You can find the complete list of interface parameters, and their descriptions, in the [API](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) section. The library calls the [`resolveSymbol`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#resolvesymbol) method to request symbol information. To provide this information, create the [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) object and pass it to [`ResolveCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#resolvecallback) as a parameter. :::tip Refer to the [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api) topic for more information on how to supply the chart with data. ::: ## Symbol name The library addresses a symbol by a unique identifier. You can use [`ticker`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#ticker) or [`name`] to specify such an identifier for a certain symbol. :::info The ticker or name should not contain information other than an identifier for a symbol. Therefore, they should not contain the exchange. ::: ### name The `name` property is an identifier for a symbol within an exchange, such as `AAPL` or `9988` (on Hong Kong exchange). This identifier is visible to users. Note that the `name` value does not have to be unique and can be duplicated for several symbols. By default, `name` is used to [resolve symbols](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol) in the [Datafeed API]. If you use [`ticker`](#ticker), the library will use the ticker for Datafeed API requests. ### ticker If you need to address a symbol by a custom identifier (for example, numeric), you can use `ticker`. It is not displayed to users. You should avoid using colons (":") in ticker values unless you are following the TradingView format: "NYSE:IBM". Using colons may cause unexpected behavior and display bugs. If you provide `ticker`, the library will use it for [Datafeed API] requests. Make sure you provide `ticker` in [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) and [`SearchSymbolResultItem`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SearchSymbolResultItem). ### Letter case By default, all symbol names are shown in uppercase in the UI. To display lowercase symbol names, you should disable the [`uppercase_instrument_names`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsuppercase_instrument_names) featureset and adjust symbol names in the [`resolveSymbol`](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol) and [`symbolSearch`](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#searchsymbols) implementation. Consider the following CodePen example: ## Resolutions Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution) article for information on how to specify the following properties: - [`supported_resolutions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#supported_resolutions) - [`has_seconds`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_seconds) - [`seconds_multipliers`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#seconds_multipliers) - [`has_intraday`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_intraday) - [`intraday_multipliers`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#intraday_multipliers) - [`has_daily`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_daily) - [`daily_multipliers`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#daily_multipliers) - [`has_weekly_and_monthly`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_weekly_and_monthly) - [`weekly_multipliers`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#weekly_multipliers) - [`monthly_multipliers`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#monthly_multipliers) - [`has_ticks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_ticks) ## Time zone The [`timezone`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#timezone) property should contain a time zone of the symbol's exchange. For example, if the symbol's exchange is NASDAQ, the `timezone` value should be `"America/New_York"`. The `timezone` value affects how the library arranges data on the chart. Make sure you specify this property correctly to avoid potential issues, such as [shifted bars](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issueslibrary-shifts-bar-time). For more information about supported time zones, refer to the [Time zones](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezones) article. ## Session The [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session) property contains trading hours for the symbol. The time zone of the trading hours corresponds to the [`timezone`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#timezone) value. The [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session) value affects how the library arranges data on the chart. Make sure you specify this property correctly to avoid potential issues, such as [shifted bars](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issueslibrary-shifts-bar-time). Refer to the [Trading Sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessions) topic for more information on the session format. ### corrections The [`corrections`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#corrections) property allows you to specify changes in a trading session for a specific day. For example, you can extend or shorten the session or reschedule it for another day. The `corrections` value overrides the default session specified in the [`session`](#session) property. You can specify corrections for days in the past and future. The correction is a string that has the `SESSION:YYYYMMDD` format and consists of the following elements: Element | Description | Example ---------|----------|--------- SESSION | Trading hours specified in the same format as the `session` property. Refer to [Session formats](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessionssession-formats) for more information. | 1000‑1400 : | A separator between the session and the day when it is applied. |
YYYYMMDD | A day when the session is applied. | `20181114` If the correction is applied to multiple days, you should list the days starting from the latest one and separate them by comma. For example, `"1000-1400:20180308,20180223,20180101"`. To specify several corrections, list them one by one and use a semicolon as a separator, for example, `"1000-1845:20181113;1000-1400:20181114"`. You can also specify corrections for holidays. Note that the `corrections` property has higher priority than [`session_holidays`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session_holidays). Therefore, if both properties contain the same date, the library applies hours specified in `corrections` for that date. ## Extended sessions The library allows you to display extended trading sessions for symbols that support them. To enable an extended session for a certain symbol, you should specify the properties below. For more information on how to handle the sessions, refer to the dedicated [Extended sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions) article. :::caution The `session`, `corrections`, `subsession_id`, and `subsessions` properties affect the [Market status pop-up](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Status). Make sure you configure these properties to avoid an incorrect status for the symbol. ::: ### subsessions An extended session includes regular, pre-market, and post-market subsessions. Either a pre-market or post-market subsession can be missed. When the chart displays an extended session, the subsessions are represented as colored areas. You should provide information on the extended session and its subsessions to the library using the [`subsessions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#subsessions) property. The property contains an array of [`LibrarySubsessionInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySubsessionInfo) objects, where each object describes a certain subsession. For example, the code sample below specifies an extended session that starts at 04:00 and ends at 20:00. It includes a pre-market subsession from 04:00 to 09:30, a regular subsession from 09:30 to 16:00, and a post-market subsession from 16:00 to 20:00. ```javascript "subsessions": [ { "description": "Regular Trading Hours", "id": "regular", "session": "0930-1600" }, { "description": "Extended Trading Hours", "id": "extended", "session": "0400-2000" }, { "description": "Pre-market", "id": "premarket", "session": "0400-0930" }, { "description": "Post-market", "id": "postmarket", "session": "1600-2000" } ] ``` ### subsession_id The [`subsession_id`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#subsession_id) property specifies the session type that the chart should currently display. The `subsession_id` value is either `"regular"` or `"extended"`. You should update the property's value when the session type is changed. Refer to the [Handle session switch](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessionshandle-session-switch) section for more information. ### Update session value Note that the [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session) value depends on the chart type currently selected on the chart. The property's value should match the corresponding [`LibrarySubsessionInfo.session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySubsessionInfo#session) value specified in [`subsessions`](#subsessions). For example, if the chart displays `"extended"` session, and for this session type `LibrarySubsessionInfo.session` is `"0400-2000"`, the `LibrarySymbolInfo.session` value should also be `"0400-2000"`. You should update `session` when the session type is changed. Refer to the [Handle session switch](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessionshandle-session-switch) section for more information. :::tip You can use the following expression to make sure that `session` is correct. The expression should always be `true`: ```javascript symbolInfo.session === symbolInfo.subsessions.find(x => x.id === subsession_id).session ``` ::: ## Supported price values The [`visible_plots_set`] property indicates which values the symbol supports, such as open, high, low, close, and volume. If you prefer to only provide close values, set `visible_plots_set` to `"c"`. This makes the chart show the symbol data using only line-based styles. ## Price format The library supports the [decimal](#decimal-format) and [fractional](#fractional-format) price formats. To configure how the price displays, specify the following properties: - [`pricescale`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#pricescale) — a number of decimal places or fractions that the price has. - [`minmov`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#minmov) — a number of units that represents the price tick. - [`minmove2`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#minmove2) — a fraction of a fraction. - [`fractional`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#fractional) — a boolean value that shows whether the format is fractional or decimal. These properties' values depend on the chosen format and are not visible to users. ### Decimal format - `pricescale` should be `10^n`, where `n` is the number of decimal places. For example, if the price is `1.01`, set `pricescale` to `100`. - `minmov` depends on the tick size that is calculated as `minmov / pricescale`. For example, if the tick size is `0.25`, set `minmov` to `25`. - `minmove2` should be `0` or not specified. - `fractional` should be `false` or not specified. Consider the following examples: - The security's tick size is `0.01`. To display this security, set `minmov = 1`, `pricescale = 100`. - The security's tick size is `0.0125`. To display this security, set `minmov = 125`, `pricescale = 10000`. - The security's tick size is `0.20`. To display this security, set `minmov = 20`, `pricescale = 100`. #### Variable tick size If you need to adjust a tick size depending on a symbol price, you can additionally specify the [`variable_tick_size`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#variable_tick_size) property. This property should be a `string` that contains prices and the corresponding tick sizes. The library overrides the [`pricescale`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#pricescale) and [`minmov`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#minmov) properties to represent the desired tick size. For example, the `'0.01 10 0.02 25 0.05'` value specifies the following ticks: - For prices less than or equal to 10, the tick size is `0.01`. Therefore, `minmov = 1`, `pricescale = 100`. - For prices greater than 10 but less than or equal to 25, the tick size is `0.02`. Therefore, `minmov = 2`, `pricescale = 100`. - For prices greater than 25, the tick size is `0.05`. Therefore, `minmov = 5`, `pricescale = 100`. Note that you need to initialize `pricescale` and `minmov` regardless of whether you use `variable_tick_size` or not. #### How to display pips You can display pips for symbols that have `forex` or `cfd` type. To do this, set `minmove2` to `10`. In the UI, pips look smaller than the price digits. ![Symbology Pips Example](https://www.tradingview.com/charting-library-docs/img/symbology_pips.png) If `minmove2` is `0` for `forex`/`cfd` symbols, the spread is displayed in ticks, not pips. ### Fractional format The fractional price is displayed as `x'y` (for example, `133'21`), where `x` and `y` are the integer and fractional parts, respectively. A single quote is used as a delimiter. - `pricescale` should be `2^n`. This value represents the number of fractions. - `minmov` depends on the tick size that is calculated as `minmov / pricescale`. For example, if the tick size is `1/4`, set `minmov` to `1`. - `minmove2` should be `0` or not specified. - `fractional` should be `true`. Consider the following examples: - To display a security that has the `1/32` tick size, set `minmov = 1`, `pricescale = 32`. - To display a security that has the `2/8` tick size, set `minmov = 2`, `pricescale = 8`. #### Fraction of a fraction format The fraction of a fraction format is a particular case of the fractional format. It is displayed as `x'y'z` (for example, `133'21'5`), where `z` is a fractional part of `y`. In this case, `minmove2` differs from `0` and represents a fraction of a fraction. For example, the `ZBM2023` tick size is 1/4 of a 32nd. To display this security, set `minmov = 1`, `pricescale = 128`, `minmove2 = 4`. The price is displayed in the UI as follows: - `119'16'0` represents `119 + 16.0/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` [Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api [`name`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#name [`visible_plots_set`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#visible_plots_set URL: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessions =============================================================================================== # Trading sessions A trading session defines the hours in a week when a symbol is actively traded on an exchange. A session is passed to the library in the [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session) field of the [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) object. Session time should be in the **exchange time zone**. Note that the last (rightmost) time of any session is **non-inclusive**. For example, if you specify a `0930-1630` session and select the one‑hour resolution, the following bars are displayed on the chart: `[09:30, 10:30, 11:30, 12:30, 13:30, 14:30, 15:30]`. The period of the last bar starts at 15:30 and ends at 16:30 that coincides with the end of the trading session. :::caution The [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session) value affects how the library arranges data on the chart. Make sure you specify this property correctly to avoid potential issues, such as [shifted bars](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issueslibrary-shifts-bar-time). ::: ## Session formats A trading session is defined by a string. This format allows you to describe a variety of sessions. :::tip You can use the [Session Parser](https) to check your session string. ::: ### 24/7 sessions A session that runs 24 hours a day, 7 days a week, including Saturday and Sunday. It starts at 00:00 and ends at 00:00 the following day. - `24x7` ### Intraday sessions A session within a day. For example: - `0930-1600` starts at 09:30 and ends at 16:00 from Monday to Friday. - `0000-0000` starts at 00:00 and ends at 00:00 the following day from Monday to Friday. ### Overnight sessions In the library, an **overnight** session is a session that starts **before** the trading day. For example, the trading day is Monday, but the session starts on Sunday. A session is considered overnight by default in the following cases: - The start time is more than the end time, for example, `1600-0930`. The session starts at 16:00 on the previous day and ends at 09:30 on the current day. - The start time is equal to the end time, for example, `1700-1700`. The session starts at 17:00 on the previous day and ends at 17:00 on the current day. Note that the `0000-0000` value is considered to be an [intraday](#intraday-sessions) session. In other cases, you can use the `F` character to specify the time for the previous day. For example: - `1700F-2200` starts at 17:00 on the previous day and ends at 22:00 on the current day. For example, a Wednesday session starts at 17:00 on Tuesday and ends at 22:00 on Wednesday. - `1900F-2350F` starts at 19:00 on the previous day and ends at 23:50 on the previous day. For example, a Monday session starts at 19:00 on Sunday and ends at 23:50 on Sunday. To specify a session that starts several days before the trading day, use `Fn`, where `n` is the number of days. Note that the number of days cannot be more than 6. For example: - `1900F3-1900` starts at 19:00 three days ago and ends at 19:00 on the current day. For example, a Monday session starts at 19:00 on Friday and ends at 19:00 on Monday. - `1900F3-2350F3` starts at 19:00 three days ago and ends at 23:50 three days ago. For example, a Friday session starts at 19:00 on Tuesday and ends at 23:50 on Tuesday. :::info To specify a session that spans midnight but is not an overnight session in the library context, use time values larger than `2400`. For example, `0930-2730`. In this case, a Monday session starts at 09:30 on Monday and ends at 03:30 on Tuesday. ::: ### Multiple sessions There may be several sessions in one trading day. In this case, you should specify all sessions, separated by commas. For example, `0930-1400,1430-1700`. The first session starts at 09:30 and ends at 14:00. The second session starts at 14:30 and ends at 17:00. ### Different sessions for different days By default, sessions take place from Monday to Friday. There are no sessions on Saturday and Sunday. You can specify a session for a certain day by adding `:n`, where `n` is a day number. Day numbers are `1` for Sunday and `7` for Saturday (`2` — Monday, `3` — Tuesday, etc.). Therefore, you can specify a Saturday/Sunday session. A session can relate to multiple days. For example, `0900-1400:23` means that the session starts at 09:00 and ends at 14:00 on Mondays and Tuesdays. - `0900-1400:2|0900-1630` on Mondays the session starts at 09:00 and ends at 14:00. On all other days the session starts at 09:00 and ends at 16:30. - `2200-2200:3456|1700F-2200:2` a Monday session starts at 17:00 on Sunday and ends at 22:00 on Monday. On all other days the session starts at 22:00 on the previous day and ends at 22:00 on the current day. - `0930-1630:34567` starts at 09:30 and ends at 16:30 on Tuesday, Wednesday, Thursday, Friday, and Saturday. ### First trading day You can specify the first trading day of the week using semicolon: - `1;0900-1630|0900-1400:2` — the first day of the week is Sunday. - `0900-1630|0900-1400:2;6` — the first day of the week is Saturday. - `0900-1630|0900-1400:2` — the first day of the week is Monday (default value). ### Forex sessions In Forex trading, sessions typically cover a full 24-hour period, five days a week, and use the time zone "Etc/UTC". For example, you can configure a Forex session as `2200-2200`. ## Note about bar timestamps The first bar timestamp coincides with the session opening time. All the following bar timestamps are calculated from the first one. For example, the session starts at 09:15, and the timestamp of the first bar is 09:15. The selected resolution is 1 hour. In this case, the second bar timestamp is 10:15, the third is 11:15, etc. If you want to display timestamps like `[09:15, 10:00, 11:00,...]`, you should set [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session) to `0900-HHMM` and [`session_display`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session_display) to `0915-HHMM`. ## Examples - `0900-1630|0900-1400:2` All weekdays except Mondays have one session that starts at 09:00 and ends at 16:30. A Monday's session starts at 09:00 and ends at 14:00. Fragment | Meaning ---------|-------- 0900‑1630|A session 0900-1630. This session will be assigned by default to all non-weekend days because it's not followed by the `:` specifier. ||Sessions separator. This character divides different sessions. 0900‑1400|A session 0900-1400. It's the session for a day #2 (see below). :|Day specifier. This character follows the session hours and is followed by the day numbers. 2|The day number for the session above (Monday). - `1715F-0300,0915-1200,1300-1630:3456|1715F3-0300F2,0915-1200,1300-1630:2` Tuesday, Wednesday, Thursday, and Friday have three sessions. The first starts at 17:15 on the previous day and ends at 03:00 on the current day, the second starts at 09:15 on the current day and ends at 12:00, and the third starts at 13:00 and ends at 16:30. Monday also has three sessions. The first starts at 17:15 on Friday and ends at 03:00 on Saturday, the second starts at 09:15 on Monday and ends at 12:00, and the third one starts at 13:00 and ends at 16:30. Fragment | Meaning ---------|-------- 1715F‑0300|A session starts at 17:15 the day before and ends at 03:00. 0915‑1200|A session starts at 09:15 and ends at 12:00 . 1300‑1630|A session starts at 13:00 and ends at 16:30. :|Day specifier. This character follows the session hours and is followed by the day numbers. 3456|The day numbers for the sessions above (Tuesday, Wednesday, Thursday, and Friday). ||Sessions separator. This character divides different sessions. 1715F3‑0300F2|A session starts at 17:15 three days ago and ends at 03:00 two days ago. 0915‑1200|A session starts at 09:15 and ends at 12:00. 1300‑1630|A session starts at 13:00 and ends at 16:30. :|Day specifier. 2|The day number for the session above (Monday). ## Session history If session time has changed in the past, you can specify the history of session changes in the [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session) property. To do this, provide a string that has the `SESSION#YYYYMMDD/SESSION` format and consists of the following elements: Element | Description | Example ---------|----------|--------- SESSION | Trading hours specified in the [required format](#session-formats). | 0930‑1700 # | A separator between the session and the day when it was rescheduled. |
YYYYMMDD | A day when the session was rescheduled. | `20181114` ∕ | A separator between the sessions. |
SESSION | Trading hours of the current session. | 1100‑1800 Note that the string should include only past sessions and the current one. You cannot specify changes that will happen in the future. :::tip If you want to specify changes for a specific day, use the [`corrections`](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologycorrections) property. ::: ### Session switch The session switch happens on the first day of the week according to the new session. For example, if the new session runs from Wednesday till Friday, Wednesday is considered the first day of the week.Otherwise, if the switch date falls midweek, the old session will stay in effect for the remainder of the current week. Consider the following cases: 1. The switch date coincides with the first day of week - Session: `09:30-17:00:3456#20240108/10:00-18:00` - Session switch date: 2024‑01‑08 (Monday) - First day of the week: Monday Since the switch date aligns with the first day of the week, the new session schedule begins on 2024‑01‑08. 2. The switch date does not coincide with the first day of week - Session: `09:30-17:00:3456#20240110/10:00-18:00` - Session switch date: 2024‑01‑10 (Wednesday) - First day of the week: Monday Since the switch day does not coincide with the first day of week, the new session schedule begins on the next Monday 2024‑01‑15. Until then, the previous session schedule (09:30-17:00) remains in effect. URL: https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF ================================================================================== # UDF ## What is UDF It's a predefined Datafeed API adapter that uses an HTTP-based UDF protocol designed to deliver data to the library in a simple and efficient way. :::tip This predefined adapter is an example implementation of the JS API. You are not required to implement your datafeed using UDF. ::: ## How to start You should create a server-side HTTP service that gets the data from your storage and responds to library requests. ## Response-as-a-table concept Think of data feed responses as tables. For example, a data feed response that includes a symbol list from the exchange may be treated as a table where each symbol represents a row, along with some columns (minimal_price_movement, description, has_intraday e.t.c.). Each column may be an array (it will provide a separate value for each row in a table). Note that there might be a situation when all rows have the same value in the same column. In this case, the column value can be defined as a single value in JSON response. Example: Let's assume that we requested a symbol list from the New York Stock Exchange. The response (in pseudo-format) might look like ```javascript { symbols: ["MSFT", "AAPL", "FB", "GOOG"], min_price_move: 0.1, description: ["Microsoft corp.", "Apple Inc", "Facebook", "Google"] } ``` Here is how this response will look like in a table format. Symbol|min_price_move|Description ---|---|--- MSFT|0.1|Microsoft corp. AAPL|0.1|Apple Inc FB|0.1|Facebook GOOG|0.1|Google ## API Calls ### Data feed configuration data Request: `GET /config` Response: The library expects to receive a JSON response of the same structure as a result of Datafeed API [onReady() call](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IExternalDatafeed#onready). Also there should be 2 additional properties: * `supports_search`: Set it to `true` if your data feed supports symbol search and individual symbol resolve logic. * `supports_group_request`: Set it to `true` if your data feed provides full information on symbol group only and is not able to perform symbol search or individual symbol resolve. Either `supports_search` or `supports_group_request` should be set to `true`. **Note:** if your data feed doesn't implement this call (doesn't respond or sends 404 error) then the default configuration is being used. Here is the default configuration: ```javascript { supported_resolutions: ['1', '5', '15', '30', '60', '1D', '1W', '1M'], supports_group_request: true, supports_marks: false, supports_search: false, supports_timescale_marks: false, } ``` ### Symbol group request Request: `GET /symbol_info?group=` * `group_name`: string Example: `GET /symbol_info?group=NYSE` Response: Response is expected to be an object with properties listed below. Each property is treated as table column, as described above (see [response-as-a-table](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDFresponse-as-a-table-concept)). The response structure is similar (but **not equal**) to [SymbolInfo](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology). Therefore, you should read the description of each field to learn about the details. * `symbol` * `description` * `exchange_listed_name` * `minmovement` * `minmovement2` * `fractional` * `pricescale` * `has-intraday` * `visible-plots-set` * `type` * `ticker` * `timezone` * `session-regular` (mapped to `SymbolInfo.session`) * `session-holidays` * `corrections` * `supported-resolutions` * `force-session-rebuild` * `has-daily` * `intraday-multipliers` * `volume_precision` * `has-weekly-and-monthly` * `has-empty-bars` Here is an example of data feed response to `GET /symbol_info?group=NYSE` request: ```javascript { symbol: ["AAPL", "MSFT", "SPX"], description: ["Apple Inc", "Microsoft corp", "S&P 500 index"], exchange_listed_name: "NYSE", minmovement: 1, minmovement2: 0, pricescale: [1, 1, 100], has-dwm: true, has-intraday: true, type: ["stock", "stock", "index"], ticker: ["AAPL~0", "MSFT~0", "$SPX500"], timezone: "America/New_York", session-regular: "0900-1600", } ``` **Notes:** 1. This call will be used if your data feed sent `supports_group_request: true` in the configuration data or didn't respond to the configuration request at all. 2. In the event that your data feed does not support the requested symbol group (which should not happen if your response to request #1 (supported groups) is correct) you may expect a 404 error. 3. When using this mode of receiving data (getting large amount of symbol data) your browser will keep the data that wasn't even requested by the user. If your symbol list has more than a few items, please consider supporting symbol search / individual symbol resolve instead. ### Symbol resolve Request: `GET /symbols?symbol=` * `symbol`: string. Symbol name or ticker. Example: `GET /symbols?symbol=AAL`, `GET /symbols?symbol=NYSE:MSFT` A JSON response of the same structure as [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo). **Note:** this call will be requested if your data feed sent `supports_group_request: false` and `supports_search: true` in the configuration data. ### Symbol search Request: `GET /search?query=&type=&exchange=&limit=` * `query`: string. Text typed by the user in the Symbol Search edit box * `type`: string. One of the symbol types [supported](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#symbols_types) by your back-end * `exchange`: string. One of the exchanges [supported](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#exchanges) by your back-end * `limit`: integer. The maximum number of symbols in a response Example: `GET /search?query=AA&type=stock&exchange=NYSE&limit=15` A response is expected to be an array of symbol objects as in [respective JS API call](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#searchsymbols) **Note:** this call will be requested if your data feed sent `supports_group_request: false` and `supports_search: true` in the configuration data. ### Bars Request: `GET /history?symbol=&from=&to=&resolution=&countback=` * `symbol`: symbol name or ticker. * `from`: unix timestamp (UTC) of leftmost required bar * `to`: unix timestamp (UTC) of rightmost required bar (not inclusive) * `resolution`: string * `countback`: number of bars (higher priority than `from`) starting with `to`. If `countback` is set, `from` should be ignored. Example: `GET /history?symbol=BEAM~0&resolution=D&from=1386493512&to=1395133512&countback=500` A response is expected to be an object with some properties listed below. Each property is treated as a table column, as described above. * `s`: status code. Expected values: `ok` | `error` | `no_data` * `errmsg`: Error message. Should be present only when `s = 'error'` * `t`: Bar time. Unix timestamp (UTC) * `c`: Closing price * `o`: Opening price (optional) * `h`: High price (optional) * `l`: Low price (optional) * `v`: Volume (optional) * `nextTime`: Time of the next bar if there is no data (status code is `no_data`) in the requested period (optional) **Notes:** 1. Bar time for daily bars should be 00:00 UTC and is expected to be a trading day (not a day when the session starts). The library aligns the time according to the [Session](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologysession) from SymbolInfo. 1. 1. Bar time for monthly bars should be 00:00 UTC and be the first trading day of the month. 1. Prices should be passed as numbers and not as strings in quotation marks. Example: ```javascript { s: "ok", t: [1386493512, 1386493572, 1386493632, 1386493692], c: [42.1, 43.4, 44.3, 42.8] } ``` ```javascript { s: "no_data", nextTime: 1386493512 } ``` ```javascript { s: "ok", t: [1386493512, 1386493572, 1386493632, 1386493692], c: [42.1, 43.4, 44.3, 42.8], o: [41.0, 42.9, 43.7, 44.5], h: [43.0, 44.1, 44.8, 44.5], l: [40.4, 42.1, 42.8, 42.3], v: [12000, 18500, 24000, 45000] } ``` 1. If it is possible, it would be better to handle `countback` parameter for performance reasons. Basically, if you handle `countback`, you don't have to worry about passing `nextTime`, because `countBack` helps to avoid empty responses for ranges with no data. #### How `nextTime` works Consider the following example. The current symbol is AAPL and the chart resolution is one minute. The library requests data in the `[2015-04-03 16:00 UTC+0, 2015-04-03 19:00 UTC+0]` range. There was no trade on 2015‑04‑03 due to a public holiday. In this case, the library expects the following response from the datafeed: ```javascript { s: "no_data", nextTime: 1428001140000 // 2 Apr 2015 18:59:00 GMT+0 } ``` `nextTime` is the time of the closest available bar in the past. ### Marks Request: `GET /marks?symbol=&from=&to=&resolution=` * `symbol`: symbol name or ticker. * `from`: unix timestamp (UTC) of leftmost visible bar * `to`: unix timestamp (UTC) of rightmost visible bar * `resolution`: string A response is expected to be an object with some properties listed below. This object is similar to [respective response](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#getmarks) in Datafeed API, but each property is treated as a table column, as described above. If the `two_character_bar_marks_labels` feature is enabled then at most the first two characters of the `label` text will be displayed. Otherwise only the first character will be displayed. ```javascript { id: [array of ids], time: [array of times], color: [array of colors], text: [array of texts], label: [array of labels], labelFontColor: [array of label font colors], minSize: [array of minSizes], } ``` **Note:** this call will be requested if your data feed sent `supports_marks: true` in the configuration data. ### Timescale marks Request: `GET /timescale_marks?symbol=&from=&to=&resolution=` * `symbol`: symbol name or ticker. * `from`: unix timestamp (UTC) or leftmost visible bar * `to`: unix timestamp (UTC) or rightmost visible bar * `resolution`: string A response is expected to be an array of objects with properties listed below. * `id`: unique identifier of a mark * `color`: rgba color * `label`: a letter to be displayed in a circle * `time`: unix time * `tooltip`: tooltip text * `shape`: optional mark shape. For possible values see the `TimeScaleMarkShape` type in the TypeScript type definitions. **Note:** this call will be requested if your data feed sent `supports_timescale_marks: true` in the configuration data. ### Server time Request: `GET /time` Response: Numeric unix time without milliseconds. Example: `1445324591` ### Quotes Request: `GET /quotes?symbols=,,...,` Example: `GET /quotes?symbols=NYSE%3AAA%2CNYSE%3AF%2CNasdaqNM%3AAAPL` A response is an object with the following keys. * `s`: Status code for the request. Expected values are: `ok` or `error` * `errmsg`: Error message. Should be present only when `s = 'error'` * `d`: symbol data array. Should conform to the [`QuoteData`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#quotedata) interface. Example: ```json { "s": "ok", "d": [ { "s": "ok", "n": "NYSE:AA", "v": { "ch": 0.16, "chp": 0.98, "short_name": "AA", "exchange": "NYSE", "description": "Alcoa Inc. Common", "lp": 16.57, "ask": 16.58, "bid": 16.57, "open_price": 16.25, "high_price": 16.60, "low_price": 16.25, "prev_close_price": 16.41, "volume": 4029041 } }, { "s": "ok", "n": "NYSE:F", "v": { "ch": 0.15, "chp": 0.89, "short_name": "F", "exchange": "NYSE", "description": "Ford Motor Company", "lp": 17.02, "ask": 17.03, "bid": 17.02, "open_price": 16.74, "high_price": 17.08, "low_price": 16.74, "prev_close_price": 16.87, "volume": 7713782 } } ] } ``` ## Constructor ```javascript Datafeeds.UDFCompatibleDatafeed = function(datafeedURL, updateFrequency, limitedServerResponse) ``` ### datafeedURL This is a URL of a data server that will receive requests and return data. ### updateFrequency This is a frequency of requests that the data feed will send to the server in milliseconds. Default is 10000 (10 sec). ### limitedServerResponse Optional parameter for configuring the datafeed for truncated server responses. Use this if your data server has a maximum response size. The object has two parameters: `maxResponseLength` and `expectedOrder`. * `maxResponseLength`: number. Set this value to the maximum number of bars which the data backend server can supply in a single response. This doesn't affect or change the library behavior regarding how many bars it will request. It just allows this Datafeed implementation to correctly handle this situation. * `expectedOrder`: Possible values: 'latestFirst' | 'earliestFirst'. If the server can't return all the required bars in a single response then `expectedOrder` specifies whether the server will send the latest (newest) or earliest (older) data first. URL: https://www.tradingview.com/charting-library-docs/latest/connecting_data ============================================================================== # Connecting Data ## Overview The library is meant to be used on your own site, with your own source of market data. It does NOT include any market data. If you want to display TradingView market data, please check our [widgets](https). Unlike simple charts, the primary aim of which is just displaying data, the library gives users control over the chart. Thus, market data connection API is designed in such a way, that all interactions (data requests, symbol information requests and symbol search) are initiated by the user. ## Datafeed API The market data connection API ([Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api)) is a set of methods that must be implemented in JavaScript. All these methods are called by the library as needed. The library expects to get an implementation of the Datafeed API in the [datafeed](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#datafeed) field of the constructor. ## UDF If you don’t have sufficient JavaScript knowledge, or if you don’t yet have a Web-based server API that you can fetch data from, then you can use a ready-made [UDF adapter](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF) that implements the [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api) and makes simple HTTP(S) requests at the specified URL in a specific format. This adapter does not support data streaming out of the box (but it still can be added there). Do not use UDF with data grouping (see [`supports_group_request`](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDFdata-feed-configuration-data)) if your backend has more than **100** symbols. Also, the UDF adapter can be used as an **example** implementation of the Datafeed API. You can copy [its code](https) 🔐 (access is [restricted](../getting_started/getting_started )) and start editing it. ## Go ahead [Start implementing Datafeed API if you have an existing Web API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api) [Start with a predefined UDF adapter and implement a server-side API](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF) URL: https://www.tradingview.com/charting-library-docs/latest/connecting_data/datafeed-api/additional-methods ============================================================================================================== # Additional methods This article describes the additional methods in the [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/connecting_data/datafeed-api). With methods, you can enable additional features such as marks and a countdown to the bar close. ## getMarks The library calls [`getMarks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#getmarks) to request [marks](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Marksmarks-on-the-chart) for the visible bar range. The library assumes that you call [`GetMarksCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#getmarkscallback) once per `getMarks` call. Pass an array of [`Mark`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Mark) objects as a callback parameter. Only ten marks can be attached to a bar. 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`. :::caution This method is called only if your datafeed [supports marks](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#supports_marks). ::: The code sample below demonstrates the example of `getMarks` implementation: ```js getMarks = (symbolInfo, startDate, endDate, onDataCallback, resolution) => { console.log('getMarks'); onDataCallback( [ { id: 1, time: endDate, color: 'red', text: ['This is the mark pop-up text.'], label: 'M', labelFontColor: 'blue', minSize: 25 }, { id: 2, time: endDate + 5260000, // 2 months color: 'red', text: ['Second marker'], label: 'S', labelFontColor: 'green', minSize: 25 } ]); }; ``` ## getTimescaleMarks The library calls [`getTimescaleMarks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#gettimescalemarks) to request [timescale marks](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Marksmarks-on-the-time-scale) for the visible bar range. The library assumes that you call [`GetMarksCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#getmarkscallback) once per `getTimescaleMarks` call. Pass an array of [`TimescaleMark`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TimescaleMark) objects as a callback parameter. :::caution These method is called only if your datafeed [supports marks](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#supports_marks). ::: The code sample below demonstrates the example of `getTimescaleMarks` implementation: ```js getTimescaleMarks = ( symbolInfo, startDate, endDate, onDataCallback, resolution ) => { // optional console.log('getTimescaleMarks'); let marks = []; if (symbolInfo.name === 'AAPL') { marks = [ { id: 1, time: startDate, color: 'red', label: 'Aa', minSize: 30, tooltip: [ 'Lorem', 'Ipsum', 'Dolor', 'Sit', ] }, { id: 2, time: startDate + 5260000, // 2 months color: 'blue', label: 'B', minSize: 30, tooltip: [ 'Amet', 'Consectetur', 'Adipiscing', 'Elit', ] } ]; } else { marks = [ { id: 'String id', time: endDate, color: 'red', label: 'T', tooltip: ['Nulla'] } ]; } onDataCallback(marks); }; ``` ## getServerTime By default, the library gets the time from the user's machine. If the machine time is incorrect, the time used in the library is also incorrect. To synchronize the library time with a server's time, enable the [`supports_time`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#supports_time) property and implement the [`getServerTime`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#getservertime) method. In the implementation, send a request to a time server and return the accurate value to the library using the [`ServerTimeCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#servertimecallback). The time value should be a Unix timestamp, for example, `1445324591`. Note that the callback should be called only once. The library allows you to display the countdown to the bar closing on the price scale. If you use this feature, consider implementing `getServerTime` to make sure that the countdown is correct. :::info To display a countdown, set the [`mainSeriesProperties.showCountdown`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesshowcountdown) property to `true`. Note that the countdown can be displayed only for [intraday](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolutionresolution-in-minutes-intraday) resolutions. ::: ## getVolumeProfileResolutionForPeriod The library calls [`getVolumeProfileResolutionForPeriod`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#getvolumeprofileresolutionforperiod) to request the resolution that is used to calculate the _Volume Profile Visible Range_ indicator. Implement this method if you want to calculate the indicator more accurately. The implementation depends on how much data you can transfer to the library and the depth of data in your datafeed. If this method is not specified, the library uses `currentResolution`. URL: https://www.tradingview.com/charting-library-docs/latest/connecting_data/datafeed-api =========================================================================================== # Datafeed API The library allows connecting market data to the chart in two ways: - By using the built-in [UDF adapter](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF). - By implementing your own datafeed via the Datafeed API. :::info Note that neither Advanced Charts nor Trading Platform contains any market data. You should use data from your own source or third-party providers. ::: This documentation section describes the Datafeed API methods and their implementation details. You can also refer to the [How to connect data via Datafeed API](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial) tutorial for a step-by-step guide. ## Overview The Datafeed API is a set of methods that you should implement in JavaScript and assign to the [`datafeed`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#datafeed) property in the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor). The library calls these methods to access and process data. In response, you should evoke the provided callbacks to pass the data to the library. The diagram below illustrates how the Datafeed API should be integrated with the library and your backend server. import ThemedImage from '@theme/ThemedImage'; import useBaseUrl from '@docusaurus/useBaseUrl'; ### Asynchronous callbacks As mentioned [above](#overview), you should evoke callbacks to pass data to the library. Note that all callbacks should be evoked **asynchronously**. In context of the JavaScript Event Loop, the callbacks can only be evoked within different MacroTask. Otherwise, the _Uncaught RangeError: Maximum call stack size exceeded_ [issue](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issuesmaximum-call-stack-size-exceeded) might occur. If you have data ready at the time of a request, you can set a delay as demonstrated below to ensure that a callback is only evoked when the library is ready. ```javascript setTimeout(() => { historyCallback(data); }, 0); ``` Note that the library can modify bar data that you provide utilizing callbacks. Pass a copy of the data to avoid potential issues. ## List of methods All Datafeed API methods are divided into three groups: - [Required methods](https://www.tradingview.com/charting-library-docs/latest/connecting_data/datafeed-api/required-methods) — a minimum set of methods that you should implement to connect data to the chart. - [Trading Platform methods](https://www.tradingview.com/charting-library-docs/latest/connecting_data/datafeed-api/trading-platform-methods) — the methods that are required to enable most of the [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal) features including the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket), [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List), and [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminaldepth-of-market). - [Additional methods](https://www.tradingview.com/charting-library-docs/latest/connecting_data/datafeed-api/additional-methods) — the methods that allow you to enable additional features such as marks on the chart and a countdown to the bar close. URL: https://www.tradingview.com/charting-library-docs/latest/connecting_data/datafeed-api/required-methods ============================================================================================================ # Required methods import ThemedImage from '@theme/ThemedImage'; import useBaseUrl from '@docusaurus/useBaseUrl'; This article describes the required methods in the [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/connecting_data/datafeed-api). The library calls these methods to initialize the chart, resolve requested symbols, and load data for them. At the end of the article, you can find [diagrams](#sequence-diagrams) illustrating the sequence in which methods are called. :::tip Refer to the [How to connect data via Datafeed API](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial) tutorial that explains how to implement the methods step-by-step . ::: ## onReady The library calls the [`onReady`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IExternalDatafeed#onready) method when the chart is initialized. This method supplies the library with the datafeed configuration data such as supported symbol types, exchanges, time intervals (resolution), currency codes and more. Call the [`OnReadyCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#onreadycallback) and pass a [`DatafeedConfiguration`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration) object as a parameter: ```javascript onReady: (callback) => { console.log('[onReady]: Method call'); setTimeout(() => callback(configurationData)); } ``` The following code sample shows the [`DatafeedConfiguration`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration) implementation: ```javascript const configurationData = { supports_search: true, supports_group_request: false, supports_marks: true, supports_timescale_marks: true, supports_time: true, exchanges: [ { value: "", name: "All Exchanges", desc: "" }, { value: "NasdaqNM", name: "NasdaqNM", desc: "NasdaqNM" }, { value: "NYSE", name: "NYSE", desc: "NYSE" } ], symbols_types: [ { name: "All types", value: "" }, { name: "Stock", value: "stock" }, { name: "Index", value: "index" } ], supported_resolutions: ["D", "2D", "3D", "W", "3W", "M", "6M"] } ``` ## searchSymbols The library calls the [`searchSymbols`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#searchsymbols) method to request symbols that match some user input. Pass the resulting array of symbols as a parameter to [`SearchSymbolsCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#searchsymbolscallback). ```javascript searchSymbols: async ( userInput, exchange, symbolType, onResultReadyCallback, ) => { console.log('[searchSymbols]: Method call'); const symbols = await getMatchingSymbolsFromBackend(userInput, exchange, symbolType); onResultReadyCallback(newSymbols); } ``` As a result, the library gets an array of [`SearchSymbolResultItem`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SearchSymbolResultItem) objects that have the following format: ```javascript [ { "symbol": "", "description": "", "exchange": "", "ticker": "", "type": "stock" // "futures"/"crypto"/"forex"/"index" }, { //... } ] ``` If no symbol is found, pass an empty array to [`SearchSymbolsCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#searchsymbolscallback). You can adjust the frequency of search requests utilizing the [`symbol_search_request_delay`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#symbol_search_request_delay) property. ## resolveSymbol The library calls the [`resolveSymbol`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#resolvesymbol) method to get [symbol information](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology) such as the exchange, time zone, trading hours, etc. Specify this information in a [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) object as demonstrated below: ```javascript const symbolInfo = { ticker: 'BTCUSD', name: 'BTCUSD', description: 'Bitcoin/USD', type: symbolItem.type, session: '24x7', timezone: 'Etc/UTC', exchange: 'Example Exchange', minmov: 1, pricescale: 100, has_intraday: false, visible_plots_set: 'ohlcv', has_weekly_and_monthly: false, supported_resolutions: ['1', '5', '30', '60', '1D', '1W'], volume_precision: 2, data_status: 'streaming', }; ``` Pass symbol information as a parameter to [`ResolveCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#resolvecallback). If the symbol cannot be resolved, call [`ErrorCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#datafeederrorcallback) and specify an error message. ```javascript resolveSymbol: async ( symbolName, onSymbolResolvedCallback, onResolveErrorCallback, extension ) => { try { const symbolInfo = await getSymbolInfoFromBackend(symbolName, extension); onSymbolResolvedCallback(symbolInfo); } catch (err) { onResolveErrorCallback(err.message); } } ``` ### Multiple symbol resolving In the [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) object, you can provide both [name](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologyname) and [ticker](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologyticker) as the symbol name. The library behaves differently based on whether these values are the same or different: - If the name and ticker are the same, the library makes a single `resolveSymbol` call. - If the name and ticker differ, the library resolves the symbol twice: once for the entered name (e.g., `KO`) and again for the resolved ticker (e.g., `NYSE:KO`). Multiple resolving happens because a single symbol name can correspond to multiple tickers. For example, AAPL might return results for NASDAQ and LSE. By resolving the ticker separately, the library ensures accurate and complete information, as the ticker is expected to be unique and is prioritized for data display. ### Display invalid symbol icon You can display the default TradingView icon when error occurs. To do this, specify the `"unknown_symbol"` error message: ```javascript onResolveErrorCallback("unknown_symbol"); ``` In this case, the chart shows the following icon and message. Ghost icon :::tip If the icon is not displayed, make sure that the [`hide_image_invalid_symbol`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetshide_image_invalid_symbol) featureset is not enabled. ::: ## getBars The library calls [`getBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#getbars) to get historical data in a certain range. To transfer the requested data, pass an array of [`Bar`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Bar) objects to [`HistoryCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#historycallback). :::info The library caches historical data. Therefore, you do not need to implement a client-side cache. ::: ### Bar order The array of [`Bar`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Bar) items should be arranged in **ascending chronological order**, meaning that the timestamps of the bars should be getting bigger for each bar in the array. For example, `[1746774000000, 1747058400000, 1747144800000, ...]`. Note that for **daily, weekly, and monthly** bars, the [`time`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Bar#time) value should represent the **beginning of the trading day** at 00:00:00 UTC, not the beginning of the session. ### Correct amount of data The library calculates the amount of data that is necessary to fill the chart space and requests it in [`getBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#getbars). You cannot change this amount. Return data to [`getBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#getbars) based on the following [`PeriodParams`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PeriodParams) properties: - [`from`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PeriodParams#from) — Unix timestamp of the leftmost requested bar. The library requires data in the `[from, to)` time range. - [`to`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PeriodParams#to) — Unix timestamp of the rightmost requested bar **(not inclusive)**. - [`countBack`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PeriodParams#countback) — the required amount of bars to load. It is more important to pass the required number of bars than to match the `[from, to)` time range for the following reasons: - The library might miscalculate the `from` value. It may happen if you provide incorrect [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session) or [`session_holidays`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session_holidays) values. In this case, the `[from, to)` range does not represent the required number of bars. - The library calculates the correct `from` value, but your backend does not contain enough bars in the `[from, to)` range. It might happen if the market was opened, but the symbol was not traded. In both cases, the library calls [`getBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#getbars) multiple times in order to get the missing data. It might cause potential issues. To avoid them, consider the following recommendations: - Return at least two bars — returning only one may cause an error when clicking on the chart. - Your response should always include **all the existing data** for the requested range. - If the number of bars in the requested range is less than the `countBack` value, you should include earlier bars until the `countBack` count is reached. For example, the chart requests 300 bars in the range `[2019-06-01T00:00:00..2020-01-01T00:00:00)`, and your backend have only 250 bars in the requested period. Return these 250 bars and 50 bars prior to `2019-06-01T00:00:00`. - In the unlikely case that the number of bars in the requested range is larger than the `countBack` value, then you should return all the bars in that range instead of truncating it to the `countBack` length. - If there is no data left (in other words the current response to return an empty array, **and** there is no older data on the server), set [`noData`](../../api/interfaces/Charting_Library.HistoryMetadata.md#nodata) to `true` to prevent further requests. The library can request more bars than are visible because some indicators require additional history, for example, Moving Average with the length `10`. :::info Previously, it was necessary to specify [`noData`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.HistoryMetadata#nodata) and [`nextTime`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.HistoryMetadata#nexttime) to load data outside the requested range. For now, you can send this data in response to the current request. However, you can still use these properties if your datafeed supports only the `from`/`to` properties and requires another request from the library. ::: The following piece of code is just a snippet to begin with. You will have to change it to fit your requirements but copying & pasting the code below should render candles on the chart for a given symbol and nothing for all other symbols. It is also to illustrate the `noData: true` result. ```javascript resolveSymbol(symbolName, onSymbolResolvedCallback, onResolveErrorCallback, extension) { setTimeout( () => { // Return some simple symbol information for the TEST symbol if (symbolName === 'TEST') { onSymbolResolvedCallback({ "name": "TEST", "timezone": "America/New_York", "minmov": 1, "minmov2": 0, "pointvalue": 1, "session": "24x7", "has_intraday": false, "visible_plots_set": "c", "description": "Test Symbol", "type": "stock", "supported_resolutions": [ "D" ], "pricescale": 100, "ticker": "TEST", "exchange": "Test Exchange", "has_daily": true, "format": "price" }); } else { // Ignore all other symbols onResolveErrorCallback('unknown_symbol'); } }, 50 ); } getBars(symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) { setTimeout( () => { // For this piece of code only we will only return bars for the TEST symbol if (symbolInfo.ticker === 'TEST' && resolution === '1D') { // We are constructing an array for `countBack` bars. const bars = new Array(periodParams.countBack); // For constructing the bars we are starting from the `to` time minus 1 day, and working backwards until we have `countBack` bars. let time = new Date(periodParams.to * 1000); time.setUTCHours(0); time.setUTCMinutes(0); time.setUTCMilliseconds(0); time.setUTCDate(time.getUTCDate() - 1); // Fake price. let price = 100; for (let i = periodParams.countBack - 1; i > -1; i--) { bars[i] = { open: price, high: price, low: price, close: price, time: time.getTime(), } // Working out a random value for changing the fake price. const volatility = 0.1; const x = Math.random() - 0.5; const changePercent = 2 * volatility * x; const changeAmount = price * changePercent; price = price + changeAmount; // Note that this simple "-1 day" logic only works because the TEST symbol has a 24x7 session. // For a more complex session we would need to, for example, skip weekends. time.setUTCDate(time.getUTCDate() - 1); } // Once all the bars (usually countBack is around 300 bars) the array of candles is returned to the library. onHistoryCallback(bars); } else { // If no result, return an empty array and specify it to the library by changing the value of `noData` to true. onHistoryCallback([], { noData: true }); } }, 50 ); } } ``` ## subscribeBars The library calls [`subscribeBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#subscribebars) to receive real-time updates for a symbol. Call [`SubscribeBarsCallback`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#subscribebarscallback) every time you want to update the most recent bar or add a new one. For example, if the chart has loaded data up to 14:00, you can only update the last bar (14:00) or add a newer bar (15:00). :::danger You cannot update a historical bar using this method. Otherwise, you get the _putToCacheNewBar: time violation_ [issue](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issuestime-violation). If you need to change historical data, you should call [`resetCache`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#resetcache) and then `chart.resetData()` to redraw the chart. ::: If you return a bar that has the same [`time`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Bar#time) value as the most recent bar, the library replaces the most recent bar with the new one. Consider the following example. The most recent bar (in pseudo-code) is `{time: 1419411578413, open: 10, high: 12, low: 9, close: 11}`. You call `onRealtimeCallback({time: 1419411578413, open: 10, high: 14, low: 9, close: 14})`. As the bar with the time `1419411578413` already exists, and it is the most recent one, the library **replaces the entire bar** making the most recent bar `{time: 1419411578413, open: 10, high: 14, low: 9, close: 14}`. Refer to the [tutorial](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial/Streaming-Implementationstep-1-connect-to-streaming) to see the example of [`subscribeBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#subscribebars) implementation. ### Multiple subscriptions The library provides a unique subscriber ID as a parameter when it calls `subscribeBars` and [`unsubscribeBars`](#unsubscribebars). This subscriber ID allows you to track and manage subscriptions for symbol updates. The library can have multiple subscriptions at the same time, for example, when a user switches to another symbol or resolution. You should handle `subscribeBars` and `unsubscribeBars` calls for different resolutions and symbols as independent events. Note that the library can call these methods in any order and with a delay. When you receive an update from the server, you should send the data via the specific callback for the subscriber which has the correct symbol name and [resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution). :::danger If you send a subscriber data that does not match the subscriber's symbol and resolution, the _putToCacheNewBar: time violation_ [issue](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issuestime-violation) can occur. ::: Note that you should provide updates to all the subscriptions until the library unsubscribes from them. Therefore, you may require multiple connections to your backend server if you have multiple subscriptions. Consider the following example. The current symbol is `AAPL`, and the resolution is `1D` (one day). You switch the resolution to `5` (five minutes). The library separately calls `subscribeBars` to subscribe for five-minute updates and `unsubscribeBars` to unsubscribe from one-day updates (after a short delay). During this period, the library has at least two active subscribers: for five-minute and one-day updates. You should send five-minute updates to the five-minute subscriber and continue to send one-day updates to the one-day subscriber until the library unsubscribes from the `1D` resolution. Assume that the last bar (in pseudo-code) is: - `{time: 1684368000000, open: 10, high: 12, low: 9, close: 11}` on the one-day chart - `{time: 1684422300000, open: 10.5, high: 11.5, low: 10, close: 11}` on the five-minute chart If the price jumps to `13`, you should send the following bars to the subscribers: - `{time: 1684368000000, open: 10, high: 13, low: 9, close: 13}` to the one-day subscriber - `{time: 1684422300000, open: 10.5, high: 13, low: 10, close: 13}` to the five-minute subscriber ## unsubscribeBars The library calls [`unsubscribeBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#unsubscribebars) to stop receiving updates for the symbol when the user selects another symbol on the chart. The `listenerGuid` argument contains the same object that was passed to [`subscribeBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#subscribebars) before. Refer to the [tutorial](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial/Streaming-Implementationstep-1-connect-to-streaming) to see the example of [`unsubscribeBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#unsubscribebars) implementation. ## Sequence diagrams In this section, you can find diagrams illustrating the sequence of Datafeed API method calls. Expand the sections below to view the diagrams for the following cases:

A user opens a chart for the first time.
A user switches to a new symbol or adds a new one to the chart.
URL: https://www.tradingview.com/charting-library-docs/latest/connecting_data/datafeed-api/trading-platform-methods ==================================================================================================================== # Trading Platform methods [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal) is a standalone client-side solution that provides trading capabilities. To use Trading Platform, in addition to the [required](https://www.tradingview.com/charting-library-docs/latest/connecting_data/datafeed-api/required-methods) Datafeed API methods, you should implement the quote-related methods, including [`getQuotes`](#getquotes), [`subscribeQuotes`](#subscribequotes), and [`unsubscribeQuotes`](#unsubscribequotes). The library calls these methods to request [quotes](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/quotes), which are data sets that show the most recent bid and ask prices, opening and closing prices, price changes, and other market data. Quotes are used in most Trading Platform features including the following: - [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) - [Legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend) - [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) - [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminaldetails) - [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news) - [Depth of Market (DOM)](https://www.tradingview.com/charting-library-docs/latest/trading_terminaldepth-of-market) For [DOM](https://www.tradingview.com/charting-library-docs/latest/trading_terminaldepth-of-market), you should also implement the [`subscribeDepth`](#subscribedepth) and [`unsubscribeDepth`](#unsubscribedepth) methods. :::tip For Trading Platform, along with implementing the Datafeed API methods, you also need to implement the Broker API. For more information, refer to [Core trading concepts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts), or jump into the [step-by-step tutorial](https://www.tradingview.com/charting-library-docs/latest/api/implement-broker-api) to start implementing the Broker API. ::: ## getQuotes Trading Platform calls [`getQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#getquotes) to request quote data that is used to display the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List), [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminaldetails), [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket), [DOM](https://www.tradingview.com/charting-library-docs/latest/trading_terminaldepth-of-market) widgets, and the [Legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend). To transfer the requested data, pass an array of [QuoteData](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#quotedata) objects as a parameter to [QuotesCallback](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#quotescallback). The library expects to receive necessary data in a single callback. :::caution Note that if you integrate the library with [mobile applications](https://www.tradingview.com/charting-library-docs/latest/mobile_specifics), `getQuotes` is required to avoid [NaN values](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legendnan-values-in-legend) appearing in the legend. ::: The example of [QuoteData](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#quotedata) is demonstrated below: ```json { { "s": "ok", "n": "NasdaqNM:AAPL", "v": { "ch": 0, "chp": 0, "short_name": "AAPL", "exchange": "", "original_name": "NasdaqNM:AAPL", "description": "NasdaqNM:AAPL", "lp": 173.68, "ask": 173.68, "bid": 173.68, "open_price": 173.68, "high_price": 173.68, "low_price": 173.68, "prev_close_price": 172.77, "volume": 173.68 } } } ``` Note that **Percentage change** value, **Ask/Bid buttons** and **lines** also require quote data. They are **not displayed** on the chart if [`getQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#getquotes) is not implemented. ![Datafeed API buttons](https://www.tradingview.com/charting-library-docs/img/datafeed_api_buttons.png) The following piece of code is just a snippet to begin with. You will have to change it to fit your requirements but copying & pasting the code below should enable displaying values in the Legend when on mobile along with values for `ask` and `bid` buttons (if activated within the Chart settings) when using Trading Platform. [`subscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#subscribequotes) will however update the values on regular basis. ```javascript // In this example we are returning random values (which probably don't make any sense from a trading purpose) // but it is just to illustrate how to structure the function and returned object. getQuotes(symbols, onDataCallback, onErrorCallback) { const data = []; symbols.forEach((symbol)=>{ data.push({ n: symbol, s: 'ok', v: { ch: Math.random() * (5 - 1) + 1, chp: Math.random() * (5 - 1) + 1, lp: Math.random() * (10 - 1) + 1, ask: Math.random() * (10 - 1) + 1, bid: Math.random() * (10 - 1) + 1, spread: 0.20, open_price: Math.random() * (5 - 1) + 1, high_price: Math.random() * (5 - 1) + 1, low_price: Math.random() * (5 - 1) + 1, prev_close_price: Math.random() * (5 - 1) + 1, original_name: symbol, volume: Math.random() * (5 - 1) + 1, }, }); }); // To ensure the callback is only evoked when the library is ready - see Asynchronous callbacks setTimeout(() => onDataCallback(data), 0); } ``` ## subscribeQuotes The library calls [`subscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#subscribequotes) to receive real-time quote updates for certain symbols. Call [QuotesCallback](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#quotescallback) every time you want to update the quotes and pass an array of [QuoteData](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#quotedata) objects as a parameter. The following piece of code is just a snippet to begin with. You will have to change it to fit your requirements but copying & pasting the code below should render different values in the Legend when on mobile along with values for `ask` and `bid` buttons (if activated within the Chart settings). [`unsubscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#unsubscribequotes) will however update the values on regular basis. ```javascript subscribeQuotes(symbols, fastSymbols, onRealtimeCallback, listenerGUID) { // In this example, `_quotesSubscriptions` is a global variable used to clear the subscription in `unsubscribeQuotes` this._quotesSubscriptions[listenerGUID] = setInterval(() => this.getQuotes(symbols.concat(fastSymbols), onRealtimeCallback, () => undefined), 5000); } ``` ## unsubscribeQuotes The library calls [`unsubscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#unsubscribequotes) to stop receiving updates for the symbol when the user removes it from the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) or selects another symbol on the chart. The `listenerGuid` argument contains the same object that was passed to [`subscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#subscribequotes) before. The following piece of code is just a snippet to begin with. You will have to change it to fit your requirements but copying & pasting the code below should stop updating the values created by [`subscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#subscribequotes). ```javascript unsubscribeQuotes(listenerGUID) { clearInterval(this._quotesSubscriptions[listenerGUID]); } ``` ## subscribeDepth The library calls [`subscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#subscribedepth) to receive real-time [Level 2](https) (DOM) data for a symbol. Call [DOMCallback](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#domcallback) every time you want to update the quotes and pass a [DOMData](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DOMData) object as a parameter. Note that you should specify the [broker_config](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#broker_config) property in the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions) and set [supportLevel2Data](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportlevel2data) to `true`. Otherwise, the library does not call the [`subscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#subscribedepth)/[`unsubscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#unsubscribedepth) methods. This method should return a unique identifier (`subscriberUID`) that is used to unsubscribe from updates. ## unsubscribeDepth The library calls [`unsubscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#unsubscribedepth) to stop receiving DOM data updates. The `subscriberUID` argument contains the same object that was returned by [`subscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#subscribedepth). URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Localization ========================================================================================= # Localization ## Set up language To set up a default language, specify the [`locale`] property in the [Widget Constructor]. Check out the [Widget Constructor tutorial][tutorial-locale] on YouTube for an implementation example. ## Supported languages The languages that the library supports are listed below. | Language | `locale` value | |-|:-:| | Arabic | `ar` | | Catalan (Spain) | `ca_ES` | | Chinese (Taiwan) | `zh_TW` | | Chinese | `zh` | | English | `en` | | French | `fr` | | German (Germany) | `de` | | Hebrew (Israel) | `he_IL` | | Indonesian (Indonesia) | `id_ID` | | Italian | `it` | | Japanese | `ja` | | Korean | `ko` | | Malay (Malaysia) | `ms_MY` | | Polish | `pl` | | Portuguese | `pt` | | Russian | `ru` | | Spanish | `es` | | Swedish | `sv` | | Thai (Thailand) | `th` | | Turkish | `tr` | | Vietnamese | `vi` | [//]: # (Persian "fa", Czech "cs", Dutch "nl_NL", Greek "el", Hungarian "hu_HU", and Romanian "ro" are no longer supported) ## Multiple languages To support several languages, you need to create a custom [Widget Constructor] for each of them and recreate the widget every time users switch the language. ## Unsupported locale If an unsupported locale is specified in the [Widget Constructor], the chart falls back to English with a console warning *locale isn't supported*. ## Custom translations If you want to provide custom translations for UI strings, use the [`custom_translate_function`] property of the [Widget Constructor]. ## Right-to-left alignment The library supports right-to-left (RTL) alignment for RTL languages such as Arabic and Hebrew. Note that the alignment affects only toolbars, dialogs, and other UI elements except the chart. [`custom_translate_function`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_translate_function [`locale`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#locale [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor [tutorial-locale]: https://www.youtube.com/watch?v=bdvmM3FNnSY&t=1353s URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution ======================================================================================= # Resolution **Resolution** or time interval is a time period of a single bar. The library supports resolutions in seconds, minutes, hours, days, weeks, months, years, and ticks. ## Resolution format A resolution value should have the [`ResolutionString`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#resolutionstring) type. The table below describes how to specify different resolution values. In these values, `x` represents a number of units. Resolution | Format | Example ---------|----------|--------- Ticks | `xT` | `1T` — one tick, `5T` — five ticks, `100T` — one hundred ticks Seconds | `xS` | `1S` — one second, `2S` — two seconds, `100S` — one hundred seconds Minutes | `x` | `1` — one minute, `2` — two minutes, `100` — one hundred minutes Hours | `x` minutes | `60` — one hour, `120` — two hours, `240` — four hours Days | `xD` | `1D` — one day, `2D` — two days, `100D` — one hundred days Weeks | `xW` | `1W` — one week, `2W` — two weeks, `100W` — one hundred weeks Months | `xM` | `1M` — one month, `2M` — two months, `100M` — one hundred months Years | `xM` months | `12M` — one year, `24M` — two years, `48M` — four years You can also omit the number of units if it is equal to `1`. For example, you can use `D` instead of `1D` and `W` instead of `1W`. ## Set up resolution on the chart The resolution is [initialized](#default-resolution) in the Widget Constructor and can be changed [in the UI](#in-ui) or [using the API](#using-api). To get the current resolution, use the [`resolution`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#resolution) method. ```javascript widget.onChartReady(() => { widget.activeChart().resolution(); }); ``` ### Default resolution You can specify the default resolution using the [`interval`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#interval) property in the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor). ```javascript new TradingView.widget({ // ... interval: '1D', }); ``` ### In UI Users can change the resolution in the following ways: - Use the _Resolution_ button on the top toolbar. Change resolution via top toolbar - Use the _Resolution_ button in the [_Legend_]. Change resolution in Legend - Press any digit key or the , (comma) key. Change resolution using shortcuts To disable any of the methods above, refer to [Disable resolution changing](#disable-resolution-changing). ### Using API You can use the [`setResolution`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#setresolution) method to change the resolution on the fly. ```javascript widget.onChartReady(() => { widget.activeChart().setResolution('2M'); }); ``` :::caution In the UI, users can enter values like `2h` to specify a number of hours. However, you should specify hour resolutions in minutes, for example `120`, if you change the resolution using the API. ::: ## Configure resolutions in datafeed You should configure resolutions in your [datafeed](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api) to display data correctly. To do this, follow the steps below: 1. Specify resolutions that the chart and a certain symbol support. 2. Enable specific resolutions that you use, for example, a resolution in seconds or days. 3. Implement the corresponding method in the datafeed. ### 1. Specify supported resolutions To enable any resolution, specify the following properties: - [`DatafeedConfiguration.supported_resolutions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#supported_resolutions) contains all resolutions that the chart should support. - [`LibrarySymbolInfo.supported_resolutions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#supported_resolutions) contains all resolutions that a certain symbol should support. The resolutions should be listed in a specific [format](#resolution-format). For example, `["1", "15", "240", "D", "6M"]` stands for 1 minute, 15 minutes, 4 hours, 1 day, and 6 months. If the certain symbol does not support some chart resolutions, they are disabled for this symbol in the UI. ![Supported resolutions](https://www.tradingview.com/charting-library-docs/img/symbology_supported_resolutions.png) If a user switches to another symbol, that does not support the selected resolution, the library changes the resolution to the first available one for this symbol. #### Additional resolutions The library can combine smaller intervals into larger ones to build new resolutions. For instance, it can build 2-minute bars from 1-minute bars. Therefore, you can enable resolutions that your datafeed does not explicitly provide. To do this, add these resolutions to the `supported_resolutions` arrays mentioned [above](#1-specify-supported-resolutions). If you want to [disable resolution rebuilding](#disable-resolution-rebuilding), use the [`disable_resolution_rebuild`] featureset. :::caution The library **cannot** build the following resolutions: - daily, weekly, or monthly resolutions using intraday data - resolutions higher than seconds using tick data ::: ### 2. Enable required resolutions Follow the instructions below to enable the required resolutions. #### Resolution in seconds To enable resolution in seconds, additionally configure the following properties: - Enable the [`seconds_resolution`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsseconds_resolution) featureset. To do this, include `seconds_resolution` to the [`enabled_features`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#enabled_features) array. - Set [`has_seconds`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_seconds) to `true`. - Specify [`seconds_multipliers`] that contains the resolutions provided by the datafeed. Additionally, if your datafeed supports tick data for a symbol, you can tell the library to build seconds bars from ticks. To do this, set [`build_seconds_from_ticks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#build_seconds_from_ticks) to `true`. Note that this feature is available in Trading Platform only. #### Resolution in minutes (intraday) To enable intraday resolution (in minutes), additionally configure the following properties: - Set [`has_intraday`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_intraday) to `true`. - Specify [`intraday_multipliers`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#intraday_multipliers) that contains the resolutions that the datafeed provides. #### Resolution in days To enable resolution in days, additionally configure the following properties: - Set [`has_daily`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_daily) to `true`. - Specify [`daily_multipliers`] that contains the resolutions that the datafeed provides. #### Resolution in weeks / months To enable resolution in weeks or months, additionally configure the following properties: - Set [`has_weekly_and_monthly`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_weekly_and_monthly) to `true`. - Specify [`weekly_multipliers`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#weekly_multipliers) or [`monthly_multipliers`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#monthly_multipliers) that contains the resolutions that the datafeed provides. #### Resolution in ticks To enable resolution in ticks, additionally configure the following properties: - Enable the [`tick_resolution`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetstick_resolution) featureset. To do this, include `tick_resolution` to the [`enabled_features`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#enabled_features) array. - Set [`has_ticks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_ticks) to `true`. Additionally, you can tell the library to build seconds bars from ticks. To do this, set [`build_seconds_from_ticks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#build_seconds_from_ticks) to `true`. Note that this feature is available in Trading Platform only. ### 3. Implement method in datafeed The library requests data from the datafeed based on the current resolution selected on the chart. All resolutions that your datafeed explicitly supports should be listed in the `*_multipliers` properties ([`seconds_multipliers`], [`daily_multipliers`], etc.) and implemented in the [`getBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#getbars) method. ### Example Consider the following example. The datafeed has 1-minute and 2-minute bars. Also, you would like to support a 5-minute resolution. In this case, you should configure the [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) properties as follows: ```js //... "has_intraday": true, "supported_resolutions": ["1", "2", "5"], "intraday_multipliers": ["1", "2"], // The library can request 1-minute and 2-minute bars, and will build 5-minute bars from 1-minute data //... ``` The example of the `getBars` implementation is demonstrated below: ```js getBars(symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) { if (resolution === '1') { const bars = getBarsFor1MinuteResolution(periodParams); onHistoryCallback(bars); ​ return; } ​ if (resolution === '2') { const bars = getBarsFor2MinuteResolution(periodParams); onHistoryCallback(bars); ​ return; } //... } function getBarsFor1MinuteResolution(periodParams) { // Your custom logic } function getBarsFor2MinuteResolution(periodParams) { // Your custom logic } ``` ## Additional settings You can use [featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) to adjust resolution settings. ### Disable resolution rebuilding The library aligns bars to the nearest expected bar position. For example, if [`session`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session) is `0915-1530` and the chart shows a 5-minute resolution, the library expects the following bar timestamps: `[09:15, 09:20, 09:25, ...]`. If your datafeed provides a bar with the `09:17` timestamp, the library changes this timestamp to `09:15`. You can use the [`disable_resolution_rebuild`] featureset to display bars exactly as your datafeed provides. :::info If you enable the `disable_resolution_rebuild` featureset, the library cannot build resolutions that your datafeed does not explicitly provide. For example, the library cannot build a 5-minute resolution from 1-minute data. ::: ### Enable custom resolutions You can use the [`custom_resolutions`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetscustom_resolutions) featureset to allow users to add custom resolutions. Note that if a user adds a resolution that the symbol does not support, this resolution will be disabled in the UI. Add custom resolution ### Disable resolution changing You can use the [`header_resolutions`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsheader_resolutions) featureset to remove the _Resolution_ button from the top toolbar. ![Remove resolution button](https://www.tradingview.com/charting-library-docs/img/no-resolution-button.png) To disable resolution changing in the [_Legend_], use the [`legend_inplace_edit`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetslegend_inplace_edit) featureset. If you want to completely remove the _Resolution_ button from the _Legend_, use the [`hide_resolution_in_legend`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetshide_resolution_in_legend) featureset. ![Remove resolution from Legend](https://www.tradingview.com/charting-library-docs/img/no-resolution-legend.png) To disable the _Resolution_ shortcut, use the [`show_interval_dialog_on_key_press`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsshow_interval_dialog_on_key_press) featureset. [`seconds_multipliers`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#seconds_multipliers [`daily_multipliers`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#daily_multipliers [_Legend_]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend [`disable_resolution_rebuild`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#disable_resolution_rebuild URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== # Widget Constructor The Widget Constructor is the entry point to the library. It allows you to embed the library within your web page. You can use the Widget Constructor parameters to customize the widget's appearance and behavior. All parameters are listed in the [`ChartingLibraryWidgetOptions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions) interface. If you use [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal), you can specify some [additional parameters](#trading-platform-parameters). The following video tutorial describes Widget Constructor parameters and demonstrates how to use them. import YouTubeVideo from '@site/src/components/youtube-embed'; import JsFiddle from '@site/src/components/jsfiddle-embed';
The code sample below shows how to adjust some basic parameters using Widget Constructor. ## Advanced Charts parameters The following parameters relate to Advanced Charts and Trading Platform. ### Widget configuration Use the parameters below to configure basic widget settings: import AnchoredTable from '@site/src/components/anchored-table'; import widgetConfig from './_widget_constructor_tables/widget-configuration.json'; ### Chart configuration Use the parameters below to configure basic chart settings: import chartConfig from './_widget_constructor_tables/chart-configuration.json'; ### Data configuration Use the parameters below to [connect data](https://www.tradingview.com/charting-library-docs/latest/connecting_data) to the chart: import dataConfig from './_widget_constructor_tables/data-configuration.json'; ### Chart size Use the parameters below to customize the chart size: import chartSize from './_widget_constructor_tables/chart-size.json'; ### UI customization Use the parameters below to customize colors, fonts, price and date formats, and more: import uiCustomization from './_widget_constructor_tables/ui-customization.json'; ### Chart features If you want to change the chart's behavior or show/hide UI elements, you should use [featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets). The following parameters allow you to enable/disable a certain featureset: import chartFeatures from './_widget_constructor_tables/chart-features.json'; ### Indicators and drawings Use the parameters below to customize [indicators](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators) (studies) and [drawings](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings): import indicatorDrawings from './_widget_constructor_tables/indicators-and-drawings.json'; ### Symbol search and comparison Use the parameters below to customize the [*Symbol Search*](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search): import symbolSearch from './_widget_constructor_tables/symbol-search-and-comparison.json'; ### Saving and loading chart Specify the following parameters to save/load a chart using the [predefined REST API](https://www.tradingview.com/charting-library-docs/latest/api/save-load-rest-api): import saveLoadRest from './_widget_constructor_tables/saving-loading-chart-rest.json'; Specify the following parameters to save/load a chart using the [low-level API](https://www.tradingview.com/charting-library-docs/latest/saving_loading/low-level-api): import saveLoadApi from './_widget_constructor_tables/saving-loading-chart-api.json'; Specify the [`save_load_adapter`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#save_load_adapter) property to save/load a chart using the [API handlers](https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapter). Specify the [`settings_adapter`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#settings_adapter) property to save [user settings] and set a watermark. ## Trading Platform parameters All Trading Platform parameters are listed in the [`TradingTerminalWidgetOptions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions) interface. Most of them duplicate the [Advanced Charts](#advanced-charts-parameters) parameters. Additional parameters are listed below: import tradingPlatform from './_widget_constructor_tables/trading-platform.json'; [user settings]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "symbol", "cells": [ "symbol", "The default chart symbol." ] }, { "anchorName": "interval", "cells": [ "interval", "The default chart interval." ] }, { "anchorName": "timeframe", "cells": [ "timeframe", "The default chart time frame." ] }, { "anchorName": "time_frames", "cells": [ "time_frames", "The list of visible time frames that can be selected at the bottom of the chart." ] }, { "anchorName": "timezone", "cells": [ "timezone", "The default chart time zone." ] }, { "anchorName": "locale", "cells": [ "locale", "The default chart locale." ] }, { "anchorName": "favorites", "cells": [ "favorites", "Items that should be marked as favorite by default." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "enabled_features", "cells": [ "enabled_features", "The array containing names of features that should be enabled by default." ] }, { "anchorName": "disabled_features", "cells": [ "disabled_features", "The array containing names of features that should be disabled by default." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "width", "cells": [ "width", "The desired width of the widget." ] }, { "anchorName": "height", "cells": [ "height", "The desired height of the widget." ] }, { "anchorName": "fullscreen", "cells": [ "fullscreen", "A Boolean value showing whether the chart should use all the available space in the window." ] }, { "anchorName": "autosize", "cells": [ "autosize", "A Boolean value showing whether the chart should use all the available space in the container and resize when the container itself is resized." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "datafeed", "cells": [ "datafeed", "A JavaScript object that implements the IBasicDataFeed interface to supply the chart with data." ] }, { "anchorName": "additional_symbol_info_fields", "cells": [ "additional_symbol_info_fields", "An optional field containing an array of custom symbol info fields to be shown in the Security Info dialog." ] }, { "anchorName": "snapshot_url", "cells": [ "snapshot_url", "A URL that is used to send a POST request with binary chart snapshots when a user presses the snapshot button." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "study_count_limit", "cells": [ "study_count_limit", "Maximum amount of studies allowed at one time within the layout." ] }, { "anchorName": "studies_access", "cells": [ "studies_access", "An object that allows you to specify indicators available for users." ] }, { "anchorName": "studies_overrides", "cells": [ "studies_overrides", "Use this option to customize the style or inputs of the indicators. Refer to Indicator Overrides for more information." ] }, { "anchorName": "custom_indicators_getter", "cells": [ "custom_indicators_getter", "A function that returns the Promise object with the array of your custom indicators." ] }, { "anchorName": "drawings_access", "cells": [ "drawings_access", "An object that allows you to specify drawing tools available for users." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "auto_save_delay", "cells": [ "auto_save_delay", "A threshold delay in seconds that is used to reduce the number of onAutoSaveNeeded calls." ] }, { "anchorName": "saved_data", "cells": [ "saved_data", "An object containing saved chart content." ] }, { "anchorName": "saved_data_meta_info", "cells": [ "saved_data_meta_info", "An object containing saved chart content meta info." ] }, { "anchorName": "load_last_chart", "cells": [ "load_last_chart", "A Boolean value showing whether the library should load the last saved chart for a user." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "charts_storage_url", "cells": [ "charts_storage_url", "A storage URL endpoint." ] }, { "anchorName": "charts_storage_api_version", "cells": [ "charts_storage_api_version", "A version of your backend. Supported values are: 1.0 or 1.1." ] }, { "anchorName": "client_id", "cells": [ "client_id", "A client ID that represents a user group." ] }, { "anchorName": "user_id", "cells": [ "user_id", "A user ID that uniquely identifies each user within a client_id group." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "symbol_search_request_delay", "cells": [ "symbol_search_request_delay", "A threshold delay in milliseconds that is used to reduce the number of search requests when the user enters the symbol name in the Symbol Search." ] }, { "anchorName": "symbol_search_complete", "cells": [ "symbol_search_complete", "Takes an additional search result object parameter, and returns an additional human-friendly symbol name." ] }, { "anchorName": "compare_symbols", "cells": [ "compare_symbols", "An array of custom compare symbols for the Compare window." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "broker_config", "cells": [ "broker_config", "Configuration flags for Trading Platform. Refer to Trading features configuration for more information." ] }, { "anchorName": "debug_broker", "cells": [ "debug_broker", "Makes the library write detailed Broker API and Trading Host logs into the browser console. Refer to How to enable debug mode for more information." ] }, { "anchorName": "restConfig", "cells": [ "restConfig", "Connection configuration settings for the Broker API." ] }, { "anchorName": "widgetbar", "cells": [ "widgetbar", "Settings for the widget panel on the right side of the chart. You can enable Watchlist, News, Details and Data Window widgets on the right side of the chart using this property." ] }, { "anchorName": "rss_news_feed", "cells": [ "rss_news_feed", "Use this property to change the RSS feed for news." ] }, { "anchorName": "rss_news_title", "cells": [ "rss_news_title", "Use this property to change the title for news widget when using a RSS feed." ] }, { "anchorName": "news_provider", "cells": [ "news_provider", "Use this property to set your own news getter function." ] }, { "anchorName": "trading_customization", "cells": [ "trading_customization", "Overrides order and position lines created using the createOrderLine and createPositionLine methods." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "toolbar_bg", "cells": [ "toolbar_bg", "A background color of the toolbars." ] }, { "anchorName": "theme", "cells": [ "theme", "The predefined custom theme color for the chart." ] }, { "anchorName": "custom_themes", "cells": [ "custom_themes", "The custom color palette." ] }, { "anchorName": "custom_css_url", "cells": [ "custom_css_url", "Adds your custom CSS to the chart." ] }, { "anchorName": "custom_font_family", "cells": [ "custom_font_family", "Changes the font family used on the chart." ] }, { "anchorName": "custom_formatters", "cells": [ "custom_formatters", "Custom formatters for adjusting the display format of price, date, and time values." ] }, { "anchorName": "custom_translate_function", "cells": [ "custom_translate_function", "Use this property to set custom translations for UI elements." ] }, { "anchorName": "numeric_formatting", "cells": [ "numeric_formatting", "An object that contains formatting options for numbers." ] }, { "anchorName": "overrides", "cells": [ "overrides", "Overrides values for the default widget properties." ] }, { "anchorName": "settings_overrides", "cells": [ "settings_overrides", "An object that contains new values for values saved to the settings." ] }, { "anchorName": "loading_screen", "cells": [ "loading_screen", "An object that allows you to customize the loading spinner." ] }, { "anchorName": "context_menu", "cells": [ "context_menu", "A property that allows you to customize the context menu." ] }, { "anchorName": "time_scale", "cells": [ "time_scale", "An additional optional field to add more bars on screen." ] }, { "anchorName": "header_widget_buttons_mode", "cells": [ "header_widget_buttons_mode", "An additional optional field to change the look and feel of buttons on the top toolbar." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor =============================================================================================== [ { "anchorName": "container", "cells": [ "container", "Represents either a reference to an attribute of a DOM element inside which the iframe with the chart will be placed or the HTMLElement itself." ] }, { "anchorName": "library_path", "cells": [ "library_path", "A path to a static folder." ] }, { "anchorName": "debug", "cells": [ "debug", "Makes the library write detailed Datafeed API logs into the browser console. Refer to How to enable debug mode for more information." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methods =========================================================================================== # Widget methods ## Overview After you create a widget with [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor), you can control the `widget` object using the methods defined in the `IChartingLibraryWidget` interface. This article describes the most commonly used methods. Refer to the [`IChartingLibraryWidget`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget) page to see the full list of methods. ## Advanced Charts methods ### onChartReady The [`onChartReady`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#onchartready) method calls a callback when all data is loaded and the widget is ready. Therefore, you should call other widget methods only after the `onChartReady` callback. ```javascript const widget = new TradingView.widget(/* Widget properties */); widget.onChartReady(function() { widget.getChartLanguage(); }); ``` ### chart The [`chart`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#chart) method returns an instance of the [`IChartWidgetApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi) interface that provides an extensive API for controlling the specific chart. For example, you can handle chart events, create indicators and drawings, change chart properties on the fly, and more. Consider the code sample below that adds the Bollinger Bands [indicator](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators) at the launch. ```javascript widget.onChartReady(() => { const chart = widget.chart(); chart.createStudy( "Bollinger Bands", // Indicator's name true, // forceOverlay false, // lock { in_0: 25, // length in_1: 1, // 'mult' indicator setting } ); }); ``` The `chart` method has an optional `index` parameter. If you want to interact with a certain chart on the multiple-chart layout, you should call the `chart` method with the corresponding index as a parameter. ### activeChart The [`activeChart`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#activechart) method retrieves [`IChartWidgetApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi) to interact with the currently selected chart. For example, the code sample below draws a vertical line on the chart. ```javascript widget.activeChart().createMultipointShape( [{ price: 168, time: Date.UTC(2017, 10, 13) / 1000 }], { shape: 'vertical_line'} ); ``` You can also subscribe to events on the active chart, such as [`onIntervalChanged`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#onintervalchanged). ```javascript widget.activeChart().onIntervalChanged().subscribe(null, (interval, timeframeObj) => timeframeObj.timeframe = { value: "12M", type: "period-back" }); ``` Note that the library does not manage the event subscriptions when users switch between the charts on the [multiple-chart layout](https://www.tradingview.com/charting-library-docs/latest/trading_terminalmultiple-chart-layout). If necessary, you should manually unsubscribe from the previous chart and subscribe to the newly selected one using the corresponding [methods](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISubscription). To track the currently active chart, use the [`activeChartChanged`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap#activechartchanged) event. You can also find out the active chart's index using the [`activeChartIndex`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#activechartindex) method and subscribe to this chart using the [`chart`](#chart) method. ```javascript const index = widget.activeChartIndex(); const chart = widget.chart(index); ``` ### subscribe / unsubscribe The [`subscribe`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#subscribe) method allows you to subscribe to the widget's [events](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap) and handle them. For example, the code sample below handles an event when an indicator is added to the chart and prints the indicator's name to the console. ```javascript widget.subscribe('study', (event) => { console.log(`A ${event.value} indicator was added`) }); ``` You should use the [`unsubscribe`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#unsubscribe) method to unsubscribe from events. ### applyOverrides The [`applyOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#applyoverrides) method allows you to change [Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides) on the fly. The code sample below hides the main [series](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryseries). ```js widget.applyOverrides({ "mainSeriesProperties.visible": false }); ``` ### applyStudiesOverrides The [`applyStudiesOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#applystudiesoverrides) method allows you to change [Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides) that affect [indicators](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators) (studies) on the fly. The code sample below changes the color of the Bollinger Bands indicator. ```js widget.applyStudiesOverrides({ 'bollinger bands.median.color': '#33FF88' }); ``` Note that this method only changes the indicator's properties before the indicator is created. You should use the [`applyOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IStudyApi#applyoverrides) method in [`IStudyApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IStudyApi) to change an indicator that is already on the chart. ### setSymbol The [`setSymbol`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#setsymbol) method sets a symbol and resolution of the active chart. ```javascript widget.setSymbol('IBM', '1D', () => { // Your callback function }); ``` Note that a callback is evoked when the data for the new symbol is loaded. ### changeTheme The [`changeTheme`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#changetheme) method allows you to change the [theme](https://www.tradingview.com/charting-library-docs/latest/customization/theme) on the fly. This method returns a promise that is resolved once the theme is applied. You can apply other style modifications after the promise is fulfilled. ```javascript widget.changeTheme('Dark').then(() => { widget.chart().applyOverrides({ 'paneProperties.backgroundGradientStartColor': 'red' }); }); ``` ### onShortcut The [`onShortcut`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#onshortcut) method allows you to override the built‑in [shortcuts](https://www.tradingview.com/charting-library-docs/latest/getting_started/Shortcuts) or specify custom ones. For example, the code sample below specifies a shortcut that opens [_Symbol Search_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search). ```javascript widget.onShortcut("alt+q", function() { widget.chart().executeActionById("symbolSearch"); }); ``` Refer to the [Manage shortcuts](https://www.tradingview.com/charting-library-docs/latest/getting_started/Shortcutsmanage-shortcuts) section for more examples. ### takeClientScreenshot The [`takeClientScreenshot`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#takeclientscreenshot) method creates a snapshot of the chart and returns it as a canvas. You can then take the canvas element and create an image from it. The code sample below saves a screenshot as PNG. ```javascript async function saveChartToPNG() { const screenshotCanvas = await widget.takeClientScreenshot(); const linkElement = document.createElement('a'); linkElement.download = 'screenshot'; linkElement.href = screenshotCanvas.toDataURL(); // Alternatively, use `toBlob` which is a better API linkElement.dataset.downloadurl = ['image/png', linkElement.download, linkElement.href].join(':'); document.body.appendChild(linkElement); linkElement.click(); document.body.removeChild(linkElement); } saveChartToPNG(); // Call the screenshot function ``` ### customThemes The [`customThemes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#customthemes) method retrieves [`ICustomThemesApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ICustomThemesApi) that allows you to manage [custom themes](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes). For example, you can reset the applied themes to the default values. ```javascript let customThemesAPI = (await widget.customThemes()); customThemesAPI.resetCustomThemes(); ``` ### closePopupsAndDialogs The [`closePopupsAndDialogs`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#closepopupsanddialogs) method closes any active dialog or [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) on the chart. ```js widget.closePopupsAndDialogs(); ``` ## Trading Platform methods The methods below are available in [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal) only. ### widgetbar The [`widgetbar`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#widgetbar) method retrieves [`IWidgetbarApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWidgetbarApi) that allows you to interact with the widget bar. ```javascript widget.onChartReady(() => { widget.widgetbar().then(widgetbarApi => { widgetbarApi.isPageVisible('data_window'); }); }); ``` ### watchList The [`watchList`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#watchlist) method retrieves [`IWatchListApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatchListApi) that allows you to interact with the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) widget. ```javascript const watchlistApi = await widget.watchList(); const activeListId = watchlistApi.getActiveListId(); const currentListItems = watchlistApi.getList(activeListId); // Adds a new section and item to the current Watchlist watchlistApi.updateList(activeListId, [...currentListItems, '###NEW SECTION', 'AMZN']); ``` ### news The [`news`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#news) method retrieves [`INewsApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.INewsApi) that allows you to interact with the [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news) widget. ```javascript widget.onChartReady(() => { widget.news().then(newsApi => { // newsApi is ready to use }); }); ``` ### chartsCount The [`chartsCount`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#chartscount) method counts a number of charts on the multiple-chart layout. In the code sample below, this method is used to interact with all the charts on the layout one by one. ```javascript for (let i = 0; i < widget.chartsCount(); i++) { console.log(widget.chart(i).symbolExt().name) } ``` URL: https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examples ===================================================================================================== # Custom Studies Examples ## Requesting Data for Another Ticker 1. Come up with a new ticker name to display your data and set up your server to return valid SymbolInfo for this new ticker. 1. Also, set up the server to return valid historical data for this ticker. 1. Add [custom_indicators_getter](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_indicators_getter) key to the widget constructor. Its value is a function that returns a Promise object with a list of custom indicators. 1. *(Optional)* Update your widget's initialization code to [create](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createstudy) this indicator when the chart is ready. import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; ```javascript custom_indicators_getter: function(PineJS) { return Promise.resolve([ { name: 'Equity', metainfo: { _metainfoVersion: 51, id: 'Equity@tv-basicstudies-1', description: 'Equity', shortDescription: 'Equity', is_price_study: true, isCustomIndicator: true, format: { type: 'price', // Precision is set to one digit, e.g. 777.7 precision: 1, }, plots: [{id: 'plot_0', type: 'line'}], defaults: { styles: { plot_0: { linestyle: 0, visible: true, // Make the line thinner linewidth: 1, // Plot type is Line plottype: 2, // Show price line trackPrice: true, // Set the plotted line color to dark red color: '#880000' } }, inputs: {} }, styles: { plot_0: { // Output name will be displayed in the Style window title: 'Equity value', histogramBase: 0, } }, inputs: [], }, constructor: function() { this.init = function(context, inputCallback) { this._context = context; this._input = inputCallback; // Define the symbol to be plotted. // Symbol should be a string. // You can use PineJS.Std.ticker(this._context) to get the selected symbol's ticker. // For example, // var symbol = 'AAPL'; // var symbol = '#EQUITY'; // var symbol = PineJS.Std.ticker(this._context) + '#TEST'; const symbol = '#EQUITY'; // #EQUITY should be replaced with the symbol you want to resolve this._context.new_sym(symbol, PineJS.Std.period(this._context)); }; this.main = function(context, inputCallback) { this._context = context; this._input = inputCallback; // Select the main symbol this._context.select_sym(0); const mainSymbolTime = this._context.new_var(this._context.symbol.time); // Select the secondary symbol this._context.select_sym(1); const secondarySymbolTime = this._context.new_var(this._context.symbol.time); // Align the times of the secondary symbol to the main symbol const secondarySymbolClose = this._context.new_var(PineJS.Std.close(this._context)); const alignedClose = secondarySymbolClose.adopt(secondarySymbolTime, mainSymbolTime, 1); // Select the main symbol again this._context.select_sym(0); return [alignedClose]; } } } ]); }, ``` ```typescript /* Within the Widget constructor options */ custom_indicators_getter: PineJS => { return Promise.resolve([ /* Requesting data for another ticker */ { name: 'Equity', metainfo: { _metainfoVersion: 51, id: 'Equity@tv-basicstudies-1' as RawStudyMetaInfoId, description: 'Equity', shortDescription: 'Equity', is_price_study: true, isCustomIndicator: true, format: { type: 'price', // Precision is set to one digit, e.g. 777.7 precision: 1, }, plots: [{ id: 'plot_0', type: StudyPlotType.Line }], defaults: { styles: { plot_0: { linestyle: 0, visible: true, // Make the line thinner linewidth: 1, // Plot type is Line plottype: 2 as StudyLinePlotPreferences['plottype'], // Show price line trackPrice: true, // Set the plotted line color to dark red color: '#880000', }, }, inputs: {}, }, styles: { plot_0: { // Output name will be displayed in the Style window title: 'Equity value', histogramBase: 0, }, }, inputs: [], }, constructor: function ( this: LibraryPineStudy ) { this.init = function (context, inputCallback) { this._context = context; this._input = inputCallback; const symbol = '#EQUITY'; // #EQUITY should be replaced with the symbol you want to resolve this._context.new_sym( symbol, PineJS.Std.period(this._context) ); }; this.main = function (context, inputCallback) { this._context = context; this._input = inputCallback; // Select the main symbol this._context.select_sym(0); const mainSymbolTime = this._context.new_var(this._context.symbol.time); // Select the secondary symbol ("#EQUITY") this._context.select_sym(1); const secondarySymbolTime = this._context.new_var(this._context.symbol.time); // Align the times of the secondary symbol to the main symbol const secondarySymbolClose = this._context.new_var(PineJS.Std.close(this._context)); const alignedClose = secondarySymbolClose.adopt(secondarySymbolTime, mainSymbolTime, 1); // Select the main symbol again this._context.select_sym(0); return [alignedClose]; }; }, }, ]); }, ``` ## Coloring Bars ![/img/bar_colorer.png](https://www.tradingview.com/charting-library-docs/img/bar_colorer.png) ```javascript custom_indicators_getter: function (PineJS) { return Promise.resolve([ { name: 'Bar Colorer Demo', metainfo: { _metainfoVersion: 51, id: "BarColoring@tv-basicstudies-1", name: "BarColoring", description: "Bar Colorer Demo", shortDescription: "Bar Coloring", isCustomIndicator: true, is_price_study: true, format: { type: 'price', precision: 4, }, defaults: { palettes: { palette_0: { // palette colors // change it to the default colors that you prefer, // but note that the user can change them in the Style tab // of indicator properties colors: [ { color: '#FFFF00' }, { color: '#0000FF' } ] } } }, inputs: [], plots: [{ id: 'plot_0', // plot type should be set to 'bar_colorer' type: 'bar_colorer', // this is the name of the palette that is defined // in 'palettes' and 'defaults.palettes' sections palette: 'palette_0' }], palettes: { palette_0: { colors: [ { name: 'Color 0' }, { name: 'Color 1' } ], // the mapping between the values that // are returned by the script and palette colors valToIndex: { 100: 0, 200: 1 } } } }, constructor: function() { this.main = function(context, input) { this._context = context; this._input = input; var valueForColor0 = 100; var valueForColor1 = 200; // perform your calculations here and return one of the constants // that is specified as a key in 'valToIndex' mapping var result = Math.random() * 100 % 2 > 1 ? // we randomly select one of the color values valueForColor0 : valueForColor1; return [result]; } } } ]); }, ``` ```typescript /* Within the Widget constructor options */ custom_indicators_getter: PineJS => { return Promise.resolve([ /* Coloring bars */ { name: 'Bar Colorer Demo', metainfo: { _metainfoVersion: 51, id: 'BarColoring@tv-basicstudies-1' as RawStudyMetaInfoId, name: 'BarColoring', description: 'Bar Colorer Demo', shortDescription: 'BarColoring', isCustomIndicator: true, is_price_study: true, format: { type: 'price', precision: 4, }, defaults: { palettes: { palette_0: { // palette colors // change it to the default colors that you prefer, // but note that the user can change them in the Style tab // of indicator properties colors: [{ color: '#FFFF00' }, { color: '#0000FF' }], }, }, }, inputs: [], plots: [ { id: 'plot_0', // plot type should be set to 'bar_colorer' type: StudyPlotType.BarColorer, // this is the name of the palette that is defined // in 'palettes' and 'defaults.palettes' sections palette: 'palette_0', }, ], palettes: { palette_0: { colors: [{ name: 'Color 0' }, { name: 'Color 1' }], // the mapping between the values that // are returned by the script and palette colors valToIndex: { 100: 0, 200: 1, }, }, }, }, constructor: function ( this: LibraryPineStudy ) { this.main = function (context, input) { this._context = context; this._input = input; const valueForColor0 = 100; const valueForColor1 = 200; // perform your calculations here and return one of the constants // that is specified as a key in 'valToIndex' mapping const result = (Math.random() * 100) % 2 > 1 // we randomly select one of the color values ? valueForColor0 : valueForColor1; return [result]; }; }, }, ]); }, ``` ## Custom Styles for Every Point ![/img/custom_styles_for_every_point.png](https://www.tradingview.com/charting-library-docs/img/custom_styles_for_every_point.png) ```javascript custom_indicators_getter: function(PineJS) { return Promise.resolve([ { name: 'Custom Styles For Every Point', metainfo: { _metainfoVersion: 51, id: 'CustomStylesForEveryPoint@tv-basicstudies-1', description: 'Custom Styles For Every Point', shortDescription: 'Custom Styles For Every Point', is_price_study: false, isCustomIndicator: true, plots: [ { 'id': 'plot_0', 'type': 'line', }, { 'id': 'plot_1', 'type': 'colorer', 'target': 'plot_0', 'palette': 'paletteId1', }, ], palettes: { paletteId1: { colors: { 0: { name: 'First color', }, 1: { name: 'Second color', }, }, }, }, defaults: { palettes: { paletteId1: { colors: { 0: { color: 'red', width: 1, style: 0, }, 1: { color: 'blue', width: 3, style: 1, }, }, }, }, styles: {}, precision: 4, inputs: {}, }, styles: { plot_0: { title: 'Equity value', histogramBase: 0, }, }, inputs: [], format: { type: 'price', precision: 4, }, }, constructor: function() { this.main = function(context, inputCallback) { this._context = context; this._input = inputCallback; const value = Math.random() * 200; const colorIndex = value > 100 ? 0 : 1; return [value, colorIndex]; } } } ]); }, ``` ```typescript /* Within the Widget constructor options */ custom_indicators_getter: PineJS => { return Promise.resolve([ /* Custom styles for every point */ { name: 'Custom Styles For Every Point', metainfo: { _metainfoVersion: 51, id: 'CustomStylesForEveryPoint@tv-basicstudies-1' as RawStudyMetaInfoId, description: 'Custom Styles For Every Point', shortDescription: 'Custom Styles For Every Point', is_price_study: false, isCustomIndicator: true, plots: [ { id: 'plot_0', type: StudyPlotType.Line, }, { id: 'plot_1', type: StudyPlotType.Colorer, target: 'plot_0', palette: 'paletteId1', }, ], palettes: { paletteId1: { colors: { 0: { name: 'First color', }, 1: { name: 'Second color', }, }, }, }, defaults: { palettes: { paletteId1: { colors: { 0: { color: 'red', width: 1, style: 0, }, 1: { color: 'blue', width: 3, style: 1, }, }, }, }, styles: {}, precision: 4, inputs: {}, }, styles: { plot_0: { title: 'Equity value', histogramBase: 0, }, }, inputs: [], format: { type: 'price', precision: 4, }, }, constructor: function ( this: LibraryPineStudy ) { this.main = function (context, inputCallback) { this._context = context; this._input = inputCallback; const value = Math.random() * 200; const colorIndex = value > 100 ? 0 : 1; return [value, colorIndex]; }; }, }, ]); }, ``` ## Complex Filled Areas ## Advanced Shapes Use ![/img/advanced_shapes_use.png](https://www.tradingview.com/charting-library-docs/img/advanced_shapes_use.png) ```javascript custom_indicators_getter: function(PineJS) { return Promise.resolve([ { name: 'Mondays', metainfo: { _metainfoVersion: 51, defaults: { styles: { plot_0: { color: '#FF5252', textColor: '#2196F3', plottype: 'shape_circle', location: 'Bottom', visible: true } }, inputs: {} }, plots: [ { id: 'plot_0', type: 'shapes' } ], styles: { plot_0: { isHidden: false, location: 'Bottom', text: 'Monday', title: 'Shapes' } }, description: 'Mondays', shortDescription: 'Mondays', is_price_study: true, inputs: [], id: 'Mondays@tv-basicstudies-1', format: { type: 'inherit', }, }, constructor: function() { this.main = function(context, inputCallback) { // If we don't have a time, then we cannot determine the day of week if (isNaN(context.symbol.time)) { return [NaN] } // Check if the day of the week is Monday const dayofweek = PineJS.Std.dayofweek(context); const shouldBeShapeVisible = dayofweek === 2; // 1 is plot value, it'll be displayed in legend of the indicator // NaN means that there is no value for that plot and shape should be hidden for that bar const plotValue = shouldBeShapeVisible ? 1 : NaN; return [plotValue]; } } }, ]); }, ``` ```typescript /* Within the Widget constructor options */ custom_indicators_getter: PineJS => { return Promise.resolve([ /* Advanced Shapes use */ { name: 'Mondays', metainfo: { _metainfoVersion: 51, defaults: { styles: { plot_0: { color: '#FF5252', textColor: '#2196F3', plottype: 'shape_circle' as StudyShapesPlotPreferences['plottype'], location: 'Bottom' as StudyShapesPlotPreferences['location'], visible: true } }, inputs: {}, }, plots: [ { id: 'plot_0', type: StudyPlotType.Shapes, }, ], styles: { plot_0: { isHidden: false, location: 'Bottom' as StudyShapesPlotPreferences['location'], plottype: 'shape_circle' as StudyShapesPlotPreferences['plottype'], text: 'Monday', title: 'Shapes', }, }, description: 'Mondays', shortDescription: 'Mondays', is_price_study: true, inputs: [], id: 'Mondays@tv-basicstudies-1' as RawStudyMetaInfoId, format: { type: 'inherit', }, }, constructor: function ( this: LibraryPineStudy ) { this.main = function (context, inputCallback) { // If we don't have a time, then we cannot determine the day of week if (isNaN(context.symbol.time)) { return [NaN] } // Check if the day of the week is Monday const dayofweek = PineJS.Std.dayofweek(context); const shouldBeShapeVisible = dayofweek === 2; // 1 is plot value, it'll be displayed in legend of the indicator // NaN means that there is no value for that plot and shape should be hidden for that bar const plotValue = shouldBeShapeVisible ? 1 : NaN; return [plotValue]; }; }, }, ]); }, ``` ## Advanced Colouring Candles ![/img/colouring_candles.png](https://www.tradingview.com/charting-library-docs/img/colouring_candles.png) ```javascript custom_indicators_getter: function(PineJS) { return Promise.resolve([ { name: 'Advanced Coloring Candles', metainfo: { _metainfoVersion: 51, id: 'advancedcolouringcandles@tv-basicstudies-1', name: 'Advanced Coloring Candles', description: 'Advanced Coloring Candles', shortDescription: 'Advanced Coloring Candles', isCustomIndicator: true, is_price_study: false, // whether the study should appear on the main series pane. linkedToSeries: true, // whether the study price scale should be the same as the main series one. format: { type: 'price', precision: 2, }, plots: [ { id: 'plot_open', type: 'ohlc_open', target: 'plot_candle', }, { id: 'plot_high', type: 'ohlc_high', target: 'plot_candle', }, { id: 'plot_low', type: 'ohlc_low', target: 'plot_candle', }, { id: 'plot_close', type: 'ohlc_close', target: 'plot_candle', }, { id: 'plot_bar_color', type: 'ohlc_colorer', palette: 'palette_bar', target: 'plot_candle', }, { id: 'plot_wick_color', type: 'wick_colorer', palette: 'palette_wick', target: 'plot_candle', }, { id: 'plot_border_color', type: 'border_colorer', palette: 'palette_border', target: 'plot_candle', }, ], palettes: { palette_bar: { colors: [{ name: 'Colour One' }, { name: 'Colour Two' }], valToIndex: { 0: 0, 1: 1, }, }, palette_wick: { colors: [{ name: 'Colour One' }, { name: 'Colour Two' }], valToIndex: { 0: 0, 1: 1, }, }, palette_border: { colors: [{ name: 'Colour One' }, { name: 'Colour Two' }], valToIndex: { 0: 0, 1: 1, }, }, }, ohlcPlots: { plot_candle: { title: 'Candles', }, }, defaults: { ohlcPlots: { plot_candle: { borderColor: '#000000', color: '#000000', drawBorder: true, drawWick: true, plottype: 'ohlc_candles', visible: true, wickColor: '#000000', }, }, palettes: { palette_bar: { colors: [ { color: '#1948CC', width: 1, style: 0 }, { color: '#F47D02', width: 1, style: 0 }, ], }, palette_wick: { colors: [ { color: '#0C3299', }, { color: '#E65000', }, ], }, palette_border: { colors: [ { color: '#5B9CF6', }, { color: '#FFB74D', }, ], }, }, precision: 2, inputs: {}, }, styles: {}, inputs: [], }, constructor: function () { this.main = function (context, inputCallback) { this._context = context; this._input = inputCallback; this._context.select_sym(0); const o = PineJS.Std.open(this._context); const h = PineJS.Std.high(this._context); const l = PineJS.Std.low(this._context); const c = PineJS.Std.close(this._context); // Color is determined randomly const colour = Math.round(Math.random()); return [o, h, l, c, colour /*bar*/, colour /*wick*/, colour /*border*/]; }; }, }, ]); }, ``` ```typescript /* Within the Widget constructor options */ custom_indicators_getter: PineJS => { return Promise.resolve([ /* Advanced Colouring Candles */ { name: 'Advanced Coloring Candles', metainfo: { _metainfoVersion: 51, id: 'advancedcolouringcandles@tv-basicstudies-1' as RawStudyMetaInfoId, name: 'Advanced Coloring Candles', description: 'Advanced Coloring Candles', shortDescription: 'Advanced Coloring Candles', isCustomIndicator: true, is_price_study: false, // whether the study should appear on the main series pane. linkedToSeries: true, // whether the study price scale should be the same as the main series one. format: { type: 'price', precision: 2, }, plots: [ { id: 'plot_open', type: StudyPlotType.OhlcOpen, target: 'plot_candle', }, { id: 'plot_high', type: StudyPlotType.OhlcHigh, target: 'plot_candle', }, { id: 'plot_low', type: StudyPlotType.OhlcLow, target: 'plot_candle', }, { id: 'plot_close', type: StudyPlotType.OhlcClose, target: 'plot_candle', }, { id: 'plot_bar_color', type: StudyPlotType.OhlcColorer, palette: 'palette_bar', target: 'plot_candle', }, { id: 'plot_wick_color', type: StudyPlotType.CandleWickColorer, palette: 'palette_wick', target: 'plot_candle', }, { id: 'plot_border_color', type: StudyPlotType.CandleBorderColorer, palette: 'palette_border', target: 'plot_candle', }, ], palettes: { palette_bar: { colors: [{ name: 'Colour One' }, { name: 'Colour Two' }], valToIndex: { 0: 0, 1: 1, }, }, palette_wick: { colors: [{ name: 'Colour One' }, { name: 'Colour Two' }], valToIndex: { 0: 0, 1: 1, }, }, palette_border: { colors: [{ name: 'Colour One' }, { name: 'Colour Two' }], valToIndex: { 0: 0, 1: 1, }, }, }, ohlcPlots: { plot_candle: { title: 'Candles', }, }, defaults: { ohlcPlots: { plot_candle: { borderColor: '#000000', color: '#000000', drawBorder: true, drawWick: true, plottype: OhlcStudyPlotStyle.OhlcCandles, visible: true, wickColor: '#000000', }, }, palettes: { palette_bar: { colors: [ { color: '#1948CC', width: 1, style: 0 }, { color: '#F47D02', width: 1, style: 0 }, ], }, palette_wick: { colors: [{ color: '#0C3299' }, { color: '#E65000' }], }, palette_border: { colors: [{ color: '#5B9CF6' }, { color: '#FFB74D' }], }, }, precision: 2, inputs: {}, }, styles: {}, inputs: [], }, constructor: function ( this: LibraryPineStudy ) { this.main = function (context, inputCallback) { this._context = context; this._input = inputCallback; this._context.select_sym(0); const o = PineJS.Std.open(this._context); const h = PineJS.Std.high(this._context); const l = PineJS.Std.low(this._context); const c = PineJS.Std.close(this._context); // Color is determined randomly const colour = Math.round(Math.random()); return [ o, h, l, c, colour /*bar*/, colour /*wick*/, colour /*border*/, ]; }; }, }, ]); }, ``` URL: https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-OHLC-Plots ======================================================================================================= # Custom Studies OHLC Plots OHLC plots can be used to create custom OHLC study with candle or bars type. Firstly, we should add new OHLC plot to the [metainfo](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo), using `ohlcPlots` field: ```javascript ohlcPlots: { plotcandle_0: { title: 'Plot candle title', }, }, ``` `ohlcPlots` is an object, where keys are `plot id` and values are `plots info`. `Plot info` is an object with following fields: `* - Required` * `title`* - string, title of plot that will be used in settings dialog * `isHidden`* - boolean * `drawBorder` - boolean * `showLast` - number Now we need to declare `default` values for this plot (styles etc) in `metainfo`. Depending on the plot type you want to use there might be different schemas of the `default` object. Example: ```javascript // ... defaults: { ohlcPlots: { plotcandle_0: { plottype: 'ohlc_candles', borderColor: '#000000', color: '#2196F3', drawBorder: true, drawWick: true, visible: true, wickColor: '#737375', }, }, }, // ... ``` OHLC plots are 'meta' plots, this means that under the hood there should be a set of simple plots in metainfo `plots` field. Example: ```javascript plots: [ { id: 'plot_0', type: 'ohlc_open', target: 'plotcandle_0', }, { id: 'plot_1', type: 'ohlc_high', target: 'plotcandle_0', }, { id: 'plot_2', type: 'ohlc_low', target: 'plotcandle_0', }, { id: 'plot_3', type: 'ohlc_close', target: 'plotcandle_0', }, ], ``` The main things here are `type` and `target` fields. * `type` field must be one of the following: `ohlc_open`, `ohlc_high`, `ohlc_low` or `ohlc_close`, all four plots for every OHLC plot must be declared here. * `target` - allows you to declare for which OHLC plot this 'simple' plot is. Here you should set an id of the OHLC plot (`plotcandle_0`). Last but not least you have to return data for plots from your study's `main` function in [constructor](https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom-indicator-constructor): ```javascript this.main = function(context, inputCallback) { this._context = context; this._input = inputCallback; var direction = Math.sign(Math.random() - 0.5); var value = Math.random() * 200; var open = value + 8 * direction; var high = value + 15; var low = value - 15; var close = value - 8 * direction; return [open, high, low, close]; } ``` Full example: ```javascript { name: 'OHLC_sample', metainfo: { _metainfoVersion: 51, id: 'OHLC_sample@tv-basicstudies-1', scriptIdPart: '', description: 'OHLC_sample', shortDescription: 'OHLC_sample', is_hidden_study: false, is_price_study: false, isCustomIndicator: true, plots: [ { id: 'plot_0', type: 'ohlc_open', target: 'plotcandle_0', }, { id: 'plot_1', type: 'ohlc_high', target: 'plotcandle_0', }, { id: 'plot_2', type: 'ohlc_low', target: 'plotcandle_0', }, { id: 'plot_3', type: 'ohlc_close', target: 'plotcandle_0', }, ], ohlcPlots: { plotcandle_0: { title: 'Plot candle title', }, }, defaults: { ohlcPlots: { plotcandle_0: { borderColor: '#000000', color: '#2196F3', drawBorder: true, drawWick: true, plottype: 'ohlc_candles', // might be 'ohlc_bars' for bars visible: true, wickColor: '#737375', }, }, precision: 4, inputs: {}, }, styles: {}, inputs: [], }, constructor: function() { this.main = function(context, inputCallback) { this._context = context; this._input = inputCallback; var direction = Math.sign(Math.random() - 0.5); var value = Math.random() * 200; var open = value + 8 * direction; var high = value + 15; var low = value - 15; var close = value - 8 * direction; return [open, high, low, close]; } } } ``` URL: https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Plots ================================================================================================== # Custom Studies Plots When adding a Custom Study to Widget Constructor, you have the possibility to customize the style of each plot. The `plots` field is located in [metainfo](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo) and contains an array with plots info. Plot info is an object, it contains required fields `id` and `type`. Also it can contain other fields depending on the type of a plot. Example: ```javascript ... plots: [ { id: 'plot_0', type: 'line' }, { id: 'plot_1', palette: 'palette_0', target: 'plot_0', type: 'colorer' }, { id: 'plot_2', type: 'line' }, ], ``` ## Arrows * `type`- 'arrows' * `visible`- boolean * `colorup`- string * `colordown`- string ## Chars * `type`- 'chars' * `visible`- boolean * `char`- string * `location`- string, one of the following: * `AboveBar` * `BelowBar` * `Top` * `Bottom` * `Right` * `Left` * `Absolute` * `AbsoluteUp` * `AbsoluteDown` * `color`- string * `textColor`- string ## Colorer * `type`- 'colorer' * `palette`- string * `target`- string ## DataOffset * `type`- 'dataoffset' * `target`- string ## Line * `type`- 'line' * `visible`- boolean * `plottype`- number, one of the following: * `0`- line * `1`- histogram * `3`- cross * `4`- area * `5`- columns * `6`- circles * `7`- line with breaks * `8`- area with breaks * `9`- step line * `color`- string * `linestyle`- number * `linewidth`- number * `trackPrice`- boolean ## Ohlc * `type`- string, can be either `ohlc_open`, `ohlc_high`, `ohlc_low`, or `ohlc_close` * `target`- string * `plottype`- string, can be `ohlc_bars` or `ohlc_candles` * `visible`- boolean * `color`- string If `plottype: 'ohlc_candles'`, additional fields should be provided: * `drawWick`- boolean * `drawBorder`- boolean * `wickColor`- string * `borderColor`- string ## Shapes * `type`- 'shapes' * `visible`- boolean * `plottype`- string, can have following values: * `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` * `location`- string, one of the following: * `AboveBar` * `BelowBar` * `Top` * `Bottom` * `Right` * `Left` * `Absolute` * `AbsoluteUp` * `AbsoluteDown` * `color`- string * `textColor`- string ## BarColorer * `type`- 'bar_colorer' * `palette`- string ## BgColorer * `type`- 'bg_colorer' * `palette`- string ## TextColorer * `type`- 'text_colorer' * `palette`- string * `target`- string ## OhlcColorer * `type`- 'ohlc_colorer' * `palette`- string * `target`- string URL: https://www.tradingview.com/charting-library-docs/latest/custom_studies/PineJS-Utility-Functions ====================================================================================================== # PineJS Utility Functions Custom Study [Constructor](https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom-indicator-constructor) is able to use utility functions from PineJS object (an argument of [custom_indicators_getter](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_indicators_getter) function). ## Functions ported from Pine ### `na(x)` Test value if it's a NaN. **Returns** `true` if `x` is not a valid number (`x` is NaN), otherwise `false`. ### `nz(x, y)` Replaces NaN values with zeros (or given value) in a series. **Returns** `x` if it's a valid (not NaN) number, otherwise y ### `and(expr1, expr2)` Logical AND. Applicable to boolean expressions. **Returns** Boolean value, or series of boolean values. ### `or(expr1, expr2)` Logical OR. Applicable to boolean expressions. **Returns** Boolean value, or series of boolean values. ### `not(expr)` Logical negation (NOT). Applicable to boolean expressions. **Returns** Boolean value, or series of boolean values. ### `max(x1, x2, ..., x10)` **Returns** The greatest of multiple values ### `min(x1, x2, ..., x10)` **Returns** The smallest of multiple given values. ### `pow(base, exponent)` Mathematical power function. **Returns** `x` raised to the power of `y`. If `x` is a series, it is calculated elementwise. **Arguments** - **`base` (series[float])** Specify the base to use. - **`exponent` (float)** Specifies the exponent. ### `abs(x)` Absolute value of `x` is `x` if `x >= 0`, or `-x` otherwise. **Returns** The absolute value of x ### `log(x)` Natural logarithm of any `x > 0` is the unique `y` such that `e^y = x` **Returns** The natural logarithm of x. ### `log10(x)` Base 10 logarithm of any `x > 0` is the unique `y` such that `10^y = x` **Returns** The base 10 logarithm of x. ### `sqrt(x)` Square root of any `x >= 0` is the unique `y >= 0` such that `y^2 = x` **Returns** The square root of x. ### `sign(x)` Sign (signum) of `x` is zero if the `x` is zero, `1.0` if the `x` is greater than zero, `-1.0` if the `x` is less than zero. **Returns** The sign of the argument. ### `exp(x)` The exp function of `x` is `e^x`, where `x` is the argument and `e` is Euler's number. **Returns** A number representing e^x. ### `sin(x)` The `sin` function returns the trigonometric sine of an angle. **Returns** The trigonometric sine of an angle. **Arguments** - **`x` (series[float])** Angle, in radians. ### `cos(x)` The cos function returns the trigonometric cosine of an angle. **Returns** The trigonometric cosine of an angle. **Arguments** - **`x` (series[float])** Angle, in radians. ### `tan(x)` The tan function returns the trigonometric tangent of an angle. **Returns** The trigonometric tangent of an angle. **Arguments** - **`x` (series[float])** Angle, in radians. ### `asin(x)` The asin function returns the arcsine (in radians) of number such that `sin(asin(y)) = y` for `y` in range `[-1, 1]`. **Returns** The arcsine of a value; the returned angle is in the range `[-Pi/2, Pi/2]`, or na if y is outside of range `[-1, 1]`. ### `acos(x)` The acos function returns the arccosine (in radians) of number such that `cos(acos(y)) = y` for `y` in range `[-1, 1]`. **Returns** The arc cosine of a value; the returned angle is in the range `[0, Pi]`, or `na` if `y` is outside of range `[-1, 1]`. ### `atan(x)` The atan function returns the arctangent (in radians) of number such that `tan(atan(y)) = y` for any `y`. **Returns** The arc tangent of a value; the returned angle is in the range `[-Pi/2, Pi/2]`. ### `floor(x)` **Returns** The largest integer less than or equal to the given number. ### `ceil(x)` The ceil function returns the smallest (closest to negative infinity) integer that is greater than or equal to the argument. **Returns** The smallest integer greater than or equal to the given number. ### `round(x)` **Returns** The value of `x` rounded to the nearest integer, with ties rounding up. If the precision parameter is used, returns a float value rounded to that number of decimal places. ### `avg(x1, x2, ..., x10)` Calculates average of all given series (elementwise). **Returns** Average. ### `open(context)` Current open price. **Arguments** - **`context`** PineJS execution context. ### `high(context)` Current high price. **Arguments** - **`context`** PineJS execution context. ### `low(context)` Current low price. **Arguments** - **`context`** PineJS execution context. ### `close(context)` Close price of the current bar when it has closed, or last traded price of a yet incomplete, realtime bar. **Arguments** - **`context`** PineJS execution context. ### `hl2(context)` Is a shortcut for `(high + low)/2` **Arguments** - **`context`** PineJS execution context. ### `hlc3(context)` Is a shortcut for (high + low + close)/3 **Arguments** - **`context`** PineJS execution context. ### `ohlc4(context)` Is a shortcut for (open + high + low + close)/4 **Arguments** - **`context`** PineJS execution context. ### `volume(context)` Current bar volume. **Arguments** - **`context`** PineJS execution context. ### `period(context)` Resolution string, e.g. `60` - 60 minutes, `D` - daily, `W` - weekly, `M` - monthly, `5D` - 5 days, `12M` - one year, `3M` - one quarter **Arguments** - **`context`** PineJS execution context. ### `tickerid(context)` **Arguments** - **`context`** PineJS execution context. ### `year(context)` Current bar year in exchange timezone. **Arguments** - **`context`** PineJS execution context. ### `month(context)` Current bar month in exchange timezone. **Arguments** - **`context`** PineJS execution context. ### `weekofyear(context)` Week number of current bar time in exchange timezone. **Arguments** - **`context`** PineJS execution context. ### `dayofmonth(context)` Date of current bar time in exchange timezone. **Arguments** - **`context`** PineJS execution context. ### `dayofweek(context)` Day of week for current bar time in exchange timezone. **Arguments** - **`context`** PineJS execution context. ### `hour(context)` Current bar hour in exchange timezone. **Arguments** - **`context`** PineJS execution context. ### `minute(context)` Current bar minute in exchange timezone. **Arguments** - **`context`** PineJS execution context. ### `second(context)` Current bar second in exchange timezone. **Arguments** - **`context`** PineJS execution context. ### `iff(condition, then, _else)` If ... then ... else ... **Remarks** `iff` does exactly the same thing as ternary conditional operator `?:` but in a functional style. Also iff is slightly less efficient than operator `?:` ### `rising(series, length)` Test if the `series` is now rising for `length` bars long. **Returns** `true` if current `x` is greater than any previous `x` for `length` bars back, `false` otherwise. **Arguments** - **`series` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). ### `falling(series, length)` Test if the `series` is now falling for `length` bars long. **Returns** `true` if current `x` is less than any previous `x` for `length` bars back, `false` otherwise. **Arguments** - **`series` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). ### `rsi(upper, lower)` Relative strength index. It is calculated based on rma's of upward and downward change of x. **Returns** Relative strength index. **Arguments** - **`upper` (float)** Series of values to process. - **`lower` (float)** Number of bars (length). ### `sum(source, length, context)` The sum function returns the sliding sum of last y values of x. **Returns** Sum of x for y bars back. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `sma(source, length, context)` The sma function returns the moving average, that is the sum of last `length` values of `source`, divided by `length`. **Returns** Simple moving average of x for y bars back. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `rma(source, length, context)` Moving average used in RSI. It is the exponentially weighted moving average with alpha = 1 / length. **Returns** Exponential moving average of x with alpha = 1 / y. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `fixnan(current, context)` For a given series replaces NaN values with previous nearest non-NaN value. **Returns** Series without `na` gaps. **Arguments** - **`current` (series[float])** Series of values to process. - **`context`** PineJS execution context. ### `tr(handle_nan, context)` **Returns** True range. It is `max(high - low, abs(high - close[1]), abs(low - close[1]))` **Arguments** - **`handle_nan` (bool)** How NaN values are handled. if `true`, and previous day's close is NaN then `tr` would be calculated as current day high-low. Otherwise (if `false`) `tr` would return NaN in such cases. Also note, that atr uses `tr(true)`. - **`context`** PineJS execution context. ### `atr(length, context)` Function atr (average true range) returns the RMA of true range. True range is `max(high - low, abs(high - close[1]), abs(low - close[1]))` **Returns** Average true range. **Arguments** - **`length` (integer)** Length (number of bars back). - **`context`** PineJS execution context. ### `ema(series, length, context)` The ema function returns the exponentially weighted moving average. In ema weighting factors decrease exponentially. It calculates by using a formula: `EMA = alpha * x + (1 - alpha) * EMA[1]`, where `alpha = 2 / (y + 1)` **Returns** Exponential moving average of x with alpha = 2 / (y + 1) **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `wma(source, length, context)` The wma function returns weighted moving average of `source` for `length` bars back. In wma weighting factors decrease in arithmetical progression. **Returns** Weighted moving average of `series` for `length` bars back. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `vwma(source, length, context)` The `vwma` function returns volume-weighted moving average of `source` for `length` bars back. It is the same as: `sma(x * volume, y) / sma(volume, y)` **Returns** Volume-weighted moving average of `source` for `length` bars back. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `swma(source, context)` Symmetrically weighted moving average with fixed length: 4. Weights: `[1/6, 2/6, 2/6, 1/6]`. **Returns** Symmetrically weighted moving average **Arguments** - **`source` (series[float])** Source series. - **`context`** PineJS execution context. ### `lowestbars(source, length, context)` Lowest value offset for a given number of bars back. **Returns** Offset to the lowest bar. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `lowest(source, length, context)` Lowest value for a given number of bars back. **Returns** Lowest value. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `highestbars(source, length, context)` Highest value offset for a given number of bars back. **Returns** Offset to the highest bar. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `highest(source, length, context)` Highest value for a given number of bars back. **Returns** Highest value. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `cum(x, context)` Cumulative (total) sum of `x`. In other words it's a sum of all elements of `x`. **Returns** Total sum series. **Arguments** - **`x` (series[float])** Series of values to process. - **`context`** PineJS execution context. ### `accdist(context)` Accumulation/distribution index. **Arguments** - **`context`** PineJS execution context. ### `correlation(source_a, source_b, length, context)` Correlation coefficient. Describes the degree to which two series tend to deviate from their `sma` values. **Returns** Correlation coefficient. **Arguments** - **`source_a` (series[float])** Source series. - **`source_b` (series[float])** Target series. - **`length` (integer)** Length (number of bars back). - **`context`** PineJS execution context. ### `stoch(source, high, low, length, context)` Stochastic. It is calculated by a formula: `100 * (close - lowest(low, length)) / (highest(high, length) - lowest(low, length))` **Returns** Stochastic. **Arguments** - **`source` (series[float])** Source series. - **`high` (series[float])** Series of high. - **`low` (series[float])** Series of low. - **`length` (integer)** Length (number of bars back). - **`context`** PineJS execution context. ### `tsi(source, short_length, long_length, context)` True strength index. It uses moving averages of the underlying momentum of a financial instrument. **Returns** True strength index. A value in range [-1, 1] **Arguments** - **`source` (series[float])** Source series. - **`short_length` (integer)** Short length. - **`long_length` (integer)** Long length. - **`context`** PineJS execution context. ### `cross(x, y, context)` **Returns** `true` if two series have crossed each other, otherwise `false`. **Arguments** - **`x` (series[float])** First series. - **`y` (series[float])** Second series. - **`context`** PineJS execution context. ### `linreg(source, length, offset)` Linear regression curve. A line that best fits the prices specified over a user-defined time period. It is calculated using the least squares method. The result of this function is calculated using the formula: `linreg = intercept + slope * (length - 1 - offset)`, where intercept and slope are the values calculated with the least squares method on source series (x argument). **Returns** Linear regression curve. **Arguments** - **`source` (series[float])** Source series. - **`length` (integer)** - **`offset` (integer)** Offset. ### `sar(start, inc, max, context)` Parabolic SAR (parabolic stop and reverse) is a method devised by J. Welles Wilder, Jr., to find potential reversals in the market price direction of traded goods. **Returns** Parabolic SAR. **Arguments** - **`start` (series[float])** Start. - **`inc` (integer)** Increment. - **`max` (integer)** Maximum. - **`context`** PineJS execution context. ### `alma(series, length, offset, sigma)` Arnaud Legoux Moving Average. It uses Gaussian distribution as weights for moving average. **Returns** Arnaud Legoux Moving Average. **Arguments** - **`series` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`offset` (float)** Controls tradeoff between smoothness (closer to 1) and responsiveness (closer to 0). - **`sigma` (float)** Changes the smoothness of ALMA. The larger sigma the smoother ALMA. ### `change(source)` Difference between current value and previous, `x - x[1]`. **Returns** The result of subtraction. **Arguments** - **`source` (series[float])** ### `roc(source, length)` Function roc (rate of change) showing the difference between current value of `source` and the value of `source` that was `length` days ago. It is calculated by the formula: `100 * change(src, length) / src[length]`. **Returns** The rate of change of `source` for `length` bars back. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). ### `dev(source, length, context)` Measure of difference between the series and it's `sma`. **Returns** Deviation of `source` for `length` bars back. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. ### `stdev(source, length, context)` **Returns** Standard deviation. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. **Remarks** This is a biased estimation of standard deviation. ### `variance(source, length, context)` Variance is the expectation of the squared deviation of a series from its mean `sma`, and it informally measures how far a set of numbers are spread out from their mean. **Returns** Variance of `source` for `length` bars back. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). - **`context`** PineJS execution context. **Remarks** This is a biased estimation of sample variance. ### `percentrank(source, length)` Percent rank is the percents of how many previous values was less than or equal to the current value of given series. **Returns** Percent rank of `source` for `length` bars back. **Arguments** - **`source` (series[float])** Series of values to process. - **`length` (integer)** Number of bars (length). ### `dmi(diLength, adxSmoothingLength, context)` Calculates the directional movement values +DI, -DI, DX, ADX, and ADXR. **Returns** An array of the +DI, -DI, DX, ADX, and ADXR values with `diLength` smoothing for the (+/-)DI values and `adxSmoothingLength` for the ADX value. **Arguments** - **`diLength` (integer)** Number of bars (length) used when calculating the +DI and -DI values. - **`adxSmoothingLength` (integer)** Number of bars (length) used when calculating the ADX value. - **`context`** PineJS execution context. ## Functions specific to the library - `isZero(number)` - boolean, shows whether the `number` equals zero or almost zero - `toBool(number)` - boolean, `true` if a number is finite and not equals zero - `eq(arg1, arg2)` - boolean, `true` if argument numbers are equal - `neq(arg1, arg2)` - boolean, `true` if argument numbers are not equal - `ge(arg1, arg2)` - boolean, `true` if first argument number is greater or equal to second - `gt(arg1, arg2)` - boolean, `true` if first argument number is greater than second - `le(arg1, arg2)` - boolean, `true` if first argument number is lesser or equal to second - `lt(arg1, arg2)` - boolean, `true` if first argument is lesser than second - `updatetime(context)` - string, symbol update time - `ticker(context)` - string, symbol name without exchange prefix, e.g. 'MSFT' - `interval(context)` - returns symbol interval string - `isdwm(context)` - boolean, returns `true` if current resolution is a daily or weekly or monthly resolution - `isintraday(context)` - boolean, returns true if current resolution is an intraday (minutes or seconds) resolution - `isdaily(context)` - boolean, returns `true` if current resolution is a daily resolution - `isweekly(context)` - boolean, returns `true` if current resolution is a weekly resolution - `ismonthly(context)` - boolean, returns `true` if current resolution is a monthly resolution - `add_days_considering_dst(timezone, utcTime, daysCount)` - `selectSessionBreaks(context, times)` - select session breaks for intraday resolutions only - `timepart(symbol, field, time)` - `wvap(source, context)` - `createNewSessionCheck(context)` - `error(message)` - returns study error with `message` specified - `time(context, period)` - returns UNIX time of current bar URL: https://www.tradingview.com/charting-library-docs/latest/custom_studies/Studies-Extending-The-Time-Scale ============================================================================================================== # Extending the time scale The tick marks on the [time scale] are defined by the times in the main series. Most studies calculate their values from the bars of the main series. The simplest example of this is the Volume study - each bar of the main series has a volume associated with it and the Volume study simply shows that volume at the same time point as the bar. Because of this it is natural that the times of study values correspond 1-to-1 with the times of the main series. For example, on the chart of weekly data, you can see there is one Volume bar for each bar of the main series. ![Image of a simple volume study on a chart](https://www.tradingview.com/charting-library-docs/img/simple_volume_example.png) ## Mapping times In some cases a study needs to calculate its values from a series of bars that are not the same as the main series. In this case it is necessary to map each study value to the time of one of the main series' bars. Consider the example of the built-in Moving Average study. You can provide a symbol input that is different to the symbol of the main study. The library will resolve and then use this input to calculate the Moving Average. The chart below has a symbol "A" for the main series and a Moving Average study for symbol "B". You can see 5 daily bars from 2022-12-26 to 2022-12-31. ![Image of a moving average study on a chart](https://www.tradingview.com/charting-library-docs/img/moving_average_adopt_example.png) Although you cannot tell by looking at the chart in this example the symbol B actually has more bars than symbol A: symbol A is missing a bar for 2022-12-29. | A time | B time | Shown on chart? | | ---------- | ---------- | --------------- | | 2022-12-26 | 2022-12-26 | Yes | | 2022-12-27 | 2022-12-27 | Yes | | 2022-12-28 | 2022-12-28 | Yes | | | 2022-12-29 | No | | 2022-12-30 | 2022-12-30 | Yes | | 2022-12-31 | 2022-12-31 | Yes | By default studies can only display data at a time point on the chart if the main series has a bar at that time point. This is done by mapping (or "adopting") the values of the study that correspond to a time in the main series. There are two ways of mapping times from one series to another: precise and continuous. ### Precise mapping Precise mapping means that each bar time of the main series will be mapped to at most once. | Main series time | Study time | Study value | Displayed value | | -------------------- | -------------- | --------------- | --------------- | | 2023-01-01 | 2022-01-01 | 1.11 | 1.11 | | 2023-01-02 | 2022-01-02 | 1.50 | 1.50 | | | 2022-01-02 | 2.30 | | | 2023-01-03 | 2022-01-03 | 3.00 | 3.00 | ### Continuous mapping Continuous mapping means that each main series bar time may be mapped to more than once. If the study time does not exist in the main series then the closest time greater than the study time is used. | Main series time | Study time | Study value | Displayed value | | -------------------- | -------------- | --------------- | --------------- | | 2023-01-01 | 2022-01-01 | 1.11 | 1.11 | | 2023-01-02 | 2022-01-02 | 1.50 | 1.50 | | | 2022-01-02 | 2.30 | 3.00 | | 2023-01-03 | 2022-01-03 | 3.00 | 3.00 | ## Extending the time scale feature There is a feature that allows studies to define their points on a time scale. For studies that use this feature, the restriction that the time exists in the main series is removed. This allows you to create custom studies that show bars at a higher resolution than the main series. For example, you can create a study showing the weekly average of a monthly symbol. import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Image of a monthly symbol and a weekly study on a chart Image of a monthly symbol on the chart There are two options available to enable the time scale extension feature: - [for any custom study](#for-any-custom-study) - [for the Overlay study only](#for-overlay-study) ### For any custom study To enable the feature for any [custom study], follow the steps below. 1. Enable the [`studies_extend_time_scale`] featureset. 2. Add `canExtendTimeScale: true` to the study's [metainfo]. In the example below, if a symbol input is chosen that contains more bars than the main series, the time scale will be extended to show those extra bars. Note that the example will resolve the other symbol with the same resolution as the main series. However, you can customize it by changing the resolution parameter. ```javascript { name: 'Extend Time Scale Example', metainfo: { id: 'Extend Time Scale Example@tv-basicstudies-1', name: 'Extend Time Scale Example', _metainfoVersion: 51, description: 'Extend Time Scale Example', shortDescription: 'Extend Time Scale Example', is_price_study: true, defaults: { styles: { plot_0: { plottype: 0, visible: true, color: 'orange' }, }, inputs: { symbol: '', } }, plots: [{ id: 'plot_0', type: 'line' }], styles: { plot_0: { title: 'Plot', }, }, inputs: [ { id: 'symbol', name: 'Other Symbol', type: 'symbol', }, ], format: { type: 'inherit' }, canExtendTimeScale: true, // important! }, constructor: function () { this.init = function (ctx, inputCallback) { this._context = ctx; var symbol = inputCallback(0); if (symbol !== '') { const resolution = PineJS.Std.period(this._context); this._context.new_sym(symbol, resolution); } } this.main = function (ctx, inputCallback) { this._context = ctx; this._input = inputCallback; var symbol = inputCallback(0); if (symbol !== '') { this._context.select_sym(1); } var close = this._context.new_var(PineJS.Std.close(this._context)); return [close]; }; } } ``` ### For Overlay study The library includes the built-in Overlay study, which allows you to display multiple symbols on a single chart for easy comparison. To make [compared symbols] extend the time scale, enable the [`secondary_series_extend_time_scale`] featureset. This featureset only applies to the Overlay study and enables the *Allow extend time scale* option within the *Compare symbol* dialog. For example, when comparing BTCUSD to AAPL, you can see the points on the time scale where only BTCUSD has data. The image below shows that the upper chart allows the Overlay study to extend the time scale, while the bottom chart does not. ![Extending time scale when comparing BTCUSD with AAPL](https://www.tradingview.com/charting-library-docs/img/extended-time-scale-for-overlay.png) [compared symbols]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators#add-and-compare-new-series [custom study]: https://www.tradingview.com/charting-library-docs/latest/custom_studies [metainfo]: https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo [`secondary_series_extend_time_scale`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#secondary_series_extend_time_scale [`studies_extend_time_scale`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#studies_extend_time_scale [time scale]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale URL: https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom-indicator-constructor ========================================================================================================== # Constructor ## Overview `constructor` is a required field in the [`CustomIndicator`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CustomIndicator) object that you should specify to create a [custom indicator](https://www.tradingview.com/charting-library-docs/latest/custom_studies). ```javascript custom_indicators_getter: function(PineJS) { return Promise.resolve([ { // Indicator object // ... constructor: { // ... }, } ]); }, ``` The field should contain an ES5 constructor function. The library applies the `new` operator to the constructor to create an instance of the custom indicator. The constructor contains the [`main`](#main) and [`init`](#init) methods that accept the following arguments: - [`ctx`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IContext) — context that stores an indicator state. It includes information about the current symbol, resolution, OHLC values of the current bar, and more. - `inputs` — an array of input values. Elements in the array are arranged in the same order as [inputs](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfoinputs) in the `metainfo`. You should implement either both methods or only `main` to calculate indicator data. In your implementation, use mathematical, logical, and technical analysis functions provided in the [`PineJSStd`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PineJSStd) interface. ## init The [`init`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibraryPineStudy#init) method is **optional**. It is designed to get additional information for an indicator and allows you to initialize variables needed for your data calculations. For example, you can reset a counter with this method. The library calls `init` when the indicator should be calculated from scratch. This can occur when: - The indicator is added to the chart. - The indicator is added to a new pane. - The symbol is changed. - The resolution is changed. - Additional historical data is loaded. Consider the following example. You want to display an indicator that compares values between the current symbol and a different one. In this case, the indicator requires data for another symbol. The code sample below shows how to request data for an additional symbol using the [`new_sym`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IContext#new_sym) method. In this case, requesting data should be done once, therefore, it is implemented within `init`. ```javascript this.init = function(context, inputCallback) { var symbol = "AAPL"; var period = PineJS.Std.period(this._context); context.new_sym(symbol, period); }; ``` ## main The [`main`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibraryPineStudy#main) method is **required** and should contain the main [data calculations](#data-calculations). The library calls this method for each bar of the [main series](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryseries). :::info If there is more than one series, the library calls `main` for each bar of an additional series first, and then for each bar of the main series. ::: ### Data calculations As mentioned above, the library calls `main` for each bar of the [main series](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryseries). On each iteration, you can get information about previous bars only. Therefore, when you calculate the tenth bar, you can access values of the bars in the [1..9] range. The library does not provide future bars, and you should not use them in your calculations to avoid unexpected results. To store data for intermediate calculations, you should create variables using API methods such as [`new_var`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IContext#new_var) and [`new_unlimited_var`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IContext#new_unlimited_var). Consider the [Requesting Data for Another Ticker](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examplesrequesting-data-for-another-ticker) example where the timestamp of the current bar is stored using `new_var`. ### Output values As a result, the method should return an indicator value that corresponds to the current bar. An indicator is represented with [plots](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfoplots) specified in `metainfo`. Therefore, you should provide a value for each plot. If there is only one plot, `main` should return a number, for example `10`, or an array with one element — `[10]`. Otherwise, the result is an array where elements are arranged in the same order as plots in `metainfo`. Consider the [OHLC Plots](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-OHLC-Plots) example where four plots get the corresponding open, high, low, and close values. Values in the array can be one of the following types: - Numbers, for example, `[10, 20]`. - Objects with the `{ offset: number, value: number, }` structure that allow you to display a value several bars forward or backward from the current bar. For example, `[{ value: 10, offset: 5, }, { value: 20, offset: 10, }]`. ## Example The code sample below demonstrates the `constructor` implementation for a simple indicator that plots the close value. ```javascript constructor: function () { this.main = function (context, inputCallback) { this._context = context; this._input = inputCallback; var symbolClose = PineJS.Std.close(this._context); return [symbolClose]; }; }, ``` URL: https://www.tradingview.com/charting-library-docs/latest/custom_studies ============================================================================= # Custom indicators Advanced Charts and Trading Platform support more than 100 [indicators](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators). You can also create your custom indicators in JavaScript using the library's API. The API allows you to create a variety of indicators using different plot types, styles, colors, and mathematical functions. Users can [add a custom indicator](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicatorsadd-an-indicator) to the chart and change some indicator parameters using the _Indicators_ and _Settings_ dialog in the UI, respectively. However, users cannot create their own indicators or change the code of the existing ones. :::info [Pine Script®](https) is not supported in the libraries. ::: ## Add indicators To add custom indicators to the library, specify a function that returns a Promise object with an array of custom [indicator objects](#indicator-object). Assign this function to the [`custom_indicators_getter`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_indicators_getter) property in the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor). ```javascript custom_indicators_getter: function(PineJS) { return Promise.resolve([ // Indicator objects { // ... }, { // ... }, ]); }, ``` ## Indicator object A custom indicator is an instance of [`CustomIndicator`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CustomIndicator) that contains the following fields: - `name`: an indicator's internal name that is not visible in the UI. This name should be unique. - `metainfo`: the field that describes how the indicator looks like. This field defines the [plot](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryplot) types that represent the indicator and contains information, such as an indicator's name, description, style, color, and more. Refer to the [Metainfo](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo) article for more information. - `constructor`: the field that contains functions `init()` and `main()`. You should specify data calculations in these functions. Refer to [Constructor](https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom-indicator-constructor) for more information. ```javascript custom_indicators_getter: function(PineJS) { return Promise.resolve([ { // Indicator object name: 'Custom indicator name', metainfo: { // ... }, constructor: function() { // ... } } ]); }, ``` ## Examples Follow the links below to explore some implementation examples of custom indicators. - [Requesting data for another ticker](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examplesrequesting-data-for-another-ticker) - [Coloring bars](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examplescoloring-bars) - [Advanced Coloring Candles](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examplesadvanced-colouring-candles) - [Custom styles for every point](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examplescustom-styles-for-every-point) - [Complex filled areas](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examplescomplex-filled-areas) - [OHLC plots](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-OHLC-Plots) - [Advanced Shapes use](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examplesadvanced-shapes-use) URL: https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/Custom-Studies-Defaults ============================================================================================================== # Custom Studies Defaults `defaults` is a field in [Metainfo](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo) of Custom Study, containing an object with settings that are applied when user clicks `Apply Defaults`. This object has following fields: `* - required` * `bands` - an array with band styles. Band style is an object with fields: * `color`* - string * `linestyle`* - number * `linewidth`* - number * `value`* - number * `visible`* - boolean * `filledAreasStyle` - an object. The keys are filled area ids, the values are style objects with fields: * `color`* - string * `visible`* - boolean * `transparency`* - number * `inputs` - an object with `input id` as a key and default value for this input. The default value can be `string`, `number` or `bool` depending on input type. The field is required if your study has inputs * `palettes` - an object with `pallette id` as a key and palette definition: `[name]: { colors, valToIndex, addDefaultColor }`, where * `colors`* - an object `{ [color_id]: color_info }`. The color is an object with following fields: * `color`* - string * `style`* - number * `width`* - number * `valToIndex` - an object, the mapping between the values that are returned by the script and palette color indexes * `addDefaultColor` - boolean, if `true` the defaults are used for `colorer` type plot, when its value is `NaN` * `precision`* - precision of the study's output values (quantity of digits after the decimal separator) * `styles` - an object with `plot id` as keys and style info as values. `plot style` is an object with keys, specific for each plot `type` ([see below](#default-styles)) ## Default Styles Here is a short reference for `plot style` object in `defaults`. Some of fields are the same for all of plot types: * `visible`* - boolean Additional fields should be added depending on `plot type`. ### Line * `color`* - string, plot color * `linestyle`* - number * `linewidth`* - number * `trackPrice`* - boolean, if `true`, price line is displayed ### Shapes * `plottype`* - string, can have following values: * `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` * `location`*- string, one of the following: * `AboveBar` * `BelowBar` * `Top` * `Bottom` * `Right` * `Left` * `Absolute` * `AbsoluteUp` * `AbsoluteDown` * `color`* - string, plot color * `textColor`* - string, text color * `size` - [`PlotSymbolSize`](https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.PlotSymbolSize), plot size #### Note about shape size To change the shape size, specify the `size` property with one of the values listed in [`PlotSymbolSize`](https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.PlotSymbolSize). Note that this property controls the shape's height but not its width. The width depends on the width of the bar displayed on the chart. When the visible range is low or the chart is zoomed in, the bars expand horizontally, causing the shape's width to increase accordingly. ```javascript plots: [ { id: "plot_0", type: "shapes" }, ], defaults: { styles: { plot_0: { plottype: "shape_arrow_down", size: 'huge', // Other properties }, }, }, ``` ### Chars * `char*`* - string * `location`*- string, one of the following: * `AboveBar` * `BelowBar` * `Top` * `Bottom` * `Right` * `Left` * `Absolute` * `AbsoluteUp` * `AbsoluteDown` * `color`* - string, plot color * `textColor`* - string, color ### Arrows * `colorup`* - string, color * `colordown`* - string, color URL: https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/Custom-Studies-Inputs ============================================================================================================ # Inputs ## Overview When you create a [custom indicator], you can make some indicator parameters variable and allow users to adjust them in the UI. Such parameters are called **input parameters** or **inputs**. Users should provide values for the input parameters in the _Inputs_ tab of the indicator settings dialog. Then, these values will be used in the indicator [calculations](#handle-input-values-in-the-constructor). For example, a custom indicator can accept a [source symbol] and length as input parameters. Inputs tab To enable input parameters, you should take the following steps: 1. [Define a list of input parameters](#define-a-list-of-input-parameters) 2. [Specify default values](#specify-default-values) 3. [Handle input values in the constructor](#handle-input-values-in-the-constructor) ## Define a list of input parameters To define a list of input parameters, you should assign an array of objects to the [`inputs`] property in [`StudyMetaInfo`]. ```javascript custom_indicators_getter: function(PineJS) { return Promise.resolve([ // Indicator object { // Define indicator metadata metainfo: { /* Other StudyMetaInfo properties */ // Define input parameters inputs: [ /* A list of input objects */ ] }, } ]); }, ``` :::tip `StudyMetaInfo` is an interface that you should implement to provide metadata for the custom indicator. For more information, refer to the [Metainfo] article. ::: Input parameters can be of multiple types, including numeric, text, time, and others. Therefore, each object in `inputs` should implement a certain interface depending on the parameter type. The table below contains frequently used interfaces: Interface | Definition ---------|---------- [`StudyNumericInputInfo`] | Designed for numeric parameters. [`StudyTextInputInfo`] | Designed for parameters represented with text. For example, types of a smoothing line: SMA, EMA, and WMA. [`StudySourceInputInfo`] | Designed to specify values that are used to calculate the indicator. For example, open or close prices of the bars. [`StudySymbolInputInfo`] | Designed to specify a [source symbol]. Refer to [`StudyInputInfo`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#studyinputinfo) for a complete list of interfaces. Consider the following example. A custom indicator has two input parameters: length (a time period) and source (a type of bar values). To specify these parameters, you should implement a [`StudyNumericInputInfo`] and [`StudySourceInputInfo`] objects, respectively. Both interfaces have the following properties: - `id` that is used to refer to the input parameter - `name` that specifies the parameter name in the _Inputs_ tab - `type` that specifies the parameter data type - `defval` that specifies the default parameter value Other properties depend on the parameter type. The code sample below shows the implementation of the input parameters. ```javascript metainfo: { // ... inputs: [ // StudyNumericInputInfo object { id: "length", name: "Length", defval: 9, // 9 bars type: "integer", min: 1, max: 10000, }, // StudySourceInputInfo object { id: "source", name: "Source", defval: "close", // Close price type: "source", options: [ // Options in the drop-down menu "open", "high", "low", "close", "hl2", "hlc3", "ohlc4", ], }, ] } ``` ## Specify default values [`StudyMetaInfo`] contains the [`defaults`] property that stores default values for all indicator settings, including input parameters. For each parameter defined in [`inputs`], you should provide the corresponding value in `defaults`. :::warning Your custom indicator will not work unless you provide values in `defaults` for each input parameter. ::: To specify default values, assign a [`StudyInputsSimple`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyInputsSimple) object to the `inputs` property in [`StudyDefaults`]. `StudyInputsSimple` contains pairs of keys and values, where a key is a certain input parameter's `id`, and a value is the default value for this parameter. In the [previous section](#define-a-list-of-input-parameters), you can see an example of the indicator with two input parameters: length and source. The code sample below demonstrates how to specify default input values for this indicator. ```javascript metainfo: { // ... inputs: [ { id: "length", // This value is used as ID to refer to the input parameter // ... }, { id: "source", // This value is used as ID to refer to the input parameter // ... }, ] // StudyDefaults object defaults: { // ... inputs: { // ID : default value length: 9, source: "close", }, } } ``` ## Handle input values in the constructor To create a custom indicator, you should implement a [constructor] that calculates indicator data. In the constructor, you can retrieve input values and then use them in your data calculations. To do this, use the `inputCallback` provided with [`main`] and [`init`] functions. The callback returns an array of input values arranged in the same order as in the [`inputs`] property. In the [Define a list of input parameters](#define-a-list-of-input-parameters) section, you can see an example of the indicator with two input parameters: length and source. The code sample below demonstrates how to get input values for this indicator. ```javascript constructor: function () { this.main = function(ctx, inputCallback) { // ... this._input = inputCallback; var length = this._input(0); var source = this._input(1); }; } ``` [custom indicator]: https://www.tradingview.com/charting-library-docs/latest/custom_studies [`inputs`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#inputs [source symbol]: https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#source-symbol [`StudyMetaInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#studymetainfo [Metainfo]: https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo [`StudyTextInputInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyTextInputInfo [`StudyNumericInputInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyNumericInputInfo [`StudySourceInputInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudySourceInputInfo [`StudySymbolInputInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudySymbolInputInfo [`defaults`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#defaults [`StudyDefaults`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyDefaults [constructor]: https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom-indicator-constructor [`main`]: https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom-indicator-constructor#main [`init`]: https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom-indicator-constructor#init URL: https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo ====================================================================================== # Metainfo ## Overview `metainfo` is a required field in the [`CustomIndicator`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CustomIndicator) object that you should specify to create a [custom indicator](https://www.tradingview.com/charting-library-docs/latest/custom_studies). ```javascript custom_indicators_getter: function(PineJS) { return Promise.resolve([ { // Indicator object metainfo: { // ... }, // ... } ]); }, ``` This field defines [plot](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryplot) types that represent the indicator and contains the indicator's metadata, such as a name, description, style defaults, colors, plot types, inputs, and more. The information should be arranged in a specific format and supplied as a [`StudyMetaInfo`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#studymetainfo) object. The indicator's _Settings_ dialog is generated based on this object. :::info `StudyMetaInfo` is initialized once and cannot be changed after the chart is created. ::: This article describes the most important `StudyMetaInfo` properties. You can find the complete list of properties in the [API](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo) section. :::tip Consider the [how-to guide](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator/metainfo-implementation) that demonstrates an example of the `metainfo` implementation. ::: ## Service information You should specify the properties below to provide service information on the indicator. ### _metainfoVersion The [`_metainfoVersion`] property represents a version number of metadata. The current version is `53`, and the default one is `0`. Even though this property is optional, we recommend that you always specify it and use the latest version. Therefore, your indicator is more compatible with newer versions of the library. ```javascript metainfo: { // ... _metainfoVersion: 53, } ``` ### id The [`id`] property is a string that has the `@tv-basicstudies-1` format. The `id` value should be unique. ```javascript metainfo: { // ... id: 'Custom indicator@tv-basicstudies-1', } ``` ## Indicator name You should use the properties below to specify the indicator's name in the UI. ### description The [`description`] property contains the indicator's name that is displayed in the _Indicators_ dialog and the _Object Tree_. You should use the `description` value as a `name` argument if you create an indicator using the [`createStudy`] method. ![Indicator's description](https://www.tradingview.com/charting-library-docs/img/description-property.png) ```javascript metainfo: { // ... description: 'Custom Indicator', } ``` ### shortDescription The [`shortDescription`] property contains the indicator's name that is displayed in the [_Legend_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend), the _Settings_ dialog, and the corresponding label on the [_Price Scale_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale). ![Short description of indicator](https://www.tradingview.com/charting-library-docs/img/short-description.png) ```javascript metainfo: { // ... shortDescription: 'Custom Indicator Short Description', } ``` ## Data You should use the properties below to specify data that the indicator uses. ### format Depending on the indicator data, the [_Price Scale_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale) displays price, volume, or percent values. To specify the indicator's data type, assign either a [`StudyPlotValueInheritFormat`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyPlotValueInheritFormat) or [`StudyPlotValuePrecisionFormat`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyPlotValuePrecisionFormat) object to the [`format`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#format) property. If the data has the same type and precision as the [source symbol](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossarysource-symbol), create a `StudyPlotValueInheritFormat` object with the `type` property set to `inherit`. Otherwise, create a `StudyPlotValuePrecisionFormat` object with the desired `type` and `precision`. For example, the code sample below specifies price values with two decimal places. ```javascript metainfo: { // ... format: {precision: 2, type: 'price'}, } ``` ### inputs The [`inputs`] property defines input parameters that the indicator has. Input properties depend on the [input type](https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#studyinputinfo). ```javascript metainfo: { // ... inputs: [ { id: "length", name: "Length", defval: 9, type: "integer", min: 1, max: 10000, }, { id: "source", name: "Source", defval: "close", type: "source", options: [ "open", "high", "low", "close", "hl2", "hlc3", "ohlc4", ], }, ] } ``` Options on the _Inputs_ tab of the _Settings_ dialog are generated based on `inputs`. Additionally, you should specify default values for input parameters in [`defaults`](#defaults). ```javascript metainfo: { // ... defaults: { // ... inputs: { length: 9, source: "close", }, } } ``` ![Inputs](https://www.tradingview.com/charting-library-docs/img/inputs-custom-indicator.png) Refer to the [Inputs](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/Custom-Studies-Inputs) article for more information. ### symbolSource The [`symbolSource`] property allows you to specify a symbol that will be used as a data source for the indicator. The default source is the main [series] that represents the main symbol on the chart. ## Visual representation You should use the properties below to specify visual elements that the indicator consists of. ### plots The [`plots`] property defines simple elements, for example, lines and drawings, that the indicator consists of. Refer to the [StudyPlotType](https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.StudyPlotType) page to see the list of all plot types. ```javascript metainfo: { // ... plots: [ { id: 'plot_0', type: 'line', }, ], } ``` Each plot requires additional information that should be specified in [`styles`](#styles) and [`defaults`](#defaults). ```javascript metainfo: { // ... defaults: { // ... styles: { plot_0: { linestyle: 0, linewidth: 1, plottype: 1, trackPrice: false, transparency: 0, visible: true, color: '#000080', } }, }, styles: { plot_0: { title: "Plot", histogramBase: 0, joinPoints: false, }, }, } ``` For more information about plots, refer to the [Custom Studies Plots](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Plots) article. ### ohlcPlots The [`ohlcPlots`] property defines open-high-low-close (OHLC) plots that are used to display OHLC indicators. Refer to the [Custom Studies OHLC](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-OHLC-Plots) article for more information. ### bands The [`bands`] property defines bands (horizontal lines) and their settings that users cannot change. Bands ```javascript metainfo: { // ... bands: [ { id: 'hline_0', name: 'UpperLimit', zorder: -1.1, }, { id: 'hline_1', name: 'LowerLimit', zorder: -1.11, }, ] } ``` Additionally, you should specify default values for settings that the user can change on the _Styles_ tab, for example, colors and styles, in the [`defaults`](#defaults) properties. ```javascript metainfo: { // ... // ... defaults: { bands: [ { color: '#787B86', linestyle: 2, linewidth: 1, visible: true, value: 1, }, { color: '#787B86', linestyle: 2, linewidth: 1, visible: true, value: 0, } ] } } ``` Bands in UI ### filledAreas The [`filledAreas`] property defines color areas. These areas can be drawn between two [plot](#plots) lines or two [bands](#bands), but not between a band and a plot line. Consider the [Complex Filled Areas](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examplescomplex-filled-areas) example that shows how to use `filledAreas`. Bands Filled Areas in UI ## Appearance and visibility You should use the properties below to specify the indicator's appearance. ### defaults The [`defaults`] property contains default values for other properties in [`StudyMetaInfo`] like [`plots`](#plots), [`inputs`](#inputs), [`styles`](#styles), and others. In the _Settings_ dialog, users can reset all settings or override default values using the _Defaults_ dropdown list. ![Defaults dropdown list](https://www.tradingview.com/charting-library-docs/img/defaults-ui.png) All properties that you can specify in `defaults` are listed in [`StudyDefaults`]. Refer to the [Custom Studies Defaults](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/Custom-Studies-Defaults) for more information. ### styles The [`styles`] property contains style settings for each plot defined in [`plots`](#plots). Users cannot change these settings in the UI. ```javascript metainfo: { // ... styles: { plot_0: { title: 'Plot', histogramBase: 0, joinPoints: false, } } } ``` Additionally, you should specify default values for plot settings that the user can change in the _Styles_ tab, for example, colors and styles, in the [`defaults`](#defaults) properties. ```javascript metainfo: { // ... defaults: { styles: { plot_0: { linestyle: 0, linewidth: 1, plottype: 1, trackPrice: false, transparency: 0, visible: true, color: '#000080', } } } } ``` ![Styles tab](https://www.tradingview.com/charting-library-docs/img/styles-tab.png) ### palettes The [`palettes`] property defines color palettes that are required if you use [plot](#plots) types such as `Colorer`, `BarColorer`, `OhlcColorer`, and others. These plot types allow you to draw an indicator that consists of lines, bars, or other elements of different colors. Consider the [Coloring Bars](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examplescoloring-bars) example that shows how to use `palettes`. ### is_hidden_study The [`is_hidden_study`] property allows you to hide a custom indicator in the _Indicators_ dialog. To do this, set this property to `true`. The default value is `false`. ```javascript metainfo: { // ... is_hidden_study: true, } ``` ### is_price_study The [`is_price_study`] property specifies whether the indicator should be displayed on the same pane with the main [series]. Price study ### linkedToSeries The [`linkedToSeries`] property specifies whether the indicator should use the same [price scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale) as the main [series]. If the property is `false`, you can move the series to another pane without the indicator. linkedToSeries You should set `linkedToSeries` to `true` if you create an indicator that does not make sense without the series. In this case, the _Move to_ option is hidden in the UI. [`_metainfoVersion`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#_metainfoversion [`id`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#id [`is_price_study`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#is_price_study [`is_hidden_study`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#is_hidden_study [`description`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#description [`shortDescription`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#shortdescription [`createStudy`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createstudy [`defaults`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#defaults [`StudyDefaults`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyDefaults [`linkedToSeries`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#linkedtoseries [`styles`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#styles [`StudyMetaInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#studymetainfo [`palettes`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#palettes [`inputs`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#inputs [`symbolSource`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#symbolsource [`plots`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#plots [`bands`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#bands [`filledAreas`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#filledareas [`ohlcPlots`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#ohlcplots [series]: https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#series URL: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets ======================================================================================== # Featuresets **Featureset** is a string literal that allows showing or hiding UI elements and changing the chart's behavior. ## How to use To enable or disable a feature, include it in the [`enabled_features`] or [`disabled_features`] array of the [Widget Constructor] object. ```html ``` This code sample enables the spread operators in the [*Symbol Search*] dialog and disables [*Add to favorites*] and *Show Object tree* buttons in the UI. ## Simple and complex featuresets Featuresets can be simple and complex where complex consists of the simple ones. Note that disabling complex featureset disables all its simple parts as well. In the table below, simple featuresets are nested within complex featuresets using indentation. import AnchoredTable from '@site/src/components/anchored-table'; import complexFeaturesets from './_featureset_tables/complex_featuresets.json'; ## Visibility of controls and visual elements import visibilityFeaturesets from './_featureset_tables/visibility_controls.json'; ## Elements placement import elementsPlacementFeaturesets from './_featureset_tables/elements_placement.json'; ## Behavior import behaviourFeaturesets from './_featureset_tables/behaviour.json'; ## Trading Platform :::info These featuresets are only available in [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal). ::: import ttFeaturesets from './_featureset_tables/trading_terminal.json'; [*Add to favorites*]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings#favorite-tools [`disabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features [`enabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#enabled_features [*Symbol Search*]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets ======================================================================================== [ { "anchorName": "accessible_keyboard_shortcuts", "cells": [ "accessible_keyboard_shortcuts", "Off", "Changes the keyboard navigation shortcut from Alt + Z to Tab. Refer to Keyboard navigation for more information." ] }, { "anchorName": "allow_arbitrary_symbol_search_input", "cells": [ "allow_arbitrary_symbol_search_input", "Off", "Enables or disables the ability for users to enter arbitrary input in the Symbol Search dialog. When this feature is disabled (default behavior), pressing the _Enter_ key without selecting a search result will automatically select the top search result as the input value. If no results are available, pressing _Enter_ will have no effect.
When this feature is enabled, the user's direct input will be used as the selected value, regardless of whether it matches any search results. This input will then be passed to the data feed for resolution and loading." ] }, { "anchorName": "aria_crosshair_price_description", "cells": [ "aria_crosshair_price_description", "Off", "Announces, via the screen reader, the price when the crosshair is moved on the chart. Currently only supported for the English language." ] }, { "anchorName": "aria_detailed_chart_descriptions", "cells": [ "aria_detailed_chart_descriptions", "Off", "Generates a more detailed ARIA description of the chart for screen readers when the active chart is changed by the user. The more detailed description includes a brief description of the price values for the main series.
ARIA descriptions are currently only provided for the English language. You can use the custom_chart_description_function constructor option if you wish to add support for additional languages." ] }, { "anchorName": "auto_enable_symbol_labels", "cells": [ "auto_enable_symbol_labels", "On", "Shows the symbol name label when comparing symbols." ] }, { "anchorName": "axis_pressed_mouse_move_scale", "cells": [ "axis_pressed_mouse_move_scale", "On", "Enables axis scaling with the left mouse button pressed." ] }, { "anchorName": "chart_scroll", "cells": [ "chart_scroll", "On", "Enables chart scrolling." ] }, { "anchorName": "chart_zoom", "cells": [ "chart_zoom", "On", "Enables chart zooming." ] }, { "anchorName": "charting_library_debug_mode", "cells": [ "charting_library_debug_mode", "Off", "Enables logs." ] }, { "anchorName": "confirm_overwrite_if_chart_layout_with_name_exists", "cells": [ "confirm_overwrite_if_chart_layout_with_name_exists", "Off", "By default, many chart layouts can be saved with the same name. If this feature is enabled, the library will prompt to confirm overwriting chart layouts with the same name when saving, renaming, or cloning (Save as)." ] }, { "anchorName": "create_volume_indicator_by_default", "cells": [ "create_volume_indicator_by_default", "On", "Adds the Volume indicator upon the chart initialization." ] }, { "anchorName": "create_volume_indicator_by_default_once", "cells": [ "create_volume_indicator_by_default_once", "On", "Prevents the Volume indicator from being recreated when an instrument or a resolution is switched." ] }, { "anchorName": "constraint_dialogs_movement", "cells": [ "constraint_dialogs_movement", "On", "Keeps the dialogs within the chart." ] }, { "anchorName": "cropped_tick_marks", "cells": [ "cropped_tick_marks", "On", "Shows partially visible price labels on price axis." ] }, { "anchorName": "custom_resolutions", "cells": [ "custom_resolutions", "Off", "Allows adding custom resolutions in the UI." ] }, { "anchorName": "datasource_copypaste", "cells": [ "datasource_copypaste", "On", "Enables copying of drawings and indicators." ] }, { "anchorName": "determine_first_data_request_size_using_visible_range", "cells": [ "determine_first_data_request_size_using_visible_range", "Off", "By default, the chart requests a small, fixed number of bars for the initial data request when the chart is first created. If this feature is enabled, the library will calculate the request size based on the number of bars that will be visible on the chart." ] }, { "anchorName": "disable_pulse_animation", "cells": [ "disable_pulse_animation", "Off", "Disables the pulse animation when chart type is set to Line." ] }, { "anchorName": "disable_resolution_rebuild", "cells": [ "disable_resolution_rebuild", "Off", "Shows bar time exactly as provided by the datafeed, without adjustments. For more information, refer to Resolution." ] }, { "anchorName": "end_of_period_timescale_marks", "cells": [ "end_of_period_timescale_marks", "Off", "Toggles the timeline marks to display the bar's end time." ] }, { "anchorName": "fix_left_edge", "cells": [ "fix_left_edge", "Off", "Prevents scrolling to the left of the first historical bar." ] }, { "anchorName": "header_in_fullscreen_mode", "cells": [ "header_in_fullscreen_mode", "Off", "Enables the header widget DOM element in the full screen mode" ] }, { "anchorName": "hide_price_scale_if_all_sources_hidden", "cells": [ "hide_price_scale_if_all_sources_hidden", "Off", "Hides the price scale if all indicators or series attached to the price scale are hidden." ] }, { "anchorName": "horz_touch_drag_scroll", "cells": [ "horz_touch_drag_scroll", "On", "Enables the chart to handle the horizontal pointer movements on touch screens. In this case, the webpage is not scrolled. If disabled, the webpage is scrolled instead.

Note that if the user starts scrolling the chart vertically or horizontally, scrolling is continued in any direction until the user releases the finger." ] }, { "anchorName": "inactivity_gaps", "cells": [ "inactivity_gaps", "Off", "Allows displaying inactivity gaps on charts. These gaps represent periods within the trading session when there has been no trading activity. For more information, refer to the Show/hide gaps section." ] }, { "anchorName": "iframe_loading_compatibility_mode", "cells": [ "iframe_loading_compatibility_mode", "Off", "Enables alternative loading mode for the library, which can be used to support older browsers and a few non-standard browsers." ] }, { "anchorName": "iframe_loading_same_origin", "cells": [ "iframe_loading_same_origin", "Off", "Enables an alternative loading mode for the library, which can be used when the iframe content must be served from the same origin.
Available from version 28." ] }, { "anchorName": "insert_indicator_dialog_shortcut", "cells": [ "insert_indicator_dialog_shortcut", "On", "Enables the Open indicator shortcut (/)." ] }, { "anchorName": "legend_inplace_edit", "cells": [ "legend_inplace_edit", "On", "Enables in-place editing of indicators and series in the Legend.
Note that disabling this featureset also hides the Symbol Search within the Legend." ] }, { "anchorName": "library_custom_color_themes", "cells": [ "library_custom_color_themes", "On", "Enables Custom Themes API.
Available from version 28." ] }, { "anchorName": "lock_visible_time_range_on_resize", "cells": [ "lock_visible_time_range_on_resize", "Off", "Prevents changing visible time area on chart resizing." ] }, { "anchorName": "lock_visible_time_range_when_adjusting_percentage_right_margin", "cells": [ "lock_visible_time_range_when_adjusting_percentage_right_margin", "Off", "Lock the visible range when adjusting the percentage right margin via the settings dialog. This applies when the chart is already at the current default margin position." ] }, { "anchorName": "low_density_bars", "cells": [ "low_density_bars", "Off", "Allows zooming in to one bar in the viewport." ] }, { "anchorName": "mouse_wheel_scale", "cells": [ "mouse_wheel_scale", "On", "Enables series scaling with a mouse wheel." ] }, { "anchorName": "mouse_wheel_scroll", "cells": [ "mouse_wheel_scroll", "On", "Enables chart scrolling with a horizontal mouse wheel." ] }, { "anchorName": "no_min_chart_width", "cells": [ "no_min_chart_width", "Off", "Disables the minimum chart width limit." ] }, { "anchorName": "pinch_scale", "cells": [ "pinch_scale", "On", "Enables series scaling with pinch/zoom gestures. This feature is supported on touch devices only." ] }, { "anchorName": "pressed_mouse_move_scroll", "cells": [ "pressed_mouse_move_scroll", "On", "Enables chart scrolling with the left mouse button pressed." ] }, { "anchorName": "pre_post_market_price_line", "cells": [ "pre_post_market_price_line", "Off", "Enables the pre-/post-market price lines.
Available from version 29.1." ] }, { "anchorName": "request_only_visible_range_on_reset", "cells": [ "request_only_visible_range_on_reset", "Off", "When the chart data is reset, this featureset enables re-requesting the data for just the visible range, instead of the entire range of the existing loaded data." ] }, { "anchorName": "right_bar_stays_on_scroll", "cells": [ "right_bar_stays_on_scroll", "On", "Determines the behavior of the Zoom feature: the bar under the mouse cursor stays in the same place if this feature is disabled" ] }, { "anchorName": "save_shortcut", "cells": [ "save_shortcut", "On", "Enables the Save chart layout shortcut (Ctrl + S)." ] }, { "anchorName": "saveload_separate_drawings_storage", "cells": [ "saveload_separate_drawings_storage", "Off", "Enables an alternative saving and loading mode for the library. This mode saves the state of the drawings separately from the chart layout." ] }, { "anchorName": "seconds_resolution", "cells": [ "seconds_resolution", "Off", "Enables the support of resolutions in seconds." ] }, { "anchorName": "secondary_series_extend_time_scale", "cells": [ "secondary_series_extend_time_scale", "Off", "Allows an additional series to extend the time scale." ] }, { "anchorName": "shift_visible_range_on_new_bar", "cells": [ "shift_visible_range_on_new_bar", "On", "If disabled, adding a new bar zooms the chart out preserving the first visible point. Otherwise, when a new bar appears, the chart is scrolled one point to the left." ] }, { "anchorName": "side_toolbar_in_fullscreen_mode", "cells": [ "side_toolbar_in_fullscreen_mode", "Off", "Enables the Drawings toolbar in the full screen mode." ] }, { "anchorName": "studies_extend_time_scale", "cells": [ "studies_extend_time_scale", "Off", "Enables custom indicators to extend the time scale if canExtendTimeScale is set to true in the indicator's metainfo." ] }, { "anchorName": "study_templates", "cells": [ "study_templates", "Off", "Enables a button in the header to load/save Indicator template." ] }, { "anchorName": "study_symbol_ticker_description", "cells": [ "study_symbol_ticker_description", "Off", "Applies the symbol display mode (ticker/description) to the indicator inputs in the status line." ] }, { "anchorName": "study_overlay_compare_legend_option", "cells": [ "study_overlay_compare_legend_option", "Off", "Applies the symbol display mode (ticker/description) to overlay/compare indicators in the status line." ] }, { "anchorName": "tick_resolution", "cells": [ "tick_resolution", "Off", "Enables the support of resolutions in ticks." ] }, { "anchorName": "two_character_bar_marks_labels", "cells": [ "two_character_bar_marks_labels", "Off", "Allows displaying up to two characters in bar marks. The default behavior is to only display one character." ] }, { "anchorName": "uppercase_instrument_names", "cells": [ "uppercase_instrument_names", "On", "When disabled, this feature allows a user to enter case-sensitive symbols." ] }, { "anchorName": "use_last_visible_bar_value_in_legend", "cells": [ "use_last_visible_bar_value_in_legend", "Off", "By default, the legend shows the most recent \"global\" bar value. When this featureset is enabled, the rightmost bar in the visible range is used instead." ] }, { "anchorName": "vert_touch_drag_scroll", "cells": [ "vert_touch_drag_scroll", "On", "Enables the chart to handle the vertical pointer movements on touch screens. In this case, the webpage is not scrolled. If disabled, the webpage is scrolled instead.

Note that if the user starts scrolling the chart vertically or horizontally, scrolling is continued in any direction until the user releases the finger." ] }, { "anchorName": "volume_force_overlay", "cells": [ "volume_force_overlay", "On", "Places the Volume indicator on the same pane with the main series." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets ======================================================================================== [ { "anchorName": "context_menus", "cells": [ "context_menus", "On", "Shows any context menu when users right-click anywhere in the UI." ] }, { "anchorName": "legend_context_menu", "indent": 1, "cells": [ "legend_context_menu", "On", "Shows the context menu when users right-click the Legend widget." ] }, { "anchorName": "pane_context_menu", "indent": 1, "cells": [ "pane_context_menu", "On", "Shows the context menu when users right-click the chart." ] }, { "anchorName": "scales_context_menu", "indent": 1, "cells": [ "scales_context_menu", "On", "Shows the context menu when users right-click either Price Scale or Time Scale." ] }, { "anchorName": "edit_buttons_in_legend", "cells": [ "edit_buttons_in_legend", "On", "Shows buttons on the Legend widget. When disabled, hides all buttons except the ellipsis menu." ] }, { "anchorName": "delete_button_in_legend", "indent": 1, "cells": [ "delete_button_in_legend", "On", "Shows the Remove button on the Legend widget." ] }, { "anchorName": "format_button_in_legend", "indent": 1, "cells": [ "format_button_in_legend", "On", "Shows the Settings button on the Legend widget." ] }, { "anchorName": "show_hide_button_in_legend", "indent": 1, "cells": [ "show_hide_button_in_legend", "On", "Shows the Hide and Show buttons on the Legend widget." ] }, { "anchorName": "header_widget", "cells": [ "header_widget", "On", "Shows the header panel and Symbol Search on the chart." ] }, { "anchorName": "header_chart_type", "indent": 1, "cells": [ "header_chart_type", "On", "Shows the chart type button on the header panel." ] }, { "anchorName": "header_compare", "indent": 1, "cells": [ "header_compare", "On", "Shows the Compare or Add Symbol button on the header panel." ] }, { "anchorName": "header_fullscreen_button", "indent": 1, "cells": [ "header_fullscreen_button", "On", "Shows the Fullscreen mode button on the header panel." ] }, { "anchorName": "header_indicators", "indent": 1, "cells": [ "header_indicators", "On", "Shows the Indicators button on the header panel." ] }, { "anchorName": "header_resolutions", "indent": 1, "cells": [ "header_resolutions", "On", "Shows the Resolution button on the header panel." ] }, { "anchorName": "show_interval_dialog_on_key_press", "indent": 3, "cells": [ "show_interval_dialog_on_key_press", "On", "Opens the Change Interval dialog when users type digits or press the comma key." ] }, { "anchorName": "header_screenshot", "indent": 1, "cells": [ "header_screenshot", "On", "Shows the Take a snapshot button on the header panel." ] }, { "anchorName": "header_settings", "indent": 1, "cells": [ "header_settings", "On", "Shows the Chart settings button on the header panel." ] }, { "anchorName": "header_symbol_search", "indent": 1, "cells": [ "header_symbol_search", "On", "Shows the Symbol Search button on the header panel." ] }, { "anchorName": "header_undo_redo", "indent": 1, "cells": [ "header_undo_redo", "On", "Shows the Undo/Redo buttons on the header panel." ] }, { "anchorName": "header_quick_search", "indent": 1, "cells": [ "header_quick_search", "On", "Shows the Quick search button on the header panel." ] }, { "anchorName": "symbol_search_hot_key", "indent": 1, "cells": [ "symbol_search_hot_key", "On", "Allows opening Symbol Search using the typing keys." ] }, { "anchorName": "use_localstorage_for_settings", "cells": [ "use_localstorage_for_settings", "On", "Allows storing chart properties and user settings, including favorites, in the browser's localStorage.
Refer to the Customization precedence article to learn more about the application order of localStorage among other approaches." ] }, { "anchorName": "save_chart_properties_to_local_storage", "indent": 1, "cells": [ "save_chart_properties_to_local_storage", "On", "Can be disabled to forbid storing chart properties in the localStorage while allowing to save other properties. The other properties include favorites in Advanced Charts, and Watchlist symbols and some panel states in Trading Platform." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets ======================================================================================== [ { "anchorName": "move_logo_to_main_pane", "cells": [ "move_logo_to_main_pane", "Off", "Places the logo on the main series pane instead of the bottom pane." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets ======================================================================================== [ { "anchorName": "add_to_watchlist", "cells": [ "add_to_watchlist", "On", "Enables the Add symbol to Watchlist option in the menu." ] }, { "anchorName": "always_pass_called_order_to_modify", "cells": [ "always_pass_called_order_to_modify", "Off", "If a bracket order is modified, the terminal passes its parent order to modifyOrder. The featureset disables this behavior." ] }, { "anchorName": "buy_sell_buttons", "cells": [ "buy_sell_buttons", "On", "Shows the Buy/Sell buttons in the Legend." ] }, { "anchorName": "broker_button", "indent": 1, "cells": [ "broker_button", "On", "Shows the Broker button () in the Legend." ] }, { "anchorName": "chart_crosshair_menu", "cells": [ "chart_crosshair_menu", "On", "Shows the Plus button on the price scale for quick trading. Note that this menu will be empty unless you implement the Broker API." ] }, { "anchorName": "chart_hide_close_position_button", "cells": [ "chart_hide_close_position_button", "Off", "Hides the close button for positions." ] }, { "anchorName": "chart_hide_close_order_button", "cells": [ "chart_hide_close_order_button", "Off", "Hides the close button for orders." ] }, { "anchorName": "chart_property_page_trading", "cells": [ "chart_property_page_trading", "On", "Shows the Trading section in Chart settings." ] }, { "anchorName": "chart_template_storage", "cells": [ "chart_template_storage", "Off", "Enables saving/loading chart templates. To store chart templates, implement the logic for API handlers." ] }, { "anchorName": "drawing_templates", "cells": [ "drawing_templates", "On", "Enables Drawing Templates on the Drawing toolbar." ] }, { "anchorName": "dom_widget", "cells": [ "dom_widget", "Off", "Enables the Depth of Market widget visibility." ] }, { "anchorName": "header_layouttoggle", "cells": [ "header_layouttoggle", "On", "Shows the Select Layout button on the top toolbar. Using this button, users can select multiple-chart layouts." ] }, { "anchorName": "hide_right_toolbar", "cells": [ "hide_right_toolbar", "Off", "Hides the right toolbar when initializing the chart to free up space. The toolbar can be shown/hidden later using the WidgetBar API." ] }, { "anchorName": "hide_right_toolbar_tabs", "cells": [ "hide_right_toolbar_tabs", "Off", "Hides the tabs within the right toolbar." ] }, { "anchorName": "keep_object_tree_widget_in_right_toolbar", "cells": [ "keep_object_tree_widget_in_right_toolbar", "Off", "Keeps the Object tree in the right toolbar. If the right_toolbar featureset is not enabled, this feature will not work." ] }, { "anchorName": "legend_last_day_change", "cells": [ "legend_last_day_change", "Off", "Adds the Last day change values option to the Chart Settings dialog in the UI. This option allows users to show/hide the last day change values in the main series legend." ] }, { "anchorName": "multiple_watchlists", "cells": [ "multiple_watchlists", "On", "Enables creating multiple Watchlists." ] }, { "anchorName": "open_account_manager", "cells": [ "open_account_manager", "On", "Keeps the Account Manager opened by default." ] }, { "anchorName": "order_info", "cells": [ "order_info", "On", "Shows the order information section in the Order Ticket." ] }, { "anchorName": "order_panel", "cells": [ "order_panel", "On", "Shows the Order Ticket. Note that disabling this featureset also hides the Trade button in the Account Manager." ] }, { "anchorName": "order_panel_close_button", "cells": [ "order_panel_close_button", "On", "Shows the Close Order Ticket button." ] }, { "anchorName": "order_panel_undock", "cells": [ "order_panel_undock", "On", "Shows the Undock button in the Order Ticket settings." ] }, { "anchorName": "prefer_symbol_name_over_fullname", "cells": [ "prefer_symbol_name_over_fullname", "On", "Displays the symbol name instead of the exchange:name combination in the UI.
Available from version 28." ] }, { "anchorName": "right_toolbar", "cells": [ "right_toolbar", "On", "Shows the right toolbar with buttons." ] }, { "anchorName": "show_dom_first_time", "cells": [ "show_dom_first_time", "Off", "Shows the Depth of Market widget when a user opens the chart for the first time." ] }, { "anchorName": "show_last_price_and_change_only_in_series_legend", "cells": [ "show_last_price_and_change_only_in_series_legend", "Off", "Shows only the last price and change values in the main series legend." ] }, { "anchorName": "show_order_panel_on_start", "cells": [ "show_order_panel_on_start", "Off", "Shows the Order Ticket when the chart opens." ] }, { "anchorName": "show_symbol_logo_in_account_manager", "cells": [ "show_symbol_logo_in_account_manager", "On", "Displays the symbol's logo within the Account Manager. Note that you must also enable show_symbol_logos." ] }, { "anchorName": "show_trading_notifications_history", "cells": [ "show_trading_notifications_history", "On", "Enables the Notifications log tab on the bottom panel." ] }, { "anchorName": "support_multicharts", "cells": [ "support_multicharts", "On", "Enables context menu actions (for example Sync in layout for drawings) related to multiple-chart layout.
Note that disabling this featureset does not remove the Select Layout button on the top toolbar. To hide this button, disable the header_layouttoggle featureset." ] }, { "anchorName": "trading_account_manager", "cells": [ "trading_account_manager", "On", "Shows the Account Manager." ] }, { "anchorName": "trading_notifications", "cells": [ "trading_notifications", "On", "Shows trading notifications on the chart." ] }, { "anchorName": "watchlist_context_menu", "cells": [ "watchlist_context_menu", "On", "Enables context menu support in the Watchlist." ] }, { "anchorName": "watchlist_import_export", "cells": [ "watchlist_import_export", "On", "Enables Watchlist export and import." ] }, { "anchorName": "watchlist_sections", "cells": [ "watchlist_sections", "On", "Display UI (buttons and context menu options) for creating sections within the watchlist." ] }, { "anchorName": "prefer_quote_short_name", "cells": [ "prefer_quote_short_name", "On", "Displays the short_name value as a symbol name in the Watchlist and Details." ] }, { "anchorName": "watchlist_cross_tab_sync", "cells": [ "watchlist_cross_tab_sync", "On", "Enables the cross-tab synchronization for watchlists.
Available from version 29.2.0." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets ======================================================================================== [ { "anchorName": "adaptive_logo", "cells": [ "adaptive_logo", "On", "Shows the Chart by TradingView text on small-screen devices." ] }, { "anchorName": "always_show_legend_values_on_mobile", "cells": [ "always_show_legend_values_on_mobile", "Off", "Shows legend values when on mobile." ] }, { "anchorName": "border_around_the_chart", "cells": [ "border_around_the_chart", "On", "Adds a 2px padding to the chart." ] }, { "anchorName": "chart_style_hilo", "cells": [ "chart_style_hilo", "Off", "Adds High-Low option to the chart style controls." ] }, { "anchorName": "chart_style_hilo_last_price", "cells": [ "chart_style_hilo_last_price", "Off", "Enables last price line and price axis label on the High-Low chart style." ] }, { "anchorName": "chart_property_page_right_margin_editor", "cells": [ "chart_property_page_right_margin_editor", "On", "Shows the Right margin field in Settings → Appearance" ] }, { "anchorName": "chart_property_page_scales", "cells": [ "chart_property_page_scales", "On", "Allows Overrides for the Price Scale." ] }, { "anchorName": "clear_price_scale_on_error_or_empty_bars", "cells": [ "clear_price_scale_on_error_or_empty_bars", "On", "Clears the pane price scales when the main series has an error or no bars." ] }, { "anchorName": "compare_symbol_search_spread_operators", "cells": [ "compare_symbol_search_spread_operators", "Off", "Shows the spread operators in the Compare symbol dialog. Note that you must also enable show_spread_operators." ] }, { "anchorName": "control_bar", "cells": [ "control_bar", "On", "Shows the Zoom In/Out and Scroll to the Left/Right navigation buttons at the bottom of the chart." ] }, { "anchorName": "countdown", "cells": [ "countdown", "On", "Shows the Countdown to bar close option on the Price Scale." ] }, { "anchorName": "display_data_mode", "cells": [ "display_data_mode", "Off", "Enables an icon and the Data is delayed section in the Legend." ] }, { "anchorName": "display_legend_on_all_charts", "cells": [ "display_legend_on_all_charts", "Off", "Display the Legend widget on all diagrams regardless of the crosshair synchronization." ] }, { "anchorName": "display_market_status", "cells": [ "display_market_status", "On", "Shows the market status on the Legend widget." ] }, { "anchorName": "dont_show_boolean_study_arguments", "cells": [ "dont_show_boolean_study_arguments", "Off", "Shows true and false indicator arguments." ] }, { "anchorName": "go_to_date", "cells": [ "go_to_date", "On", "Shows the Go to option that allows jumping to a particular bar." ] }, { "anchorName": "header_saveload", "cells": [ "header_saveload", "On", "Shows the Save layout and Load layout buttons (the feature is not part of the header_widget featureset)." ] }, { "anchorName": "hide_image_invalid_symbol", "cells": [ "hide_image_invalid_symbol", "Off", "Hides the image that is shown to illustrate an invalid symbol." ] }, { "anchorName": "hide_last_na_study_output", "cells": [ "hide_last_na_study_output", "Off", "Shows last N/A indicator output data." ] }, { "anchorName": "hide_left_toolbar_by_default", "cells": [ "hide_left_toolbar_by_default", "Off", "Shows left toolbar when a user opens the chart for the first time." ] }, { "anchorName": "hide_main_series_symbol_from_indicator_legend", "cells": [ "hide_main_series_symbol_from_indicator_legend", "On", "Hides the optional symbol input value from the indicator legend if the Main chart symbol option is selected." ] }, { "anchorName": "hide_price_scale_global_last_bar_value", "cells": [ "hide_price_scale_global_last_bar_value", "Off", "Hides the global last price label on the Price Scale if the last bar is outside of the visible range." ] }, { "anchorName": "hide_exponentiation_spread_operator", "cells": [ "hide_exponentiation_spread_operator", "Off", "Shows the exponentiation spread operator (^) in the Symbol Search dialog." ] }, { "anchorName": "hide_reciprocal_spread_operator", "cells": [ "hide_reciprocal_spread_operator", "Off", "Shows reciprocal spread operator (1/x) in the Symbol Search dialog." ] }, { "anchorName": "hide_object_tree_and_price_scale_exchange_label", "cells": [ "hide_object_tree_and_price_scale_exchange_label", "Off", "Hides the exchange label from the displayed label." ] }, { "anchorName": "hide_resolution_in_legend", "cells": [ "hide_resolution_in_legend", "Off", "Shows the interval (D, 2D, W, M, etc.) in the chart legend and the data window." ] }, { "anchorName": "hide_unresolved_symbols_in_legend", "cells": [ "hide_unresolved_symbols_in_legend", "Off", "Shows unresolved symbols in the chart legend and the data window." ] }, { "anchorName": "items_favoriting", "cells": [ "items_favoriting", "On", "Shows the Add to favorites icon for chart types, drawings, indicators, and resolutions." ] }, { "anchorName": "left_toolbar", "cells": [ "left_toolbar", "On", "Shows the Drawings toolbar on the left panel." ] }, { "anchorName": "legend_widget", "cells": [ "legend_widget", "On", "Shows the Legend widget on the top-left corner of any chart." ] }, { "anchorName": "main_series_scale_menu", "cells": [ "main_series_scale_menu", "On", "Shows the Settings button in the right-bottom corner of the chart." ] }, { "anchorName": "object_tree_legend_mode", "cells": [ "object_tree_legend_mode", "On", "Shows the Show Object tree button in the legend at a small width." ] }, { "anchorName": "pricescale_currency", "cells": [ "pricescale_currency", "Off", "Shows the Currency context menu in Chart Settings → Scales. The menu allows selecting the visibility of the currency in which the instrument is traded on the price scale. Refer to the Instrument currency section for more information." ] }, { "anchorName": "pricescale_unit", "cells": [ "pricescale_unit", "Off", "Shows the Unit context menu in Chart Settings → Scales. The menu allows selecting the visibility of the unit in which the instrument is traded on the Price Scale." ] }, { "anchorName": "pre_post_market_sessions", "cells": [ "pre_post_market_sessions", "Off", "Enables pre- and post-market session support. For more information, refer to Extended sessions." ] }, { "anchorName": "property_pages", "cells": [ "property_pages", "On", "Shows all Settings pages." ] }, { "anchorName": "popup_hints", "cells": [ "popup_hints", "On", "Shows pop-up hints about possible mouse/shortcut/UI actions." ] }, { "anchorName": "remove_library_container_border", "cells": [ "remove_library_container_border", "On", "Sets the border style to 0px and padding to 1px." ] }, { "anchorName": "scales_date_format", "cells": [ "scales_date_format", "On", "Shows the Date format selector in Chart settings." ] }, { "anchorName": "scales_time_hours_format", "cells": [ "scales_time_hours_format", "On", "Shows the Time hours format selector in Chart settings." ] }, { "anchorName": "show_chart_property_page", "cells": [ "show_chart_property_page", "On", "Enables the Chart settings page." ] }, { "anchorName": "show_average_close_price_line_and_label", "cells": [ "show_average_close_price_line_and_label", "Off", "Shows the visibility settings of the label and the average close price line." ] }, { "anchorName": "show_exchange_logos", "cells": [ "show_exchange_logos", "Off", "Shows logos for the exchanges within the Symbol Search dialog." ] }, { "anchorName": "show_right_widgets_panel_by_default", "cells": [ "show_right_widgets_panel_by_default", "On", "Opens the right widget toolbar on the first launch." ] }, { "anchorName": "show_symbol_logos", "cells": [ "show_symbol_logos", "Off", "Shows logos for the symbols within Symbol Search and the Watchlist widget." ] }, { "anchorName": "show_symbol_logo_for_compare_studies", "cells": [ "show_symbol_logo_for_compare_studies", "On", "Shows the symbol's logo within the legend for compare studies. Note that you must also enable show_symbol_logos and show_symbol_logo_in_legend." ] }, { "anchorName": "show_symbol_logo_in_legend", "cells": [ "show_symbol_logo_in_legend", "On", "Display the main symbol's logo within the Legend. Note that you must also enable show_symbol_logos." ] }, { "anchorName": "show_object_tree", "cells": [ "show_object_tree", "On", "Shows the Show Object tree button on the left or right toolbar depending on the product and configuration." ] }, { "anchorName": "show_percent_option_for_right_margin", "cells": [ "show_percent_option_for_right_margin", "Off", "Shows the option to specify the default right margin in percentage in the Appearance → Chart settings dialog." ] }, { "anchorName": "show_spread_operators", "cells": [ "show_spread_operators", "Off", "Shows the spread operators in the Symbol Search dialog." ] }, { "anchorName": "show_zoom_and_move_buttons_on_touch", "cells": [ "show_zoom_and_move_buttons_on_touch", "Off", "On touch devices, shows the zoom and move buttons at the bottom of the chart." ] }, { "anchorName": "snapshot_trading_drawings", "cells": [ "snapshot_trading_drawings", "Off", "Includes orders, positions, and executions in the screenshot." ] }, { "anchorName": "source_selection_markers", "cells": [ "source_selection_markers", "On", "Enables selection markers for series and indicators." ] }, { "anchorName": "studies_symbol_search_spread_operators", "cells": [ "studies_symbol_search_spread_operators", "Off", "Shows the spread operators for some indicators (for example Volume and Moving Average) in the Settings → Inputs → Another symbol → Change symbol dialog. Note that you should also enable show_spread_operators." ] }, { "anchorName": "symbol_info", "cells": [ "symbol_info", "On", "Shows the Symbol Info option on the Legend widget." ] }, { "anchorName": "symbol_info_long_description", "cells": [ "symbol_info_long_description", "Off", "Enables long symbol descriptions to be shown in the main series and compare studies legends if provided in the symbol info data." ] }, { "anchorName": "symbol_info_price_source", "cells": [ "symbol_info_price_source", "Off", "Shows symbol price source in the main series and Compare indicator legends. You should also provide the price_source_id and price_sources properties in the LibrarySymbolInfo object." ] }, { "anchorName": "timeframes_toolbar", "cells": [ "timeframes_toolbar", "On", "Shows the Time frame toolbar at the bottom of the chart." ] }, { "anchorName": "timezone_menu", "cells": [ "timezone_menu", "On", "Enables the Time zone dropdown list that allows switching the time zone from the bottom toolbar." ] }, { "anchorName": "use_na_string_for_not_available_values", "cells": [ "use_na_string_for_not_available_values", "Off", "Shows a literal \"N/A\" for not available values instead of \"∅\"." ] }, { "anchorName": "use_symbol_name_for_header_toolbar", "cells": [ "use_symbol_name_for_header_toolbar", "Off", "Uses the name of a symbol rather than its ticker name in the Symbol Search dialog and header button.
Available from version 29.4.0." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/customization/customization-issues ================================================================================================= # Common issues This article describes common customization issues. ## General troubleshooting To debug any customization issue, consider the following: 1. Refer to the [Customization precedence](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedence) article to understand how different customization-related settings work and which ones take priority in case of conflicts. 2. Check your customization-related settings defined in both the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) and the [`onChartReady`](https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methodsonchartready) implementation to identify and resolve potential conflicts. 3. Ensure that your settings are not overriden by [user settings](#user-settings-override-default-ones). ## Settings are not applied The library supports extensive customization through a set of APIs. Some settings, such as the chart background color, can be adjusted with different API approaches. If your setting does not take effect, it might be overridden by another API approach. Refer to the [Customization precedence](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedence) article to understand API priorities, and consider using an alternative approach if needed. ## User settings override default ones In the library, [user settings](https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings) take precedence over default configurations specified with the API. Therefore, replacing settings defined through [`overrides`](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedenceoverrides) and [`custom_themes`](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedencecustomThemes) with user input is expected behavior. By default, user settings are stored in [`localStorage`](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedencelocalStorage). To override them, you should adjust these settings with another API approach that has higher priority according to the [table](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedenceapproaches). You can also disable saving settings to the local storage using the [`use_localstorage_for_settings`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsuse_localstorage_for_settings) featureset. Alternatively, you can use [`settings_adapter`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#settings_adapter) to implement your preferred storage method. ## Theme is not switched The library supports light and dark [themes](https://www.tradingview.com/charting-library-docs/latest/customization/theme), which are applied to the entire widget. However, the toolbar and the chart colors are managed separately. The chart color is picked from [user settings](https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings) that take precedence over default configurations. In some case, the theme may not be fully applied, meaning that the chart color differs from the toolbar one. Consider the example. - The chart and toolbar colors are dark. - A user switches to another page, where the chart color and the theme of the application are light. At this stage, the chart color is saved to user settings. - The user goes back to the dark-themed page. The toolbars are dark as expected, but the chart remains light. This happens because the chart color is picked from the user settings. ![Theme issue](https://www.tradingview.com/charting-library-docs/img/theme-switching-issue.png) To resolve this issue, you should apply the theme once again using the [`changeTheme`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#changetheme) method. ```javascript widget.onChartReady(function() { widget.changeTheme("dark"); }); ``` You can also implement a trigger for a conditional theme change. ```javascript widget.changeTheme("dark").then(() => { widget.chart().applyOverrides({ "paneProperties.background": "black", }); }); ``` :::tip The chart colors can be managed with multiple APIs approaches that can override each other. If your color is not applied, make sure that this setting is not changed with another API approach. Refer to the [Customization precedence](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedence) article for more information. ::: URL: https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedence ===================================================================================================== # Customization precedence The library offers multiple approaches to modify the chart's appearance and behavior. This article lists these approaches and demonstrates an example to clarify their order of precedence. ## Approaches The table below provides an overview of customization methods/properties and their precedence. When multiple methods define the same entity, the one with higher precedence will be applied. Here, a lower number means higher precedence, for example: - 1 — takes effect first, meaning it will override other approaches - 8 — takes effect only if no higher-precedence method/property overrides the same entity import AnchoredTable from '@site/src/components/anchored-table'; import customizationOrder from './customization_order.json'; ## Example You can check out the following example to understand how these approaches override each other. Change the flags' values provided at the beginning of the JavaScript file (lines 1-7) to easily manage the example. The coloring of the candle bodies will vary based on the approach applied. Below, you will find the colors associated with each method/property. - `applyOverrides` → orange - `load` → blue - `saved_data` → red - `settings_overrides` → purple - `settings_adapter` → green - `localStorage` → black - `overrides` → yellow URL: https://www.tradingview.com/charting-library-docs/latest/customization ============================================================================ # Customization overview import CardLinkList from "@site/src/components/CardLinkList"; import styles from "./customization.module.css"; The library supports extensive customization through a set of APIs, each designed for specific tasks. For example, [Featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) should be used to control the visibility of chart elements, and the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) to configure the chart size and default symbol. For color adjustments, either [Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides) or [Custom themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes) may be used. The image below illustrates specific areas of the chart and indicates the appropriate API to use for their customization. ![Customization map](https://www.tradingview.com/charting-library-docs/img/customization-map.png) ## Customization APIs :::caution Note that some settings, such as the chart background color, can be adjusted with different API approaches. These approaches may override each other depending on their priority. Refer to the [Customization precedence](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedence) article for more information. ::: ## Commonly customized items ## TradingView logo The visibility of the TradingView logo depends on the terms of your license agreement. Contact your TradingView account manager for more information. ## Limitations - You cannot customize icons on the toolbars. - The library does not support injecting custom UI components. If you want to add a UI component, implement it outside the library. URL: https://www.tradingview.com/charting-library-docs/latest/customization ============================================================================ .customisationPageCardLinkList { padding-bottom: 20px; } URL: https://www.tradingview.com/charting-library-docs/latest/customization ============================================================================ [ { "anchorName": "applyOverrides", "cells": [ "applyOverrides", "Applies overrides to the chart without reloading. Refer to Overrides for more information.", "1" ] }, { "anchorName": "load", "cells": [ "load", "Loads the chart state from an object when the chart is initialized. Refer to the Low-level API section for more information.", "2" ] }, { "anchorName": "saved_data", "cells": [ "saved_data", "Sets an object that contains saved chart content. Refer to the Widget Constructor tutorial on YouTube for an implementation example.", "3" ] }, { "anchorName": "settings_overrides", "cells": [ "settings_overrides", "Overrides chart settings loaded from a custom settings adapter or a local storage. Refer to the Widget Constructor tutorial on YouTube for an implementation example.", "4" ] }, { "anchorName": "settings_adapter", "cells": [ "settings_adapter", "Allows creating your custom settings adapter to save user settings to your preferred storage, including server-side. Refer to the Save user settings article for more information.", "5" ] }, { "anchorName": "localStorage", "cells": [ "localStorage", "Allows storing chart settings in the browser's local storage via the Storage object. You can disable storing properties in the local storage by using the use_localstorage_for_settings featureset.", "6" ] }, { "anchorName": "overrides", "cells": [ "overrides", "Overrides default values of the widget properties. Refer to Overrides for more information.", "7" ] }, { "anchorName": "customThemes", "cells": [ "custom_themes", "Overrides default colors of the light and darks themes. Refer to Custom themes API for more information.", "8" ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Drawings-Overrides ========================================================================================================= # Drawing overrides The [Overrides API](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides) includes properties that can be used to customize [drawing] parameters such as colors, width, size, and more. This article describes ways to customize drawings and contains a [list of overrides](#list-of-overrides) for each drawing. ## Customize drawings This section describes ways to customize drawings. ### Specify default properties You should use the [`overrides`] property of the [Widget Constructor] to specify the drawing's default properties. For example, the following code sample specifies that all _Horizontal Lines_ should be green and dashed. ```js var widget = window.tvWidget = new TradingView.widget({ // ... overrides: { "linetoolhorzline.linecolor": "rgba(48, 164, 22, 0.8)", "linetoolhorzline.linestyle": 2, } }); ``` ### Change default properties on the fly To change the drawing's default properties after the chart is initialized, use the [`applyOverrides`] method. All drawings created after the `applyOverrides` call have new properties. For example, the following code sample specifies that all newly created _Horizontal Lines_ should be purple. ```js widget.applyOverrides({ "linetoolhorzline.linecolor": "#7f11e0" }); ``` ### Change the existing drawing If you want to change a drawing that is already on the chart, use the [`setProperties`] method in [`ILineDataSourceApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ILineDataSourceApi). For example, the code sample below specifies new properties for the existing _Icon_. ```javascript const iconId = widget.activeChart().getAllShapes().find(x => x.name === "icon").id; const icon = widget.activeChart().getShapeById(iconId); icon.setProperties({ size: 60, color: "#7f11e0" }); ``` ### Customize a single drawing If you need to change a style of only one drawing, create the drawing using the [Drawings API] and pass overrides properties as a parameter. These properties are applied above the [default ones](#specify-default-properties) that are specified in `overrides`. For example, the code sample below specifies that the default _Horizontal Line_ color is green and creates one red _Horizontal Line_. ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... overrides: { "linetoolhorzline.linecolor": "rgba(48, 164, 22, 0.8)", } }); widget.onChartReady(() => { widget.chart().createShape( { price: 180 }, { shape: "horizontal_line", overrides: { linecolor: "#FF0000" }, } ) }); ``` ### Customize icons, stickers, and emojis Note that you cannot customize icons, stickers, or emojis using [`overrides`] in the Widget Constructor or the [`applyOverrides`] method. To customize such drawings, create a new drawing using the [Drawings API] and specify the drawing properties in the `overrides` parameter. Consider the examples below. #### Icons ```javascript widget.chart().createShape( { time: 1514796562, price: 180 }, { shape: "icon", overrides: { color: "#5eeb34", size: 50, }, icon: 0xf004, // Heart } ); ``` Refer to [Drawings list](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/Drawings-Listicons) for a list of icons. #### Stickers ```javascript widget.chart().createShape( { time: 1514796562, price: 160 }, { shape: "sticker", overrides: { sticker: "dislike", size: 90, }, } ); ``` Refer to [Drawings list](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/Drawings-Liststickers) for a list of stickers. #### Emojis ```javascript widget.activeChart().createMultipointShape( [{ time: 1712158200, price: 170 }], { shape: "emoji", overrides: { size: 30, }, emoji: "u/1F602" // Grinning face } ); ``` Note that the emoji code requires `u/` before it. Refer to [Drawings list](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/Drawings-Listemojis) for a list of emojis. ## List of overrides Refer to [DrawingOverrides](https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#drawingoverrides) for a list of overrides. [drawing]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings [`overrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#overrides [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor [`applyOverrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#applyoverrides [`setProperties`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ILineDataSourceApi#setproperties [Drawings API]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api#create-drawings URL: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides ================================================================================================ # Overrides The Overrides API allows you to customize elements on the chart like panes, scales, series, drawings, indicators, legends, and more. ## Chart and drawings To override a property that relates to the chart, drawing, or trading element, you should specify this property in the [`overrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#overrides) parameter of [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor). The code sample below changes the chart background color and chart style using [`paneProperties.background`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiesbackground) and [`mainSeriesProperties.style`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesstyle). ```js var widget = window.tvWidget = new TradingView.widget({ // ... overrides: { "paneProperties.background": "#020024", "mainSeriesProperties.style": 2, } }); ``` If you want to change a property's value on the fly, you can use the [`applyOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#applyoverrides) method. ```js widget.applyOverrides({ "mainSeriesProperties.visible": false }); ``` For more information on how to customize different entities using overrides, refer to the corresponding topics: - [Chart overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides) - [Drawings overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Drawings-Overrides) - [Trading overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/trading-overrides) ## Indicators You can also customize indicators using overrides. Refer to the [Indicator Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides) article for more information. URL: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides ====================================================================================================== # Chart overrides This article describes [Overrides API](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides) properties that affect elements on the chart. You can find a full list of properties on the [ChartPropertiesOverrides](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides) page. All properties are divided into four groups: - [`paneProperties`](#paneproperties) — affect elements on the main chart pane. - [`scalesProperties`](#scalesproperties) — affect price and time scales. - [`mainSeriesProperties`](#mainseriesproperties) — affect series. - [`tradingProperties`](#trading-platform) — affect Trading Platform features. ## paneProperties These properties affect elements located on the chart's pane (inside the highlighted area). ![Main pane](https://www.tradingview.com/charting-library-docs/img/overrides-pane.png) ### Chart background color You can specify a background color using the following properties: Property | Description | ---------|----------| [`paneProperties.backgroundType`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiesbackgroundtype) | Pane background type. | [`paneProperties.background`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiesbackground) | Pane background color. | [`paneProperties.backgroundGradientStartColor`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiesbackgroundgradientstartcolor) | Pane background gradient start color. | [`paneProperties.backgroundGradientEndColor`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiesbackgroundgradientendcolor) | Pane background gradient end color. | Background color can be either solid or gradient. Note that the default background type is `gradient` in the **dark theme**. The following code samples demonstrate how to specify background in the dark theme: ```javascript title="Gradient color" var widget = (window.tvWidget = new TradingView.widget({ // ... theme: "dark", overrides: { "paneProperties.backgroundGradientStartColor": "#020024", "paneProperties.backgroundGradientEndColor": "#4f485e", }, })); ``` ![Gradient color](https://www.tradingview.com/charting-library-docs/img/gradient-background.png) ```javascript title="Solid color" var widget = (window.tvWidget = new TradingView.widget({ // ... theme: "dark", overrides: { "paneProperties.background": "#020024", "paneProperties.backgroundType": "solid" }, })); ``` ![Solid color](https://www.tradingview.com/charting-library-docs/img/solid-color.png) ### Grid lines You can specify grid lines using the following properties: Property | Description | ---------|----------| [`paneProperties.vertGridProperties.color`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiesvertgridpropertiescolor) | Pane vertical grid color. | [`paneProperties.vertGridProperties.style`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiesvertgridpropertiesstyle) | Pane vertical grid line style. | [`paneProperties.horzGridProperties.color`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieshorzgridpropertiescolor) | Pane horizontal grid color. | [`paneProperties.horzGridProperties.style`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieshorzgridpropertiesstyle) | Pane horizontal grid line style. | [`paneProperties.gridLinesMode`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiesgridlinesmode) | Pane grid line mode. | The code sample below specifies a dotted grid line. ```javascript title="Dotted grid line" var widget = (window.tvWidget = new TradingView.widget({ // ... overrides: { "paneProperties.horzGridProperties.style": 1, }, })); ``` ### Pane separator You can change the color of the pane separator using the following property (it's also available in Chart settings but you'll have to at least have a pane in addition to main series to see it): Property | Description | ---------|----------| [`paneProperties.separatorColor`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiesseparatorcolor) | Pane separator color. | Here's a code sample: ```javascript title="Pane separator color" var widget = (window.tvWidget = new TradingView.widget({ // ... overrides: { "paneProperties.separatorColor": "#9598a1" }, })); ``` ### Legend You can specify a legend using the following properties: Property | Description | ---------|----------| [`paneProperties.legendProperties.showLastDayChange`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesshowlastdaychange) | Ability to show daily changes in the chart legend. | [`paneProperties.legendProperties.showStudyArguments`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesshowstudyarguments) | Study legend input values visibility. | [`paneProperties.legendProperties.showStudyTitles`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesshowstudytitles) | Studies legend title visibility. | [`paneProperties.legendProperties.showStudyValues`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesshowstudyvalues) | Studies legend value visibility. | [`paneProperties.legendProperties.showSeriesTitle`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesshowseriestitle) | Series legend title visibility. | [`paneProperties.legendProperties.showSeriesOHLC`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesshowseriesohlc) | Study legend OHLC values visibility. | [`paneProperties.legendProperties.showBarChange`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesshowbarchange) | Series legend change value visibility. | [`paneProperties.legendProperties.showSeriesLegendCloseOnMobile`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesshowserieslegendcloseonmobile) | Series legend close value visibility on mobile. | [`paneProperties.legendProperties.showVolume`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesshowvolume) | Series legend volume value visibility. | [`paneProperties.legendProperties.showBackground`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesshowbackground) | Legend background visibility. | [`paneProperties.legendProperties.backgroundTransparency`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertieslegendpropertiesbackgroundtransparency) | Legend background transparency percentage. | Some properties that relate to the [`mainSeriesProperties`](#mainseriesproperties) group also affect the chart's legend. Property | Description | ---------|----------| [`mainSeriesProperties.statusViewStyle.showExchange`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesstatusviewstyleshowexchange) | Main series legend exchange visibility. | [`mainSeriesProperties.statusViewStyle.showInterval`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesstatusviewstyleshowinterval) | Main series legend interval visibility. | [`mainSeriesProperties.statusViewStyle.symbolTextSource`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesstatusviewstylesymboltextsource) | Main series legend text style. | The code sample below removes OHLCV values and chart resolution from the legend. It also specifies the `"long-description"` text style in the legend. ```javascript title="Legend" var widget = (window.tvWidget = new TradingView.widget({ // ... overrides: { "paneProperties.legendProperties.showVolume": false, "paneProperties.legendProperties.showSeriesOHLC": false, "mainSeriesProperties.statusViewStyle.showInterval": false, "mainSeriesProperties.statusViewStyle.symbolTextSource": "long-description", }, })); ``` ![Overrides legend](https://www.tradingview.com/charting-library-docs/img/overrides-legend.png) ### Margin Use the following properties to specify a margin applied when users scale the chart: Property | Description | ---------|----------| [`paneProperties.topMargin`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiestopmargin) | Pane auto scaling top margin percentage. | [`paneProperties.bottomMargin`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiesbottommargin) | Pane auto scaling bottom margin percentage. | ### Crosshair You can specify a crosshair using the following properties: Property | Description | ---------|----------| [`paneProperties.crossHairProperties.color`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiescrosshairpropertiescolor) | Crosshair color. | [`paneProperties.crossHairProperties.style`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiescrosshairpropertiesstyle) | Crosshair style. | [`paneProperties.crossHairProperties.transparency`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiescrosshairpropertiestransparency) | Crosshair transparency. To use this property, specify `paneProperties.crossHairProperties.color` with a **hexadecimal** value such as `#ff0000`. Otherwise, transparency is not applied. | [`paneProperties.crossHairProperties.width`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#panepropertiescrosshairpropertieswidth) | Crosshair width. | ## scalesProperties These properties affect appearance of the [time] and [price] scales. ### Price scale position You can use the [`priceScaleSelectionStrategyName`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#pricescaleselectionstrategyname) property to specify a price scale position. If you want to change the price scale position on the fly, you should use the [`changePriceScale`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISeriesApi#changepricescale) method. ```javascript widget.activeChart().getSeries().changePriceScale('new-left'); ``` ### Scale colors and fonts You can specify scale colors and fonts using the following properties: Property | Description | ---------|----------| [`scalesProperties.lineColor`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertieslinecolor) | Scales (axis) border line color. | [`scalesProperties.textColor`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiestextcolor) | Scales (axis) text color. | [`scalesProperties.fontSize`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesfontsize) | Scales (axis) font size. | [`scalesProperties.axisHighlightColor`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesaxishighlightcolor) | Sets the highlight color of the scales when adding a drawing. | ### Labels on the scale Advanced Charts and Trading Platform include labels that allow you to display additional information on the price scale like a symbol name, bid/ask prices, indicators, and more. You can use the properties below to enable these labels: Property | Description | ---------|----------| [`scalesProperties.showSeriesLastValue`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesshowserieslastvalue) | Series last value label visibility. | [`scalesProperties.showStudyLastValue`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesshowstudylastvalue) | Study label value label visibility. | [`scalesProperties.showSymbolLabels`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesshowsymbollabels) | Symbol name label visibility. | [`scalesProperties.showStudyPlotLabels`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesshowstudyplotlabels) | Study plot labels visibility. | [`scalesProperties.showBidAskLabels`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesshowbidasklabels) | Bid/ask labels visibility. | [`scalesProperties.showPrePostMarketPriceLabel`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesshowprepostmarketpricelabel) | Pre/post market price labels visibility. | [`mainSeriesProperties.highLowAvgPrice.highLowPriceLabelsVisible`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertieshighlowavgpricehighlowpricelinesvisible) | High/low price labels visibility. | [`mainSeriesProperties.highLowAvgPrice.averageClosePriceLabelVisible`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertieshighlowavgpriceaverageclosepricelabelvisible) | Average close price lines label visibility. | You can display values focused in the crosshair in labels on the scales. To do this, specify the following properties: Property | Description | ---------|----------| [`scalesProperties.showPriceScaleCrosshairLabel`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesshowpricescalecrosshairlabel) | Price scale crosshair label visibility. | [`scalesProperties.showTimeScaleCrosshairLabel`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesshowtimescalecrosshairlabel) | Time scale crosshair label visibility. | [`scalesProperties.crosshairLabelBgColorLight`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiescrosshairlabelbgcolorlight) | Crosshair label light theme background color. | [`scalesProperties.crosshairLabelBgColorDark`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiescrosshairlabelbgcolordark) | Crosshair label dark theme background color. | You can specify label colors and display mode using the properties below: Property | Description | ---------|----------| [`mainSeriesProperties.priceAxisProperties.alignLabels`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiespriceaxispropertiesalignlabels) | Main series price axis label alignment behavior. | [`scalesProperties.axisLineToolLabelBackgroundColorActive`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesaxislinetoollabelbackgroundcoloractive) | Dynamically changes the background color of all labels on the price scale when a drawing is in motion. | [`scalesProperties.axisLineToolLabelBackgroundColorCommon`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesaxislinetoollabelbackgroundcolorcommon) | Configures the background color of a label shown on an axis scale when a drawing is selected. | [`scalesProperties.seriesLastValueMode`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#scalespropertiesserieslastvaluemode) | Series last value label display mode. | ### Price scale mode You can specify a price scale mode using the following properties: Property | Description | ---------|----------| [`mainSeriesProperties.priceAxisProperties.percentage`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiespriceaxispropertiespercentage) | Main series price axis percentage mode. | [`mainSeriesProperties.priceAxisProperties.indexedTo100`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiespriceaxispropertiesindexedto100) | Main series price axis indexed to 100 mode. | [`mainSeriesProperties.priceAxisProperties.log`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiespriceaxispropertieslog) | Main series price axis log mode. | [`mainSeriesProperties.priceAxisProperties.isInverted`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiespriceaxispropertiesisinverted) | Main series price axis inverted mode. | Note that you cannot change the price scale mode using the [`applyOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#applyoverrides) method. If you want to change the mode on the fly, you should use the [Price Scale API](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IPriceScaleApi). Consider the code sample below that enables [Logarithmic mode](https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.PriceScaleMode#log): ```javascript const priceScale = widget.activeChart().getPanes()[0].getRightPriceScales()[0]; priceScale.setMode(1); ``` ## mainSeriesProperties These properties affect the main series and UI elements related to its values. A series is a collection of data points that represents a specific metric over time. ### Series visibility If you want to hide the main series, set the [`mainSeriesProperties.visible`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesvisible) property to `false`. You can also use the [`setVisible`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISeriesApi#setvisible) method to change the visibility of the series on the fly. ```javascript widget.activeChart().getSeries().setVisible(true); ``` To check if the series is currently visible or not, use the [`isVisible`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISeriesApi#isvisible) method: ```javascript widget.activeChart().getSeries().isVisible(); ``` ### Chart styles Advanced Charts and Trading Platform support multiple [chart styles](https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.ChartStyle) including Bars, Candles, Line, Area, and more. You can specify the style using the [`mainSeriesProperties.style`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesstyle) property. For each style, there is a group of properties that you can specify to adjust the main series. Properties of one group have the same name pattern. You can use these patterns to find properties for a certain style on the [ChartPropertiesOverrides](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides) page. The table below contains styles and the corresponding patterns. Style | Name patterns | ---------|----------| Line | `mainSeriesProperties.lineStyle` | Baseline | `mainSeriesProperties.baselineStyle` | Stepline | `mainSeriesProperties.steplineStyle` | Bars | `mainSeriesProperties.barStyle` | Candles | `mainSeriesProperties.candleStyle` | Volume candles | `mainSeriesProperties.volCandlesStyle` | Area | `mainSeriesProperties.areaStyle` | HLC Area | `mainSeriesProperties.hlcAreaStyle` | HLC bars | `mainSeriesProperties.hlcBarsStyle` | Line With Markers | `mainSeriesProperties.lineWithMarkersStyle` | Hollow Candles | `mainSeriesProperties.hollowCandleStyle` | Heikin Ashi | `mainSeriesProperties.haStyle` | Columns | `mainSeriesProperties.columnStyle` | High-low | `mainSeriesProperties.hiloStyle` | Renko | `mainSeriesProperties.renkoStyle` | Line Break | `mainSeriesProperties.pbStyle` | Kagi | `mainSeriesProperties.kagiStyle` | Point-and-Figure | `mainSeriesProperties.pnfStyle` | You can also change the chart style properties on the fly. To do this, use the [`setChartStyleProperties`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISeriesApi#setchartstyleproperties) method. For example, the code sample changes the [properties](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CandleStylePreferences) of the Candles style. ```javascript widget.chart().getSeries().setChartStyleProperties(1, { upColor: '#10F9E0', downColor: '#1029F9', borderUpColor: '#10F9E0', borderDownColor: '#1029F9' }); ``` ![Change Candle style on the fly](https://www.tradingview.com/charting-library-docs/img/candle-style.png) Properties that can be changed using `setChartStyleProperties` are listed in interfaces like [`BarStylePreferences`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BarStylePreferences), [`RenkoStylePreferences`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RenkoStylePreferences), and [`AreaStylePreferences`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AreaStylePreferences). Refer to the [SeriesPreferencesMap](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SeriesPreferencesMap) page to see the list of such interfaces. ### Session Advanced Charts and Trading Platform support pre-market and post-market sessions. To enable them, you should set the [`mainSeriesProperties.sessionId`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiessessionid) to `"extended"`. For more information about the sessions, refer to [Trading Sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessions) and [Extended Sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions). ### Countdown On the price scale, you can display a countdown to the bar close. To do this, set the [`mainSeriesProperties.showCountdown`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesshowcountdown) property to `true`. Note that you should also implement the [`getServerTime`](https://www.tradingview.com/charting-library-docs/latest/api/additional-methods#getservertime) method to display the countdown. ### Price line You can specify a price line using the following properties: Property | Description | ---------|----------| [`mainSeriesProperties.showPriceLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesshowpriceline) | Main series price line visibility. | [`mainSeriesProperties.priceLineWidth`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiespricelinewidth) | Main series price line width. | [`mainSeriesProperties.priceLineColor`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiespricelinecolor) | Main series price line color. | ### Additional lines Advanced Charts and Trading Platform include additional lines that can be displayed on the chart. You can enable them using the toggle properties in the table below. For each line, there is a group of properties that you can specify to adjust this line. Properties of one group have the same name pattern. You can use these patterns to find properties for a certain line on the [ChartPropertiesOverrides](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides) page. Line | Toggle | Name patterns | ---------|----------| ----------| Bid/ask | [`mainSeriesProperties.bidAsk.visible`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesbidaskvisible) |`mainSeriesProperties.bidAsk` | High/low price | [`highLowAvgPrice.highLowPriceLinesVisible`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertieshighlowavgpricehighlowpricelinesvisible) | `mainSeriesProperties.highLowAvgPrice` | Previous close price | [`mainSeriesProperties.showPrevClosePriceLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesshowprevclosepriceline) |`mainSeriesProperties.prevClosePrice` | ### minTick The [`minTick`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesmintick) property allows you to change the [`pricescale`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#pricescale), [`minmov`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#minmov), and [`fractional`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#fractional) properties for the current symbol at once. For more information about these properties, refer to [Price Format](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologyprice-format). All `minTick` possible values are represented below as objects for better readability: ```text { priceScale: 1, minMove: 1, frac: false }, { priceScale: 10, minMove: 1, frac: false }, { priceScale: 100, minMove: 1, frac: false }, { priceScale: 1000, minMove: 1, frac: false }, { priceScale: 10000, minMove: 1, frac: false }, { priceScale: 100000, minMove: 1, frac: false }, { priceScale: 1000000, minMove: 1, frac: false }, { priceScale: 10000000, minMove: 1, frac: false }, { priceScale: 100000000, minMove: 1, frac: false }, { priceScale: 2, minMove: 1, frac: true }, { priceScale: 4, minMove: 1, frac: true }, { priceScale: 8, minMove: 1, frac: true }, { priceScale: 16, minMove: 1, frac: true }, { priceScale: 32, minMove: 1, frac: true }, { priceScale: 64, minMove: 1, frac: true }, { priceScale: 128, minMove: 1, frac: true }, { priceScale: 320, minMove: 1, frac: true }, ``` If you want to reset the `pricescale`, `minmov`, and `fractional` properties to their values initialized in [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo), set `minTick` to `"default"`. Specify the [`mainSeriesProperties.minTick`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesmintick) property as demonstrated below: ```javascript // Set minTick to "default" tvWidget.applyOverrides({ "mainSeriesProperties.minTick": "default" }); // Set series' minTick to { priceScale: 10000, minMove: 1, frac: false } tvWidget.applyOverrides({ "mainSeriesProperties.minTick": "10000,1,false" }); // Set minTick for overlay studies to { priceScale: 10000, minMove: 1, frac: false } tvWidget.applyStudiesOverrides({ "overlay.minTick": "10000,1,false" }); ``` ## Time zone If you want to change a time zone that is set in [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor), you should use the [`timezone`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#timezone) property. ```javascript tvWidget.applyOverrides({ "timezone": "Europe/Belgrade"}); ``` ## Trading Platform You can use `tradingProperties` to customize Trading Platform features such as orders and positions. Refer to the [Trading overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/trading-overridesadjust-display-of-trading-features) for more information. [price]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale [time]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale URL: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides ========================================================================================================== # Indicator overrides The [Overrides API](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides) includes properties that can be used to customize [indicators'](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators) parameters such as colors, line width, plot type, and more. This article contains the following information: - How to [customize indicators](#customize-indicators). - How to [customize new series](#customize-new-series). - How to get the [list](#list-of-overrides) of overrides for built-in indicators. - How to get the list of overrides for custom indicators based on [overrides syntax](#overrides-syntax). ## Customize indicators This section describes ways to customize indicators. :::tip Refer to [List of overrides](#list-of-overrides) to see properties for built-in indicators. ::: ### Specify default properties You should use the [`studies_overrides`] property of the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) to specify the indicator's default properties. For example, the following code sample specifies that all _Bollinger Bands_ indicators should be green with the upper line width set to 7. ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... studies_overrides: { "bollinger bands.median.color": "#33FF88", "bollinger bands.upper.linewidth": 7 } }); ``` ### Change default properties on the fly To change the indicator's default properties after the chart is initialized, use the [`applyStudiesOverrides`] method. All indicators created after the `applyStudiesOverrides` call have new properties. For example, the following code sample specifies that all newly created _Moving Average_ indicators should have the length set to 5. ```javascript widget.applyStudiesOverrides({ "moving average.length": 5 }) ``` ### Change the existing indicator If you want to change an indicator that is already on the chart, you should use the [`applyOverrides`] method in [`IStudyApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IStudyApi). For example, the code sample below specifies new properties for the existing _Volume_ indicator. ```javascript const volumeStudyId = widget.activeChart().getAllStudies().find(x => x.name === "Volume").id; const volume = widget.activeChart().getStudyById(volumeStudyId); volume.applyOverrides({ "volume.color.0": "pink", "volume.color.1": "purple" }); ``` ### Customize a single indicator If you need to change a style of only one indicator, you can create the indicator using the [`createStudy`] method and pass overrides properties as a parameter. These properties are applied above the [default ones](#specify-default-properties) that are specified in `studies_overrides`. For example, the code sample below specifies that _Moving Average_ indicators should be blue and creates one _Moving Average_ that is purple. ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... studies_overrides: { "moving average.plot.color": "rgb(0, 255, 255)" } }); widget.onChartReady(() => { widget.activeChart().createStudy("Moving Average", false, false, { length: 5 }, { "Plot.color": "rgb(150, 95, 196)" }, ) }); ``` Any property [from studies_overrides](#specify-default-properties) can be changed using `createStudy`. However, the properties listed below can be specified in `createStudy` but might not work in `studies_overrides` depending on the indicator and property. - `showPriceLine`: boolean - `showLabelsOnPriceScale`: boolean - `showLegendValues`: boolean - `transparency`: number - `precision`: string For example, you can specify the default transparency of the _Volume_ indicator via `studies_overrides`, but you can use only `createStudy` to disable labels on the price scale. ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... studies_overrides: { "volume.volume.transparency": 99 } }); widget.onChartReady(() => { widget.chart().createStudy("Volume", false, false, undefined, { "showLabelsOnPriceScale": false } }); ``` ## Customize new series Users can add new [series](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryseries) to the chart in the UI to compare symbols. To add a new series programmatically, you should use the _Overlay_ or _Compare_ indicator. For more information, refer to the [Indicators](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicatorsadd-and-compare-new-series) article. This section describes how to customize the _Overlay_ and _Compare_ indicators. ### Overlay You should use [`studies_overrides`] to specify default properties for all _Overlay_ indicators. ```javascript studies_overrides: { // ... "overlay.style": 1, // Candle "overlay.candleStyle.upColor": "purple" } ``` You can also create a singe _Overlay_ indicator with specific parameters as follows: ```javascript widget.activeChart().createStudy("Overlay", true, false, { symbol: "IBM" }, { "style": 2 // Line "lineStyle.color": "purple", } ); ``` Refer to [StudyOverrides](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyOverrides#overlayextendtimescale) or [OverlayIndicatorOverrides](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.OverlayIndicatorOverrides) to see a list of _Overlay_ overrides. ### Compare You can customize the _Compare_ indicator as follows: ```javascript studies_overrides: { // ... "compare.plot.color": "#000000", // Color of the line "compare.source": "high", // Price source "compare.minTick": "default" } ``` You can also create a singe _Compare_ indicator with specific parameters as follows: ```javascript widget.activeChart().createStudy("Compare", true, false, { symbol: "IBM" }, { "plot.color": "yellow" } ); ``` Refer to [StudyOverrides](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyOverrides#compareplotcolor) or [CompareIndicatorOverrides](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CompareIndicatorOverrides) to see a list of _Compare_ overrides. ## List of overrides Each indicator has a set of overrides that you can use to change its style. The [overrides syntax](#overrides-syntax) may or may not include the indicator's name depending on the method used. Refer to the pages below to see lists of overrides associated with the certain methods. - Use the properties listed in [`StudyOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyOverrides) to customize indicators via [`studies_overrides`] and [`applyStudiesOverrides`]. - Use the properties listed in [`SingleIndicatorOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#singleindicatoroverrides) to customize indicators via [`createStudy`] and [`applyOverrides`]. ```javascript var widget = window.tvWidget = new TradingView.widget({ studies_overrides: { // Includes the indicator's name "volume.volume.transparency": 99 } }); widget.onChartReady(() => { widget.chart().createStudy("Volume", false, false, undefined, { // Does not include the indicator's name "volume.transparency": 99 }) }); ``` Note that the pages above contain overrides for built-in indicators only. Refer to [Overrides syntax](#overrides-syntax) for information on how to specify overrides for custom indicators. ## Overrides syntax The overrides syntax is the same for built-in and [custom indicators]. For your convenience, overrides names for built-in indicators are generated, and the links to these overrides are listed [above](#list-of-overrides). For custom indicators, you need to figure out the overrides names based on the rules described in this section. ### Overview Overrides consist of the following parts that should be separated by a dot: - An indicator's name. The name should be the same as in the _Indicators_ dialog in the UI. Note that this part should be omitted if you specify overrides using [`createStudy`] and [`applyOverrides`]. Indicators dialog - A [path](#property-path) to the certain property. Property names are the same as in the _Settings_ dialog in the UI (in English). Indicators settings Both parts should be written in lower case, for example, `moving average.precision`. ### Property path A property path depends on a certain property and consists of lowercase identifiers separated by a dot. The properties and the corresponding path formats are described below. To see all properties of the certain indicator, you can call the [`getStudyStyles`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#getstudystyles) method. ```javascript widget.getStudyStyles("Moving Average"); ``` The code sample below shows the result of this call. Note that `getStudyStyles` does not return actual property names but the indicator's [metadata]. The values in metadata have names like `plot_0`, which are internal IDs for the plots within the indicator. However, you should take the plot's name used in the UI to refer to the plot properties. In the example below, the correct path to the `color` property is `plot.color` not `plot_0.color`. ```javascript { "defaults": { "styles": { // highlight-start // Plot properties "plot_0": { "display": 15, "linestyle": 0, "linewidth": 1, "plottype": 0, "trackPrice": false, "transparency": 0, "color": "#2196F3" }, // highlight-end "smoothedMA": { "display": 0, "linestyle": 0, "linewidth": 1, "plottype": 0, "trackPrice": false, "transparency": 0 } }, // ... "styles": { "plot_0": { // highlight-next-line "title": "Plot", // Plot name in the UI "histogramBase": 0, "joinPoints": false }, "smoothedMA": { "title": "Smoothed MA", "histogramBase": 0, "joinPoints": false } } } ``` #### Input property Format: `indicator_name.input_name` - **indicator_name**: use the name as you see it in the _Indicators_ dialog. - **input_name**: use the name as you see it in the _Settings_ dialog, for example, `show ma`. Examples: `volume.volume ma.visible`, `bollinger bands.length` You can call the [`getStudyInputs`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#getstudyinputs) method to see all input properties defined in the indicator's [metadata]. ```javascript widget.getStudyInputs("MACD"); ``` #### Plot property :::info **Plot** is a line or area that represents the indicator's values on the chart. ::: Format: `indicator_name.plot_name.property_name` - **indicator_name**: use the name as you see it in the _Indicators_ dialog. - **plot_name**: use the name as you see it in the _Settings_ dialog, for example, `volume` or `plot`. - **property_name**: one of the following: - **linewidth** - **visible**: boolean - **plottype**. Supported plot types are: - `line` - `histogram` - `cross` - `area` - `columns` - `circles` - `line_with_breaks` - `area_with_breaks` - `step_line` - `step_line_with_breaks` Examples: `volume.volume.linewidth`, `bollinger bands.median.linewidth` #### Plot color property Format: `indicator_name.plot_name.color<.color_index>` - **indicator_name**: use the name as you see it in the _Indicators_ dialog. - **plot_name**: use the name as you see it in the _Settings_ dialog, for example, `volume` or `plot`. - **color**: a keyword. - **color_index** (optional): color index (if any). It is just an ordinal number of a color for this plot. For example, to replace the color that is green by default for _Volume_, one should use `color_index = 1`. **Remark 1**: `color.0` is a synonym of `color`. Paths such as `volume.volume.color.0` and `volume.volume.color` are treated the same. **Remark 2**: The customization of area fill color and transparency is not supported currently. **Limitations**: - Only `#RRGGBB` format is supported for colors. Do not use a short format `#RGB`. - Transparency varies and the range is [0..100]. 100 means plot is fully opaque. - Thickness is an integer. #### Precision property You can change the default precision of indicators using the `indicator_name.precision` format. Example: `"average true range.precision": 8` ### Ambiguous identifiers When the library complains that there is an 'ambiguous identifier', it means that more than one property has that specific property name. This can be possible because there are a few different types (plots, bands, areas, inputs) for the properties and the name only needs to be unique amongst its own type. So there can be cases where the library can not determine which property to change based solely on the name. In these cases, you should use the 'colon type' syntax to specifically tell the library which type the property is within. The type should be specified at the end of the ambiguous name (just before the period) and can be one of the following types: - `:plot` - `:band` - `:area` - `:input` #### Example The _MA Cross_ indicator has both inputs and plots named 'Short' and 'Long'. The code sample below creates the _MA Cross_ indicator with the following visual changes: - Changes the inputs for Short and Long from 9 and 26 to 12 and 24, respectively. - Changes the width of the Short line and its type from 'line' to 'histogram'. - Hides the Long line from the chart. - Changes the type of Crosses from 'Cross' to 'Line'. ```js widget.activeChart().createStudy( "MA Cross", // Indicator's name false, // forceOverlay false, // lock false, // inputs // overrides { "short:input": 12, // Ambiguous; therefore, added :input "long:input": 24, // Ambiguous; therefore, added :input "short:plot.linewidth": 3, // Ambiguous; therefore, added :plot "short:plot.plottype": "histogram", // Ambiguous; therefore, added :plot "long:plot.display": 0, // Ambiguous; therefore, added :plot "Crosses.plottype": "line" } ); ``` [`createStudy`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createstudy [`applyOverrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IStudyApi#applyoverrides [`applyStudiesOverrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#applystudiesoverrides [`studies_overrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#studies_overrides [metadata]: https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo [custom indicators]: https://www.tradingview.com/charting-library-docs/latest/custom_studies URL: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/trading-overrides ======================================================================================================== # Trading overrides :::info Trading overrides are only available in [Trading Platform]. ::: This article explains how to use the [`trading_customization`](#customize-order-and-position-lines) property and the [Overrides API](#adjust-display-of-trading-features) to customize trading elements, including order and position lines, profit and loss information, and visibility settings. ## Customize order and position lines You can override the style of order and position lines using the [`trading_customization`] property of the [Widget Constructor]. This property is defined by the [`TradingCustomization`] interface, which offers four customization options: - `brokerOrder` and `brokerPosition` for lines created with the [Broker API](#created-with-broker-api). - `order` and `position` for lines created with [trading primitives](#created-with-trading-primitives). ### Created with Broker API The [Broker API] is a component that enables trading. When the chart is initially loaded, the library requests user's orders and positions from the Broker API implementation through the [`orders`] and [`positions`] methods. Order and position lines are displayed on the chart. You can override their style using the `brokerOrder` and `brokerPosition` properties of the [`trading_customization`] object. See [`BrokerOrderOverrides`] and [`BrokerPositionOverrides`] for full lists of override properties. ```js new TradingView.widget({ /* Other Widget Constructor properties */ trading_customization: { brokerOrder: { /* Override properties for order lines */ }, brokerPosition: { /* Override properties for position lines */ }, }, }) ``` The example below shows how to create order and position lines using the Broker API and customize their colors. Note that "normal" in the property name indicates the line is active and visible in the UI, while "disabled" means the line is inactive, such as when another dialog is open. ### Created with trading primitives :::caution Starting from version 29, the methods for creating trading primitives are only available in [Trading Platform]. ::: [Trading primitives] is a low-level mechanism for creating order and position lines using the [`createOrderLine`] and [`createPositionLine`] methods. You can override the style of these lines using the `order` and `position` properties within the [`trading_customization`] object. See [`OrderLineToolOverrides`] and [`PositionLineToolOverrides`] for full lists of override properties. ```js new TradingView.widget({ /* Other Widget Constructor properties */ trading_customization: { order: { /* Override properties for order lines */ }, position: { /* Override properties for position lines */ }, } }) ``` The example below shows how to create order and position lines and customize their quantity text color, line color, style, and width. ## Adjust display of trading features The [Overrides API] offers properties to adjust the display, alignment, and style of profit and loss information, as well as manage the visibility of positions, orders, and execution details. The properties are listed on the [ChartPropertiesOverrides] page and their names start with `tradingProperties`. For example, you can hide profit and loss values for [bracket orders]. ```js widget.applyOverrides({ "tradingProperties.bracketsPL.visibility": false, }); ``` [bracket orders]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/brackets [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [`BrokerOrderOverrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerOrderOverrides [`BrokerPositionOverrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerPositionOverrides [ChartPropertiesOverrides]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#tradingpropertiesbracketspldisplay [`createOrderLine`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createorderline [`createPositionLine`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createpositionline [`OrderLineToolOverrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.OrderLineToolOverrides [`orders`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#orders [Overrides API]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides [`PositionLineToolOverrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PositionLineToolOverrides [`positions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#positions [`trading_customization`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#trading_customization [`TradingCustomization`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingCustomization [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [Trading primitives]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Trading-Primitives [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/customization/styles/CSS-Color-Themes ==================================================================================================== # CSS Color Themes :::caution This article describes a legacy method for adjusting the colors of UI elements such as toolbars and context menus. We recommend using the [Custom themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes) instead, as it provides greater flexibility and precision. ::: ## Connect the CSS file You can change the colors of UI elements with the [CSS custom properties](#list-of-css-custom-properties). To do this, you should specify these properties in a CSS file and connect the file to the library using the [`custom_css_url`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_css_url) property in the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor). See customization example in [themed.html](https) and [themed.css](https) files 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )). Use the following CSS selectors to specify colors depending on the theme: - `: root: not (.theme-dark)` — for the light theme - `.theme-dark: root` — for the dark theme
Expand to view the code sample that sets up the pink widget for both light and dark theme. ```css :root:not(.theme-dark) { --tv-color-platform-background: #d1c4e9; --tv-color-pane-background: rgb(251, 223, 244); --tv-color-toolbar-button-background-hover: rgb(244, 143, 177); --tv-color-toolbar-button-background-expanded: rgb(244, 143, 177); --tv-color-toolbar-button-background-active: rgb(249, 185, 233); --tv-color-toolbar-button-background-active-hover: rgb(244, 143, 177); --tv-color-toolbar-button-text: rgb(136, 24, 79); --tv-color-toolbar-button-text-hover: rgb(74, 20, 140); --tv-color-toolbar-button-text-active: red; --tv-color-toolbar-button-text-active-hover: red; --tv-color-item-active-text: rgb(6, 6, 255); --tv-color-toolbar-toggle-button-background-active: red; --tv-color-toolbar-toggle-button-background-active-hover: magenta; --tv-color-toolbar-divider-background: rgb(251, 223, 244); --tv-color-toolbar-save-layout-loader: rgb(106, 109, 120); --tv-color-popup-background: rgb(241, 188, 225); --tv-color-popup-element-text: rgb(136, 24, 79); --tv-color-popup-element-text-hover: rgb(74, 20, 140); --tv-color-popup-element-background-hover: rgb(244, 143, 177); --tv-color-popup-element-divider-background: rgb(251, 223, 244); --tv-color-popup-element-secondary-text: rgb(74, 20, 140); --tv-color-popup-element-hint-text: rgb(74, 20, 140); --tv-color-popup-element-text-active: rgb(6, 6, 255); --tv-color-popup-element-background-active: red; --tv-color-popup-element-toolbox-text: rgb(136, 24, 79); --tv-color-popup-element-toolbox-text-hover: rgb(74, 20, 140); --tv-color-popup-element-toolbox-text-active-hover: rgb(74, 20, 140); --tv-color-popup-element-toolbox-background-hover: rgb(222, 89, 132); --tv-color-popup-element-toolbox-background-active-hover: magenta; } .theme-dark:root { --tv-color-platform-background: #d1c4e9; --tv-color-pane-background: rgb(251, 223, 244); --tv-color-toolbar-button-background-hover: rgb(244, 143, 177); --tv-color-toolbar-button-background-expanded: rgb(244, 143, 177); --tv-color-toolbar-button-background-active: rgb(249, 185, 233); --tv-color-toolbar-button-background-active-hover: rgb(244, 143, 177); --tv-color-toolbar-button-text: rgb(136, 24, 79); --tv-color-toolbar-button-text-hover: rgb(74, 20, 140); --tv-color-toolbar-button-text-active: red; --tv-color-toolbar-button-text-active-hover: red; --tv-color-item-active-text: rgb(6, 255, 6); --tv-color-toolbar-toggle-button-background-active: red; --tv-color-toolbar-toggle-button-background-active-hover: magenta; --tv-color-toolbar-divider-background: rgb(251, 223, 244); --tv-color-toolbar-save-layout-loader: rgb(134, 137, 147); --tv-color-popup-background: rgb(241, 188, 225); --tv-color-popup-element-text: rgb(136, 24, 79); --tv-color-popup-element-text-hover: rgb(74, 20, 140); --tv-color-popup-element-background-hover: rgb(244, 143, 177); --tv-color-popup-element-divider-background: rgb(251, 223, 244); --tv-color-popup-element-secondary-text: rgb(74, 20, 140); --tv-color-popup-element-hint-text: rgb(74, 20, 140); --tv-color-popup-element-text-active: rgb(6, 6, 255); --tv-color-popup-element-background-active: red; --tv-color-popup-element-toolbox-text: rgb(136, 24, 79); --tv-color-popup-element-toolbox-text-hover: rgb(74, 20, 140); --tv-color-popup-element-toolbox-text-active-hover: rgb(74, 20, 140); --tv-color-popup-element-toolbox-background-hover: rgb(222, 89, 132); --tv-color-popup-element-toolbox-background-active-hover: magenta; } ```
## Adjust properties on the fly To change or get the [CSS custom properties](#list-of-css-custom-properties) values at runtime, use the [`setCSSCustomProperty`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#setcsscustomproperty) or [`getCSSCustomPropertyValue`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#getcsscustompropertyvalue) methods, respectively. ```javascript widget.setCSSCustomProperty('--tv-color-pane-background', 'rgb(251, 223, 244)') ``` You can also use these methods to adjust your own variables defined in the [CSS file](#connect-the-css-file). ## List of CSS custom properties - `--tv-color-platform-background` — the main color of the page where all elements are placed on - `--tv-color-pane-background` — toolbar background color - `--tv-color-toolbar-button-background-hover` — hover effect color for a toolbar button - `--tv-color-toolbar-button-background-expanded` — hover effect color for the active button on the right toolbar - `--tv-color-toolbar-button-background-active` — background color for the active button on the right toolbar - `--tv-color-toolbar-button-background-active-hover` — background color for the active button on the right toolbar when hovering over it - `--tv-color-toolbar-button-text` — text and icon color for toolbar buttons - `--tv-color-toolbar-button-text-hover` — text and icon color for toolbar buttons when hovering over them - `--tv-color-toolbar-button-text-active` — text and icon color for toolbar buttons that are active - `--tv-color-toolbar-button-text-active-hover` — text and icon color for toolbar buttons that are active when hovering over them - `--tv-color-item-active-text` — text color for toggle toolbar buttons (e.g. Magnet Mode, Lock All Drawings) - `--tv-color-toolbar-toggle-button-background-active` — fill color for toggle toolbar buttons (e.g. Magnet Mode, Lock All Drawings) - `--tv-color-toolbar-toggle-button-background-active-hover` — fill color for toggle toolbar buttons when hovering over them (e.g. Magnet Mode, Lock All Drawings) - `--tv-color-toolbar-divider-background` — toolbar dividers color - `--tv-color-toolbar-save-layout-loader` — loader color for toolbar save layout button ### Pop-up menu properties Pop-up and pop-over menus appear when the user clicks on a toolbar icon. The pop-over menu typically presents a list of tools, options, or commands that are relevant to the context of the icon or the current user task. These styling options are also applied for context menus. - `--tv-color-popup-background` - `--tv-color-popup-element-text` - `--tv-color-popup-element-text-hover` - `--tv-color-popup-element-background-hover` - `--tv-color-popup-element-divider-background` - `--tv-color-popup-element-secondary-text` - `--tv-color-popup-element-hint-text` - `--tv-color-popup-element-text-active` - `--tv-color-popup-element-background-active` - `--tv-color-popup-element-toolbox-text` - `--tv-color-popup-element-toolbox-text-hover` - `--tv-color-popup-element-toolbox-text-active-hover` - `--tv-color-popup-element-toolbox-background-hover` - `--tv-color-popup-element-toolbox-background-active-hover` ### Buy/Sell buttons properties Use Chrome DevTools to inspect the code and identify CSS variables that allow styling the [Buy/Sell buttons](https://www.tradingview.com/charting-library-docs/latest/trading_terminalbuysell-buttons-and-lines). For example, you can specify the color of the Sell button as follows: ```css :root:not(.theme-dark) { --themed-color-sell-btn-chart: rgb(251, 223, 244); } ``` URL: https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes ================================================================================================= # Custom themes API ## Overview A theme is a set of colors arranged to create a cohesive visual design of the widget. Themes change the colors of UI elements inside and outside the chart. The library ships with the [light and dark themes](https://www.tradingview.com/charting-library-docs/latest/customization/theme) that use the [default color palette](#default-color-palette). :::info The library supports only the light and dark themes. It is not possible to create an additional theme at the moment. ::: The Custom themes API allows you to override the default colors in the palette for the light and dark themes. In this way, you can change the colors of the following UI elements: - Toolbars - Dialogs - Context menus - Tooltips - Buttons - Chart background - Main series bars - Grid - Axes The example below shows a chart with a custom light theme applied. ## Default color palette The Custom themes API overrides colors in the library’s default palette. To better understand how to work with the API, consider the demo below. It shows the default palette and where each color is applied. The default palette contains seven colors, in addition to black and white. Each color comes with 19 shades, ranging from the lightest to the darkest. Shades of one color are assigned to different UI elements. For example, light gray is used for the toolbar separators, while dark gray is applied to the tooltips. The demo allows you to identify the original colors of certain UI elements and test your colors on the chart. Click any color in the palette and specify a new one using the color picker. Changes in the palette will be applied to the chart. Therefore, if you change blue, all the elements that originally use it, for example buttons in the dialogs, will adopt the new color. The currently applied colors are represented in the JSON format. You can use this code later to [specify your custom palette](#specify-custom-palettes) with the Custom themes API. ## Specify custom palettes To specify palettes for the light and dark themes, create a [`CustomThemes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CustomThemes) object and assign it to the [`custom_themes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_themes) property of the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor). As mentioned in the previous [section](#default-color-palette), a color palette should contain seven colors, each with 19 shades. The palette is configured in the [`CustomThemeColors`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CustomThemeColors) object that contains the following properties: Property name | Definition | ---------|----------| `color1` | Blue by default | `color2` | Grey by default | `color3` | Red by default | `color4` | Green by default | `color5` | Orange by default | `color6` | Purple by default | `color7` | Yellow by default | To override a default color, create an array of color strings from the lightest to the darkest and assign it to the corresponding property. You can also specify colors used instead of black and white. If any color is not provided, the default one will be used. ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... custom_themes: { // The new palette for the light theme light: { // Color that overrides blue "color1": ["#eaefff", "#d4e0ff", "#bfd0ff", "#a9c0ff", "#94b1ff", "#7fa1ff", "#6991ff", "#5481ff", "#3e72ff", "#2962ff", "#2558e6", "#214ecc", "#1d45b3", "#193b99", "#153180", "#102766", "#0c1d4d", "#081433", "#040a1a"], // Color that overrides grey "color2": ["#f2f2f3", "#e4e5e7", "#d7d7db", "#c9cacf", "#bcbdc3", "#aeb0b6", "#a1a3aa", "#93959e", "#868892", "#787b86", "#6c6f79", "#60626b", "#54565e", "#484a50", "#3c3e43", "#303136", "#242528", "#18191b", "#0c0c0d"], // Color that overrides red "color3": ["#feebec", "#fcd7da", "#fbc3c7", "#faafb5", "#f99ba2", "#f7868f", "#f6727d", "#f55e6a", "#f34a58", "#f23645", "#da313e", "#c22b37", "#a92630", "#912029", "#791b23", "#61161c", "#491015", "#300b0e", "#180507"], // Color that overrides green "color4": ["#e6f5f2", "#ceebe6", "#b5e0d9", "#9cd6cd", "#84ccc0", "#6bc2b3", "#52b8a7", "#39ad9a", "#21a38e", "#089981", "#078a74", "#067a67", "#066b5a", "#055c4d", "#044d41", "#033d34", "#022e27", "#021f1a", "#010f0d"], // Color that overrides orange "color5": ["#fff5e6", "#ffeacc", "#ffe0b3", "#ffd699", "#ffcc80", "#ffc166", "#ffb74d", "#ffad33", "#ffa21a", "#ff9800", "#e68900", "#cc7a00", "#b36a00", "#995b00", "#804c00", "#663d00", "#4d2e00", "#331e00", "#1a0f00"],, // Color that overrides purple "color6": ["#f5e9f7", "#ebd4ef", "#e1bee7", "#d7a9df", "#ce93d8", "#c47dd0", "#ba68c8", "#b052c0", "#a63db8", "#9c27b0", "#8c239e", "#7d1f8d", "#6d1b7b", "#5e176a", "#4e1458", "#3e1046", "#2f0c35", "#1f0823", "#100412"], // Color that overrides yellow "color7": ["#fffdeb", "#fffbd8", "#fff9c4", "#fff7b1", "#fff59d", "#fff389", "#fff176", "#ffef62", "#ffed4f", "#ffeb3b", "#e6d435", "#ccbc2f", "#b3a529", "#998d23", "#80761e", "#665e18", "#4d4712", "#332f0c", "#1a1806"], "white": "#f2e6ff", "black": "#421b50" }, dark: { "color1": ["#f7dfd5", "#f3cfc0", "#efbfaa", "#ebaf95", "#e89f80", "#e48f6b", "#e07f56", "#dc6f41", "#d85f2b", "#d03f01", "#bf3a01", "#ad3501", "#9c2f01", "#8b2a01", "#792501", "#682001", "#571a00", "#451500", "#341000"], "color2": ["#f1dede", "#eacdcd", "#e2bcbc", "#dbacac", "#d49b9b", "#cd8a8a", "#c67a7a", "#bf6969", "#b75858", "#a93737", "#9b3232", "#8d2e2e", "#7f2929", "#712525", "#632020", "#551c1c", "#461717", "#381212", "#2a0e0e"], "color3": ["#ffe1e1", "#ffd3d3", "#ffc4c4", "#ffb5b5", "#ffa6a6", "#ff9797", "#ff8888", "#ff7a7a", "#ff6b6b", "#ff4d4d", "#ea4747", "#d54040", "#bf3a3a", "#aa3333", "#952d2d", "#802727", "#6a2020", "#551a1a", "#401313"], "color4": ["#e6fff7", "#d9fff2", "#ccffee", "#bfffea", "#b3ffe6", "#a6ffe1", "#99ffdd", "#8cffd9", "#80ffd5", "#66ffcc", "#5eeabb", "#55d5aa", "#4dbf99", "#44aa88", "#3c9577", "#338066", "#2b6a55", "#225544", "#1a4033"], "color5": ["#ffffe0", "#feffd1", "#feffc2", "#feffb2", "#feffa3", "#fdff94", "#fdff84", "#fdff75", "#fdff66", "#fcff47", "#e7ea41", "#d2d53b", "#bdbf35", "#a8aa2f", "#939529", "#7e8024", "#696a1e", "#545518", "#3f4012"], "color6": ["#ffe2ff", "#ffd4ff", "#ffc5ff", "#ffb7ff", "#ffa9ff", "#ff9aff", "#ff8cff", "#ff7dff", "#ff6fff", "#ff52ff", "#ea4bea", "#d544d5", "#bf3ebf", "#aa37aa", "#953095", "#802980", "#6a226a", "#551b55", "#401540"], "color7": ["#dff1ff", "#cfeaff", "#bee3ff", "#aedcff", "#9ed5ff", "#8eceff", "#7ec7ff", "#6ec0ff", "#5db9ff", "#3dabff", "#389dea", "#338fd5", "#2e80bf", "#2972aa", "#246495", "#1f5680", "#19476a", "#143955", "#0f2b40"], "white": "#ffffff", "black": "#000000" } } }); ``` Note that changing a color in the palette might affect multiple UI elements. To tweak a color of a certain element, for example the [_Price Scale_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale), use the [Overrides API](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides) that applies above the palette colors. Refer to the [Customization precedence](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedence) article for more information on customization approaches and their priorities. ## Manage palettes To manage custom palettes after the chart is initialized, you should call the [`customThemes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#customthemes) method. This method returns an instance of the [`ICustomThemesApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ICustomThemesApi) interface that provides an extensive API for controlling the palettes. ### Change palette on the fly Call the [`applyCustomThemes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ICustomThemesApi#applycustomthemes) method and pass a [`CustomThemes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CustomThemes) object as a parameter. ```javascript let customThemesAPI = (await widget.customThemes()); customThemesAPI.applyCustomThemes(customThemes); ``` ### Reset palettes Call the [`resetCustomThemes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ICustomThemesApi#resetcustomthemes) method as follows: ```javascript let customThemesAPI = (await widget.customThemes()); customThemesAPI.resetCustomThemes(); ``` ### Disable the API You can disable the Custom themes API with the [`library_custom_color_themes`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetslibrary_custom_color_themes) featureset. If you try to call the API in this case, the following error occurs: _The library_custom_color_themes feature must be enabled to use the Custom themes API_. ## API limitations The following colors cannot be changed with the Custom themes API: - Blue and red in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager) - Green, orange, and blue in the [Market Status](https://www.tradingview.com/charting-library-docs/latest/ui_elements/market-status) - Green in the [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminaldetails) URL: https://www.tradingview.com/charting-library-docs/latest/customization/styles =================================================================================== # Styles You can customize the colors of the chart so that it matches your site design. Consider the following articles for more information: - [Custom themes](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes) — specify your custom color palette for the light and dark themes. - [Chart colors](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides) — specify colors elements on the chart such as panes and bars. URL: https://www.tradingview.com/charting-library-docs/latest/customization/theme ================================================================================== # Theme The library supports dark and light themes. Use the [`theme`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#theme) parameter in [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) to specify a theme. The default value is `light`. The chart layout does not contain buttons to switch the theme in the UI. Therefore, users cannot switch the theme unless you develop this option outside the library. :::tip If you want to override the default colors of the light and dark themes, you can use the [Custom themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes). ::: ## Theme switching You should switch the chart's theme when the theme of your website changes. To do this, use the [`changeTheme`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#changetheme) method that changes the theme on the fly. ```javascript widget.onChartReady(function() { widget.changeTheme("dark"); }); ``` You can call the [`getTheme`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#gettheme) method to get the current theme. Note that the `theme` value is stored in the chart's configuration. Therefore, if you restore the chart that has the dark theme, you may see a black chart background in the light theme. In this case, you should apply the theme once again using the [`changeTheme`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#changetheme) method. ![Theme is not fully applied](https://www.tradingview.com/charting-library-docs/img/theme-issue.png) URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/Best-Practices ============================================================================================= # Best Practices This article describes the best practices for integrating the library into your website or mobile application. ## Separate Additional Features from the Library The library is used to display charts, prices, and technical analysis tools. You can find a list of included features in the [Key features](https://www.tradingview.com/charting-library-docs/latest/getting_started/Key-Features) article. If you need additional features like chats, special symbol lists, hot deals, advertisements, etc., you should implement them outside of the library. You can still integrate them to the library using the [API](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi). ## Choose an Appropriate Data Connection Approach Pay attention to the differences between implementing a datafeed in JavaScript via the [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api) and using the predefined implementation with a server that responds in the [UDF](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF) format. Refer to the following topic for more information: [Connecting Data](https://www.tradingview.com/charting-library-docs/latest/connecting_data). If you need really fast data updates or data streaming, you can use WebSockets. ## Provide Correct Amount of Data Most issues with the library appear because data is provided incorrectly. Consider the following topic for more information: [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#correct-amount-of-data). Note that when you specify [Marks](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Marks), you should provide data that matches the requested range. ## Consider the Chart's Size The smallest meaningful size that the library supports is 500×500 px. Avoid making charts smaller because they look messy. We recommend that you hide some UI elements if you need charts smaller than those mentioned above. Refer to the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructorchart-size) topic for more information on how to specify the chart's size. ## Localize Your Chart The library [supports a variety of languages](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Localization). Use the one that fits your users' needs. ## Enable Debug Logs during Development Set the [`debug`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#debug) property to `true` in [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) to enable logs. We recommend that you enable the debug mode during the development and disable this mode in the production to speed up the code execution. ## If You Face Issues First, you should [update](https://www.tradingview.com/charting-library-docs/latest/releases/Update-Library) your library's build to the latest version. If the issues still appear, the steps below can help you to debug them: 1. Set the [`debug`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#debug) property to `true` in Widget Constructor to enable logs. 2. Check that you [provide data correctly](#provide-correct-amount-of-data). Pay special attention to [symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology) as it is the most common place to make a mistake. 3. Review the output of our [demo data service](https) and compare this output to yours to ensure your backend behaves correctly. You can also search your issue among the [GitHub Issues](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )). ## Avoid Using Undocumented Features All features that are not mentioned in the documentation are subject to change without any warnings and backward compatibility. Also, altering the source code is strictly prohibited by the legal agreement you signed. ## Avoid Using Demo Datafeed on a Production Website The demo datafeed is not designed for real usage. It might be unstable and cannot withstand high loads. ## Speed Up Load Times We recommend that you use the following protocols to speed up load times: - HTTP/2 or higher - TLS 1.3 or higher Also, you can compress the library's HTML files using Gzip or Brotli when sending them to a client. ## Set Minimum Expiration Time for charting_library.js All files in the library contain hash in their names except `charting_library.js` that you add to your HTML files. When you update the library to a newer version, all file names are changed as well. If a browser loads `charting_library.js` from the cache, then all the links in this file are broken. The expiration time for this file should be set to the minimum to prevent its caching. URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/Frequently-Asked-Questions ========================================================================================================= # Frequently Asked Questions import ThemedImage from '@theme/ThemedImage'; import useBaseUrl from '@docusaurus/useBaseUrl'; If your question is not outlined below, you can ask it on [GitHub Issues](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )). ## Data Management
1. How do I connect my data? How to add new symbols? Refer to the following articles for information on how to connect data: - [Connecting Data](https://www.tradingview.com/charting-library-docs/latest/connecting_data) - [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api) - [UDF](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF) Also, consider the [Datafeed: Common Issues](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues) article to avoid typical errors when implementing the Datafeed API. Use the [Demo Chart](https) to investigate how the library processes data. Open the Network tab in a browser console and filter requests by `demo-feed` to see all data requests and responses.
2. Do you have an example of the Datafeed API implementation? You can consider [UDF Adapter](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )) as an example of the Datafeed API implementation. If you need a step-by-step guide, refer to the [How to connect data via Datafeed API] tutorial.
3. Do you have an example of a WebSocket data transport? The [How to connect data via Datafeed API] tutorial shows how to stream data using WebSocket.
4. Do you have an example of a backend datafeed in ASP.NET, Python, PHP, etc. ? The only example of a backend datafeed that we have is written in JavaScript for Node.js. For more information, refer to the [yahoo_datafeed](https) repository.
5. How can I display data stored in a TXT/CSV/XLSX file? The library is intended to display data from a server, not a file. You should also keep in mind that according to the license agreement you can use the library on public websites only. If you still want to use a file as a data source, complete the following steps: 1. Write an application using any server language (.NET, PHP, Node.js, Python, etc.). This application should read a file and transfer data from it in the [UDF](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF) format over HTTP(S). Note: You can provide data in another format or use a WebSocket to transfer it, but in this case you need a custom [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api) implementation. 2. Make sure a browser can send requests to your server. For this, you should either have a static IP or register a domain. 3. Open `index.html` and replace `demo_feed.tradingview.com` with the URL to your server.
6. Why my data is not displayed / displayed incorrectly / incorrectly fetched from the server? The first thing you should do to debug any issue is to [enable console logs](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#debug). These logs contain the most important actions performed in the library. You can also refer to the [Datafeed: Common Issues](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues) article that might answer your question. Note that most data issues occur because symbol information is set incorrectly. To avoid these issues, consider [Symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology).
7. The library is constantly asking for data. How to tell it that the data is over? To do this, you should use a flag that notifies the library that there is no more data on the server. Set the status code to `no_data` or the [`noData`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.HistoryMetadata#nodata) property to `true` if you use [UDF](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDFbars) or [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#correct-amount-of-data), respectively.
8. How to change the number of decimal places for prices on the chart? The number of decimal places depends on the [`pricescale`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#pricescale) value. For more information on the price format, refer to the [Symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologyprice-format) article.
9. What if I have a single price for each timestamp? Since the library is intended to display multiple data types like candles, bars, and histograms, you are supposed to provide Open, High, Low, Close, and optional Volume for each timestamp. If you have a single price for each timestamp, you can pass `Open = High = Low = Close = price`. For better data visualization, you can change the default chart style to “Line” (refer to the [GUI](#gui) section).
10. Why is `unsubscribeBars` called with a delay? This is intentional. Refer to the [`unsubscribeBars`](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#unsubscribebars) method for more information.
11. How to specify time properties within the library? All time properties should be [Unix timestamps](https) in **seconds** unless otherwise stated. For example, the code sample below specifies boundary values of a time range. ```javascript const from = Date.now() / 1000 - 500 * 24 * 3600; // 500 days ago const to = Date.now() / 1000; ```
12. Does the library support the FIX protocol? Advanced Charts / Trading Platform is a browser-based client-side solution. You can implement your backend data connection with any instruments, including the FIX protocol, based on your requirements. However, the library does not provide any pre-made data integrations with the FIX protocol. The diagram below illustrates the data connection layers. You should integrate the FIX protocol between your backend and the data provider.
## GUI
1. How can I subscribe to chart events? You can subscribe to chart events in two ways: - Subscribe to [general](https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methodssubscribe--unsubscribe) events that are related to a whole chart layout, not a specific chart. - Subscribe to events that are related to a [single](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#methods) chart such as [`isSelectBarRequested`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#isselectbarrequested). Some methods that expose events only allow a subscription to be created by passing a single callback function, others return a [Subscription](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Broker.ISubscription) object that can be used to subscribe and unsubscribe.
2. How to change the default bar style? You can use the [`mainSeriesProperties.style`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#mainseriespropertiesstyle) property to customize bar style. Refer to the [Chart Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrideschart-styles) article for information.
3. How to customize the chart style? The library provides extensive customization options through multiple APIs. Refer to the [Customization](https://www.tradingview.com/charting-library-docs/latest/customization) section for more information.
4. How can I change the list of resolutions (time intervals) on the chart / disable them? Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolutionconfigure-resolutions-in-datafeed) article for more information.
5. How to enable the resolution in seconds? Refer to the [Resolution in seconds](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolutionresolution-in-seconds) section for more information.
6. How to hide a GUI element (symbol, interval, button, etc.)? Most of GUI elements can be hidden using [featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets). There are base elements that cannot be hidden, but if you still want to get rid of them, you can use [CSS customization](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_css_url). Note that names, classes, and identifiers of the DOM elements may be changed in the next versions of the product without any notifications.
7. How to disable the built-in Account Manager or Order Ticket? Use the [`trading_account_manager`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetstrading_account_manager) or [`order_panel`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsorder_panel) featureset to disable the built-in Account Manager or Order Ticket, respectively. For detailed guide on each component, refer to the dedicated section: - [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-managerdisable-account-manager) - [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticketimplement-custom-order-ticket) If you want to implement a custom component instead, you can still use the [Broker API](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-conceptsbroker-api) to populate this component with data.
8. Why do the Buy/Sell buttons not work? The *Buy/Sell* buttons may appear inactive or non-working for several reasons. - **Buttons are not visible at all.** Make sure you are using the [Trading Platform], as the *Buy/Sell* buttons are only available there. Additionally, check the UI setting under *Settings → Trading → Buy/Sell buttons* and ensure the checkbox is enabled. If this setting is turned off, the buttons will not appear on the chart. - **Buttons are disabled.** Ensure that the [`isTradable`] method returns `true` for tradable symbols. Without this method, the buttons remain disabled. - **Buttons are enabled but show no prices.** Implement the [`symbolInfo`] method to provide the required symbol data. Without it, the buttons will not display bid/ask prices. - **Clicking buttons doesn't place orders**. Implement [`placeOrder`] and other required methods of the Broker API. - **Prices in buttons are not updating.** To show real-time bid/ask prices in the buttons, implement the [`getQuotes`] method.
9. Can I add custom buttons to areas of the UI other than the top toolbar? Custom buttons created with [`createButton`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#createbutton) and [`createDropdown`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#createdropdown) can only be added to the [top toolbar](https://www.tradingview.com/charting-library-docs/latest/ui_elementstop-toolbar). However, there are other ways to customize the UI: you can add extra buttons to the [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) and [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket), or [modify other elements](https://www.tradingview.com/charting-library-docs/latest/customization) to tailor the interface to your needs.
10. Why an indicator is not plotted when the resolution is changed? Indicators, such as *VWAP* and *Pivot Points*, use extensive historical data to calculate their values and may need more bars than are visible on the chart. These indicators are plotted only after the library gets all required data. The library does not prefetch all data to avoid excessive requests. Therefore, when the resolution is changed, users need to scroll the chart for the indicator to appear.
## Localization
1. What languages does the library support? How can I add the language that is not supported? The library supports a variety of languages. You can find the complete list in the [Localization](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Localizationsupported-languages) article. Note that it is impossible to add your own language support.
2. Could you provide the list of all UI strings so I can translate them? We cannot provide the list of UI strings. However, if you want to add custom translations, you can use the [`custom_translate_function`] property of the [Widget Constructor].
## Other Questions
1. What is the difference between Widget, Advanced Charts, and Trading Platform? - [Widget](https) is connected to the TradingView data. Perfect for websites, blogs, and forums where you need a fast & free solution. Integration is simply copying & pasting pre-made iframe code. Widget has lots of display modes. - [Advanced Charts](https) is a chart with your data. This is a standalone solution that you download, host on your servers, and connect your data to. You can use it in your site/app for free. - [Trading Platform](https) is a standalone product that is licensed to brokers. It contains all features available in Advanced Charts and also includes trading functionality, multiple-chart layouts, watchlists, details, news widgets, and other advanced tools. Trading Platform has its own licensing fees associated with it.
2. Does TradingView have access to any user data through the integration? No, TradingView does not collect any user data. Advanced Charts and Trading Platform are self-hosted solutions that run independently on your servers, ensuring there is no interaction with TradingView on user data.
3. Is there a way to see detailed logs when working with the library? Yes, you can enable debug modes that provide detailed logs for data connection and trading features. For more information, refer to [How to enable debug mode](https://www.tradingview.com/charting-library-docs/latest/tutorials/enable-debug-mode).
4. What should I do if I encounter a bug while using the library? If you come across a bug or issue while using the library, we recommend taking the following steps: 1. **Check for updates**. Ensure that you are using the latest version of the library. Sometimes, bugs are resolved in newer releases. If you are not using the most recent version, [update the library](https://www.tradingview.com/charting-library-docs/latest/releases/Update-Library) before proceeding further. 2. **Reproduce the bug**. After updating to the latest version, attempt to replicate the bug. This step helps determine whether the issue persists in the updated version. 3. **Report the issue**. If the bug persists even after updating to the latest version, report it in [GitHub issues](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )). Provide detailed information about the issue, including steps to reproduce it, the library version, console logs, and any error messages encountered. This allows us to investigate and address the issue promptly.
5. Is it possible to reduce the size of the library? Yes. You can remove locales from the [bundle file](https://www.tradingview.com/charting-library-docs/latest/getting_started/Package-Contentpackage-content) if your app does not support them.
6. How do I add a custom indicator? Refer to [Custom indicators](https://www.tradingview.com/charting-library-docs/latest/custom_studies) for more information.
7. Does the library support Rocket Loader by Cloudflare? No, it does not. Please avoid using Rocket Loader.
8. Do you provide iOS or Android SDKs like you do for Lightweight Charts? No, not currently. However, we have a collection of [integration examples] for frameworks commonly used with Advanced Charts and Trading Platform. You can check the following examples: - [iOS WKWebView in Swift](https) - [Android WebView](https) - [React Native for iOS and Android](https)
9. How to integrate the library with Flutter? We do not have an example for integrating the library with Flutter currently. You can consider the [How to Build a Native Communication Bridge in Flutter with WebView and JavaScript](https) article that explains how to use Flutter with WebView and JavaScript.
10. How to switch from Advanced Charts to Trading Platform? Refer to the [How to migrate from Advanced Charts](https://www.tradingview.com/charting-library-docs/latest/trading_terminalhow-to-migrate-from-advanced-charts) topic for more information.
11. Is it possible to use Pine Script® for creating and editing indicators? [Pine Script®](https) is not supported in Advanced Charts or Trading Platform. Alternatively, you can create your custom indicator using JavaScript. For more information, refer to [Custom indicators](https://www.tradingview.com/charting-library-docs/latest/custom_studies).
12. Why Advanced Charts / Trading Platform differs from tradingview.com? Some features and parts of the UI in the libraries may differ from those on [tradingview.com](https). Since Advanced Charts and Trading Platform are client-side solutions, they do not support features that rely on server-side logic. Refer to the [Unsupported features](https://www.tradingview.com/charting-library-docs/latest/getting_started/Key-Featuresunsupported-features) section for more information. Also, the libraries and the website are updated at different frequency, therefore, new features on [tradingview.com](https) may not be available in the libraries.
13. Does Advanced Charts / Trading Platform support Alerts, Range Bars, Bar Replay Tool, and patterns? Some features that are available on [tradingview.com](https) are not supported in the libraries, including Alerts, Range Bars, Bar Replay Tool, and patterns. Refer to the [Unsupported features](https://www.tradingview.com/charting-library-docs/latest/getting_started/Key-Featuresunsupported-features) section for more information.
14. Why do I get error messages mentioning CSP or blob? Content Security Policy (CSP) is a web security standard that helps prevent various types of attacks. CSP defines a policy specifying which domains are considered trusted sources for content such as scripts, images, fonts, and other resources. The error message may look like the following: ```javascript Refused to load the image ' because it violates the following Content Security Policy directive: "img-src 'self' blob data ``` Depending on your use cases, implementation, browser compatibility, or internal company policies, you may encounter issues with some library features. These could include displaying screenshots, logos, or using emojis/icons within the chart. We encourage you to properly assess the situation and choose the appropriate solution by reading the [Content Security Policy](https) article. When changing CSP is not allowed, you can enable the [`iframe_loading_compatibility_mode`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsiframe_loading_compatibility_mode) featureset. This featureset will instead use `about:blank` as the source URL and build the iframe HTML using `document.write`. The blob method is the preferred approach but this featureset offers a fallback for non-standard applications.
15. Does the library set cookies? The library does not set any cookies. If necessary, you can add your own cookies via server responses and restrict access to specific files, pages, or content based on the cookies set in the user's request.
[How to connect data via Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial [`custom_translate_function`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_translate_function [`getQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes [integration examples]: https://www.tradingview.com/charting-library-docs/latest/tutorials#framework-integrations [`isTradable`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#istradable [`placeOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#placeorder [`symbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#symbolinfo [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/Hosting-Library-Cross-Origin =========================================================================================================== # Cross Origin Hosting If you need to host the library files on a separate origin (domain) to the page containing the chart then please ensure that the [`library_path` widget constructor parameter](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#library_path) is configured as follows: - The `library_path` value should start with either `http://` or `https://`, followed by the url to the folder containing the library's static files. - example: `library_path: 'https://example.com/charting_library/'` - `library_path` should end with a trailing forward slash. ## Example: Loading the standalone version from separate origin If you hosted the library files within a folder named `charting_library` on the `example.com` domain then you would configure the library as follows. ### Loading the standalone script Place the following script tag within the `` of the page. ```html ``` ### Specifying the `library_path` parameter When evoking the widget constructor, ensure that the `library_path` value starts with `http` as described above. ```js var widget = (window.tvWidget = new TradingView.widget({ library_path: 'https://example.com/charting_library/', symbol: 'A', interval: '1D', container: 'tv_chart_container', datafeed: new Datafeeds.UDFCompatibleDatafeed( 'https://demo_feed.tradingview.com' ), })); ``` ## Server setup Make sure that the server hosting the library files is configured to allow cross-origin requests from the origin of the page containing the chart element. Please see this MDN article for more information: [Access-Control-Allow-Origin](https) ### Demo Charts and Study Templates Storage Server Please note that the demo charts and [study template storage server](https://www.tradingview.com/charting-library-docs/latest/api/save-load-rest-api#use-demo-storage) (`http://saveload.tradingview.com`) isn't compatible with requests from any origin except `localhost` and `tradingview.com`. Attempting to use this server from any other origin will still result in a CORS error. Please see [Saving and Loading Charts](https://www.tradingview.com/charting-library-docs/latest/saving_loading) for an overview on how to setup your own storage server. URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/Key-Features =========================================================================================== # Key features This topic describes the key features of Advanced Charts and [Trading Platform](#trading-platform-features). You can find a full list of features on the [TradingView website](https). Note that some [features](#unsupported-features) that are available on [tradingview.com](https) are not supported in the libraries. ## Advanced Charts features The following features are available in Advanced Charts and Trading Platform. ### Mobile friendliness Advanced Charts and Trading Platform are compatible with mobile devices. :::info The chart layout adapts to the device type and screen size by resizing/hiding elements. This means that some features, such as [Watchlist] and [News], may not be supported on smaller devices. ::: The library supports mouse and touch-based inputs and recognizes single and multi-touch gestures. Refer to the [Mobile app development](https://www.tradingview.com/charting-library-docs/latest/mobile_specifics) topic for more information. ### Chart types Advanced Charts and Trading Platform support the following chart types: - Bars - Candles - Hollow candles - Line - Line with markers - Step line - Area - HLC area - HLC bars - Baseline - Columns - High-low - Heikin Ashi :::info The types below are available in the Trading Platform only. ::: - Renko - Point-and-Figure - Line Break - Kagi ### Indicators Advanced Charts and Trading Platform support more than 100 [indicators](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators). Follow the [Indicators List](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators/Indicators-List) page to see all available indicators. You can also create your custom indicators in JavaScript. Refer to [Custom Studies](https://www.tradingview.com/charting-library-docs/latest/custom_studies) for more information. Note that [Pine Script®](https) is not supported in the libraries. ### Drawings Advanced Charts and Trading Platform support more than 70 [drawings](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings). Follow the [Drawings List](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/Drawings-List) page to see all available drawings. ### Compare symbols Advanced Charts and Trading Platform allow you to display multiple symbols on the same chart. The library brings them to the common time zone and trading session. If some symbol's trading session is longer than others, the extra data is cut by default. Alternatively, you can [extend the time scale] using the [`secondary_series_extend_time_scale`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsimportant-features) featureset. For example, the current symbol's session starts at 09:00, and you add another symbol whose session starts at 08:00. In this case, the `08:00` timestamp appears on the time scale. ### Advanced price scale Advanced Charts and Trading Platform include additional logarithmic, percent, fractional, and other price scales. You can also display symbols in different currencies and units. For more information, refer to [Price Scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale). ### Building custom resolutions Advanced Charts and Trading Platform can build bars with a higher resolution using lower resolution data. For example, they can build 2-minute bars from 1-minute bars. For more information, refer to [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution). ### Resolution in seconds and ticks Advanced Charts and Trading Platform support resolutions in seconds and ticks. Refer to the [Resolution](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologyresolutions) topic for more information. ### Trading hours Advanced Charts and Trading Platform display trading hours for a symbol in a separate widget. The libraries also support [pre-market and post-market](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions) trading sessions. ![Session Widget](https://www.tradingview.com/charting-library-docs/img/session-widget.png) ### Chart snapshot Users can take [snapshots](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Snapshots) in the UI. All snapshots are stored on the TradingView servers. The data storage period is not limited in time. You can also change the storage path using the [API](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#snapshot_url). ### Time zones Advanced Charts and Trading Platform support more than 80 time zones and daylight saving time for each of them. Users can select a time zone in the UI and observe the chart in the exchange's time zone or any time zone from the [list](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezonessupported-time-zones). If a time zone you want to provide is not supported in the library, you can request it on [GitHub Issues](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )). You can also create a [custom time zone](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezonescustom-time-zones). ### Theme Advanced Charts and Trading Platform include pre-designed dark and light themes. Note that users cannot switch the theme in the UI unless you develop this option outside the library. For more information, refer to the [Theme](https://www.tradingview.com/charting-library-docs/latest/customization/theme) section. ## Trading Platform features Refer to the [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal) article for more information about the features. ## Unsupported features Neither Advanced Charts nor Trading Platform provides full functionality of the charts on [tradingview.com](https). Since Advanced Charts and Trading Platform are client-side solutions, they do not support the client-server features listed below. - Pine Script® - Alerts - Bar Replay Tool - Range Bars - TradingView data - Strategy Tester - Screener Widget - Technicals in the Details widget - Hotlists - Calendars - Chats - Heatmap - Patterns :::tip Consider using the TradingView [Widgets](https://www.tradingview.com/charting-library-docs/latest/getting_started/product-comparisonwidgets) to display Calendars, Hotlists, and Heatmaps. ::: [extend the time scale]: https://www.tradingview.com/charting-library-docs/latest/custom_studies/Studies-Extending-The-Time-Scale#for-overlay-study [News]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal#news [Watchlist]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal#watchlist URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/NPM ================================================================================== # NPM You can install the library as an NPM dependency. Follow the steps below to set it up. ## 1. Configure package.json Specify the library version number. ```json { "dependencies": { "charting_library": "git@github.com:tradingview/charting_library.git#semver:28.0.0" } } ``` Note that files located in `node_modules/charting_library/` are not bundled during the build process. You need to ensure that these files are included on the server and can be accessed by a specific path. To do this, add a script to copy the files into a folder that serves static assets. In this example, the `public` folder is used, but this may vary based on your project structure. Adjust the `copy-files` command accordingly. ```json {2-5} { "scripts": { "postinstall": "npm run copy-files", "copy-files": "cp -R node_modules/charting_library/ public" }, "dependencies": { "charting_library": "git@github.com:tradingview/charting_library.git#semver:28.0.0" } } ``` ## 2. Run npm install This command also triggers the `postinstall` script, which copies the static files into the specified directory. :::info The library repository is private. `npm install` will only work if the Git client is logged into an account with access to the repository. Refer to [Getting Access](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access) for more information. If you encounter installation issues, ensure your [SSH public key](https) is added to your GitHub account and set for verification. If the `ssh -T git@github.com` command works, your SSH is set up correctly. ::: URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/Online-Editors ============================================================================================= # Online playgrounds Online code editors like CodePen and JSFiddle are the fastest way to create examples, reproduce bugs, or experiment with the Advanced Charts and Trading Platform, all without any local setup. This guide shows you how to use our hosted library files to get a chart running in seconds. For the quickest start, we recommend using one of our pre-made [starter templates](#starter-templates). ## Starter templates We currently provide starter templates for CodePen and JSFiddle. While other online editors may work, our hosted files use a security policy (CORS) that can prevent the chart from loading on unsupported sites. For more information on how to use the library when the HTML page and the library bundles aren't on the same origin, see [Cross-Origin Hosting](https://www.tradingview.com/charting-library-docs/latest/getting_started/Hosting-Library-Cross-Origin). The starter templates below are the fastest and most reliable way to get started. Simply open one, fork it, and start coding. ### CodePen - [Advanced Charts](https) - [Trading Platform](https) - [Themed Advanced Charts](https) ### JSFiddle - [Advanced Charts](https) - [Trading Platform](https) - [Themed Advanced Charts](https) ## Important limitations When using our hosted library files, be aware of the following restrictions. - The hosted files always point to the latest version from the `master` branch of the [charting_library GitHub repository](https)  🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )). To [use a specific version](#using-specific-version), link to your hosted library files and ensure your server allows CORS for the code playground site of your choice. - The [demo storage](https://www.tradingview.com/charting-library-docs/latest/api/save-load-rest-api#use-demo-storage) for chart layouts and indicator templates isn't compatible with requests from any origin except `localhost` and `tradingview.com`. Attempting to use this server from any other origin will result in a CORS error. - When specifying a custom CSS file via the [`custom_css_url`] property, be aware that the CSS URL should be specified relative to the [`library_path`] property. ## How to set up The starter templates are ready to go, but if you want to understand how they work or build an example from scratch, follow the steps below. Before proceeding with the steps, choose the correct domain for the library you are using. These base URLs point to the latest build of the library: - `https://charting-library.tradingview-widget.com` (for Advanced Charts) - `https://trading-terminal.tradingview-widget.com` (for Trading Platform) Then integrate the library using either the [latest version](#using-latest-version) or a [specific version](#using-specific-version). The examples below will use the Advanced Charts domain. ### Using latest version 1. Within the head of your HTML file, load two scripts: the standalone version of the library and the demo datafeed implementation: ```html ``` 2. In your JavaScript, set the [`library_path`] property to the `charting_library` subfolder of the domain of your choice. ```js new TradingView.widget({ /* Other Widget Constructor properties */ library_path: 'https://charting-library.tradingview-widget.com/charting_library/', }) ``` ### Using specific version 1. Within the head of your HTML file, load two scripts: the standalone version of the library and the demo datafeed implementation. For the library script, specify the version path you'd like to use, for example, `/versions/28.4.0`. ```html ``` 2. In your JavaScript, set the [`library_path`] property to point to the exact same version you specified in the HTML file. ```js new TradingView.widget({ /* Other Widget Constructor properties */ library_path: 'https://charting-library.tradingview-widget.com/versions/29.0.0/charting_library/', }) ``` [`custom_css_url`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_css_url [`library_path`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#library_path URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/Package-Content ============================================================================================== # Package Content The package is available on GitHub. You may check out the latest stable version (`master` branch). Please get in touch with us to get access to this repository. You can check the library version by entering the `TradingView.version()` command in a browser console. ### Package content ``` +/charting_library + /bundles - charting_library.js - charting_library.d.ts - charting_library.cjs.js - charting_library.esm.js - charting_library.standalone.js - datafeed-api.d.ts - package.json +/datafeeds + /udf - index.html - mobile_black.html - mobile_white.html - test.html ``` * `/charting_library` contains all the library files. * `/charting_library/charting_library*` files contain an external library widget interface, they is not supposed to be edited. * `.js` is an [UMD](https) module (for backward compatibility). * `.esm.js` is an native JavaScript module, see [import](https). * `.cjs.js` is an [CommonJS](https) module. * `.standalone.js` is an [iife](https) module. * `.d.ts` contains TypeScript definitions for the widget interface. * `/charting_library/datafeed-api.d.ts` contains TypeScript definitions for the data feed interface. * `/charting_library/bundles` stores library internal content and is not intended for other purposes, it should be like "black box" for you so it could be changed anytime without a notice. * `/charting_library/datafeeds/udf/` contains [UDF-compatible](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF) datafeed wrapper (implements [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api) to connect to library and UDF to connect to datafeed). Sample datafeed wrapper implements pulse real-time emulation. You are free to edit its code. * `/index.html` is an example of using library widget on your web page. * `/test.html` is an example of using different library customization features. * `/mobile*.html` are also examples of Widget customization. All internal JS and CSS codes of the library are inlined and minified to reduce the page load time. Files that are expected to be edited by you were not minified. URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/Shortcuts ======================================================================================== # Keyboard shortcuts ## Overview This article lists shortcuts built in Advanced Charts and Trading Platform. It also [explains](#manage-shortcuts) how to override the default shortcuts and specify custom ones. :::info The shortcut dialog that can be seen on [tradingview.com](https) is not available in the libraries. Therefore, you need to implement a custom dialog if necessary. ::: ## Advanced Charts shortcuts The shortcuts below are available in Advanced Charts and Trading Platform. :::tip On macOS, you can use // instead of Ctrl/Alt/Shift. ::: ### Chart You can use the following shortcuts to interact with the [chart](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Chart). | Action | Shortcut | |---|---| | Open Quick Search | Ctrl + K | | Open indicators | / | | Load chart layout | . | | Save chart layout | Ctrl + S | | Undo | Ctrl + Z | | Redo | Ctrl + Y | | Change symbol | Start typing a symbol name | | Change interval | Digit or , | | Move chart 1 bar to the left | | | Move chart 1 bar to the right | | | Move chart to the left/right | Shift + Mouse wheel | | Zoom in | Ctrl + | | Zoom out | Ctrl + | | Move further to the left | Ctrl + | | Move further to the right | Ctrl + | | Toggle maximize pane | Double-click the pane | | Toggle collapse pane | Ctrl + Double-click the pane | | Go to date | Alt + G | | Take snapshot, saving URL to clipboard | Alt + S | | Reset chart | Alt + R | | Invert series scale | Alt + I | | Enable/disable logarithmic series scale | Alt + L | | Enable/disable percent series scale | Alt + P | | Zoom in focused area | Ctrl + Mouse wheel | | Start keyboard navigation| Alt + Z

Tab if [`accessible_keyboard_shortcuts`] is enabled| ### Indicators and drawings You can use the following shortcuts to interact with [indicators](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators) and [drawings](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings). | Action | Shortcut | |---|---| | Partially erase drawing | _Eraser_ + Ctrl | | Enable Gann box fixed increments | Hold Shift | | Enable measure tool | Hold Shift + Click | | Copy selected object | Ctrl + C | | Paste object | Ctrl + V | | Temporary turn on/off magnet mode | Ctrl + Move a point | | Hide all drawings | Ctrl + Alt + H | | Clone a drawing | Ctrl + Drag | | Select multiple drawings | Hold Ctrl + Click | | Move a drawing horizontally or vertically | Drag + Shift | | Move selected drawing left | | | Move selected drawing right | | | Move selected drawing up | | | Move selected drawing down | | | Draw _Trend line_ | Alt + T | | Draw _Horizontal line_ | Alt + H | | Draw _Vertical line_ | Alt + V | | Draw _Cross line_ | Alt + C | | Draw _Fib retracement_ | Alt + F | | Draw _Rectangle_ | Alt + Shift + R | | Draw _Square_ | _Rectangle_ + Shift | | Draw _Circle_ | _Ellipse_ + Shift | | Draw 45 degrees angle or horizontal | _Trend line_ or _Channel_ + Shift | ## Trading Platform shortcuts The shorcuts below are available in [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal) only. ### Chart You can use the following shortcuts to interact with the [chart](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Chart). | Action | Shortcut | |---|---| | Switch between charts | Tab

Shift + if [`accessible_keyboard_shortcuts`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsaccessible_keyboard_shortcuts) is enabled| | Switch between charts in reverse order |Shift + Tab

Shift + if [`accessible_keyboard_shortcuts`] is enabled| | Toggle maximize chart | Alt + Enter or Alt + Click | | Add symbol to watchlist | Alt + W | ### Watchlist You can use the following shortcuts to interact with [watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List). | Action | Shortcut | |---|---| | Switch to next symbol | or Space | | Switch to previous symbol | or Shift + Space | | Select all symbols | Ctrl + A | | Select next symbol | Shift + | | Select previous symbol | Shift + | ### Trading You can use the following shortcuts to trade. | Action | Shortcut | |---|---| | Place market order to buy | Shift + B | | Place market order to sell | Shift + S | | Place limit order | Click the [Depth of Market][DOM] (DOM) cell | | Place limit order to buy | Shift + Alt + B | | Place limit order to sell | Shift + Alt + S | | Place stop order | Ctrl + Click the [DOM] cell | | Center [DOM] data | Shift + Alt + C | ## Manage shortcuts :::warning Starting from Advanced Charts **version 31**, the shortcut system **only accepts key code–based** definitions. Definitions using printable-character strings, such as `"alt+q"`, will no longer be supported. Modifier keys like `ctrl`, `alt`, `shift`, and `meta`/`command` can still be written as strings. ::: ### Transition to key code-based shortcuts (v31) Starting from version 31, all shortcuts must use **numeric key codes** for non-modifier keys. This replaces previous character-literal definitions (e.g., `"alt+q"`, `"/"`, `"+"`), which are now deprecated and will no longer work in future versions. This change: - Unifies the shortcut API across different keyboard layouts. - Eliminates ambiguities between characters that map to the same physical key. To update your code, follow the steps below. 1. Identify all `widget.onShortcut()` calls that pass printable characters as a single string or inside an array. 2. Replace each character with its corresponding numeric key code taken from the `KeyboardEvent.keyCode` or `which` property. For convenience, use a lookup tool like [Key code reference](https). 3. Keep modifier keys (`ctrl`, `alt`, `shift`, and `meta`/`command`) as lowercase strings. 4. Test the shortcuts under v31 to confirm the callbacks are triggered. ### Override shortcuts The [`onShortcut`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#onshortcut) method allows you to override the built‑in shortcuts or specify custom ones. To do this, pass a keyboard shortcut and a callback function as parameters. The `shortCut` parameter depends on the key types: - **Before v31:** If a shortcut consists of a modifier and alphabet keys, you could pass a string and use `+` as a separator. Note that this format will be deprecated starting from version 31. ```javascript // ⚠️ Will be deprecated in v31 widget.onShortcut("alt+q", function() { widget.chart().executeActionById("symbolSearch"); }); ``` - If a shortcut consists of a modifier and alphabet keys, pass them as an array — the modifier as a string, and the key as its numeric code. ```javascript // alt + q widget.onShortcut(["alt", 81], function() { widget.chart().executeActionById("symbolSearch"); }); // ctrl + shift + / widget.onShortcut(["ctrl", "shift", 220], function() { widget.chart().executeActionById("symbolSearch"); }); ``` ### Disable shortcuts The shortcuts listed below can be disabled using the corresponding [featureset](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets): - _Open indicators_ using [`insert_indicator_dialog_shortcut`] - _Save chart layout_ using [`save_shortcut`] [DOM]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market [`insert_indicator_dialog_shortcut`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#insert_indicator_dialog_shortcut [`save_shortcut`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#save_shortcut [`accessible_keyboard_shortcuts`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#accessible_keyboard_shortcuts URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/accessibility ============================================================================================ # Accessibility ## Disclaimer The TradingView team is actively working to make the library more accessible and compliant with [Web Content Accessibility Guidelines (WCAG) 2.2](https). We understand that our product is complex and feature-rich, and achieving full accessibility for everyone is an ongoing journey. It is important to note that certain components might not fully meet accessibility requirements. If you encounter any accessibility issues or have suggestions for improvements, kindly contact us at `inclusion.feedback@tradingview.com`. Note that this email is exclusively for accessibility matters. All other questions should be directed to [GitHub Issues](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )). At this stage, the library ships with the following accessibility features. ## Keyboard navigation Users can navigate through elements on the top, bottom, and drawing toolbars using the Tab and arrow keys. Keyboard navigation By default, users should press Alt + Z to start navigation. Alternatively, you can enable the [`accessible_keyboard_shortcuts`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsaccessible_keyboard_shortcuts) featureset to start the navigation with Tab. In this case, the built-in [shortcuts](https://www.tradingview.com/charting-library-docs/latest/getting_started/Shortcuts) listed in the table below are also changed. Action | Default shortcut | `accessible_keyboard_shortcuts` ---------|----------|--------- Start keyboard navigation| Alt + Z | Tab Switch between charts | Tab | Shift + Switch between charts in reverse order |Shift + Tab | Shift + :::tip The library includes built-in shortcuts that allow users to perform actions in the UI. You can also add custom shortcuts. For more information, refer to [Shortcuts](https://www.tradingview.com/charting-library-docs/latest/getting_started/Shortcuts). ::: ## Color and contrast Colors on the chart are compliant with the [WCAG 2.2 AA standard](https). The library also provides multiple customization options. For example, you can configure colors for different UI elements, resize the chart size, and adjust fonts. For more information, refer to the [Customization](https://www.tradingview.com/charting-library-docs/latest/customization) section. ## Screen reader compatibility The library supports the following screen readers. - [VoiceOver] on macOS - [Narrator]/[JAWS]/[NVDA] on Windows To use a screen reader, users should download and enable it. [VoiceOver]: https://support.apple.com/en-us/guide/voiceover-guide/welcome/web [Narrator]: https://support.microsoft.com/en-us/windows/complete-guide-to-narrator-e4397a0d-ef4f-b386-d8ae-c172f109bdb1 [NVDA]: https://www.nvaccess.org/about-nvda/ [JAWS]: https://www.freedomscientific.com/products/software/jaws/ URL: https://www.tradingview.com/charting-library-docs/latest/getting_started ============================================================================== # Getting started ## What is Advanced Charts Advanced Charts is a standalone client-side solution that is used to display financial charts, prices, and technical analysis tools. You should [download the library](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access), host it on your servers, connect your data to it, and embed the library in your website or application. Advanced Charts is provided for free. import CTAButton from "@site/src/components/landing-page/CTAButton"; ## What is Trading Platform Trading Platform is a standalone client-side solution that provides trading capabilities. Trading Platform is based on Advanced Charts and contains all its features. For more information on the Trading Platform specifics, refer to the [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal) article. ## Key features Advanced Charts and Trading Platform include a variety of features. Refer to the [Key features](https://www.tradingview.com/charting-library-docs/latest/getting_started/Key-Features) article for more information. :::info Neither Advanced Charts nor Trading Platform provides full functionality of the charts on [tradingview.com](https). Since Advanced Charts and Trading Platform are client-side solutions, they do not support client-server features available on [tradingview.com](https). Refer to [Unsupported features](https://www.tradingview.com/charting-library-docs/latest/getting_started/Key-Featuresunsupported-features) for more information. ::: ## Online demo To try the library straight away, refer to the [Advanced Charts](https) / [Trading Platform](https) demo pages. Note that demo data is restricted and updated every 10 seconds. Therefore, you should use the demos for testing purposes only. ## System requirements Advanced Charts / Trading Platform is a standalone client-side library that does not require any additional frameworks or tools. The library operates in a web browser, leveraging native browser technologies such as JavaScript, HTML, and CSS. To use the Advanced Charts / Trading Platform, you need a server to host the library files and your own data source, as the library does not contain any market data. ### Browser compatibility The library is compatible with all major browsers such as Google Chrome, Firefox, Safari, Opera, and Microsoft Edge, including their mobile versions. ### Framework compatibility You can integrate the library with common frameworks such as Angular and React. Refer to [Framework integrations](https://www.tradingview.com/charting-library-docs/latest/tutorialsframework-integrations) for a list of examples. The library can also be embedded into a mobile application using a web view. Consider the [Mobile app development](https://www.tradingview.com/charting-library-docs/latest/mobile_specifics) article for more information. URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary ======================================================================================= # Glossary This article contains terms that are used in the Advanced Charts documentation. ## Trading terms ### Bracket order An [order](#order) that helps users limit their losses and secure their profits by bracketing positions with two opposing [stop-loss](#stop-loss-order) and [take-profit](#take-profit-order) orders. Refer to [Bracket orders](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/brackets) for more information. ### Execution The completion of a buy or sell order for a financial instrument. An execution involves matching a buyer and a seller and transferring ownership of the financial instrument. ### Individual position The amount of a singular holding or investment in a financial instrument. ### Limit order An [order](#order) to buy or sell a financial instrument when a given or better price is reached. This order type guarantees a specific price but does not guarantee immediate execution. ### Limit price The maximum price a buyer is willing to pay or the minimum price a seller is willing to accept. ### Market order An [order](#order) to buy or sell a financial instrument at the current market price. This order type guarantees immediate execution but does not guarantee a specific price. ### Net position The difference between an investor's total number of open long and short positions at any given time. ### Order A request made by a trader to buy or sell a financial instrument at a specified price and quantity. An order can have various attributes, such as a [limit price](#limit-price), [stop price](#stop-price), and [duration](#order-duration). Depending on whether an order has been executed or not, it can be in various statuses such as canceled, filled, placing, or rejected. Refer to [Orders](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders) for more information. ### Order duration The time during which an order remains active. ### Pip The minimum price movement for Forex symbols. For more information on how to display pips, refer to the [Price format](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologyhow-to-display-pips) section. ### Position The amount of a financial instrument held by an investor. For more information, refer to [Positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions). ### Position netting The process of aggregating multiple individual positions for one symbol into a single net position. For more information, refer to [Position netting](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positionsposition-netting). ### Quotes Real-time price information for financial instruments, including the most recent bid and ask prices, opening and closing prices, price changes, and other market data. Refer to [Quotes](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/quotes) for more information. ### Stop-loss order A type of [order](#order) designed to limit losses by automatically closing a position at a given price when it moves unfavorably. ### Stop order An [order](#order) to buy or sell a financial instrument at the market price as soon as it reaches a certain level. ### Stop price A trigger price at which an order becomes a market or limit order. ### Take-profit order A type of [limit order](#limit-order) that closes a position at a specific price to secure a profit. ### Tick The minimum price movement. ## Technical terms ### Bar spacing A number of pixels between each data point on the chart. Smaller values show more data. ### Datafeed A middleware that requests data from a server and sends it to the library. Refer to the [Connecting data](https://www.tradingview.com/charting-library-docs/latest/connecting_data) article for more information. ### Date range A period of time that is currently visible on the chart canvas. This range changes when users scale the chart. Refer to [Time scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scaletime-frame-toolbar) for more information. ### Featureset A toggle that allows you to enable or disable a certain feature. Refer to the [Featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) article for more information. ### Pane An area on the chart where a [series](#series) or [indicator](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators) is displayed. The picture below shows the red pane with the main series and the green pane with the indicator. Chart panes ### Plot A line or area that represents indicator values on a chart. ### Series A collection of data points that represents a specific metric over time. A series can be of different styles that affect how data is displayed on the chart. Refer to [Chart styles](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrideschart-styles) for more information. ### Source symbol A symbol that is used as a data source for a certain indicator. The indicator calculates its own data based on the symbol's data. ### Spread operators Operators that allow comparison between a financial instrument, such as a stock, and an additional variable, such as another financial instrument or a numerical value. Spread operators can be enabled in the [Search Symbol](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Searchenable-spread-operators) and [Compare Symbol](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicatorsenable-spread-operators) dialogs. URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/llm-context ========================================================================================== # Build AI docs assistant ## Overview Using generic AI assistants for library-specific questions can be unreliable. The models often rely on outdated public data, which can lead to frustrating results. To address this challenge, a downloadable knowledge file is now available, containing the complete documentation. By providing this file as a knowledge base, you can turn a general-purpose AI into a dedicated expert on the library. Ask complex questions and receive detailed answers, code examples, and direct links back to the documentation. ## File contents and prerequisites The charting-library-context.txt file is a comprehensive knowledge base compiled directly from our official sources. It contains the complete public documentation and full TypeScript definitions, ensuring the AI has a deep and accurate understanding of the library. Before you begin, review the technical information below. - **File size.** Approximately 670,000 tokens. - **Model compatibility.** Due to its large size, this file requires an AI model with a very large [context window] (one million tokens or more). - **Version specificity.** The file is always for the **latest version** of our library. Consequently, solutions and code examples provided by the AI may not be compatible with older versions of the library. :::info The exact token count can vary slightly between different AI providers, but the file size remains a critical factor for model compatibility. ::: ## How to use Follow these steps to get started. We'll use Google AI Studio as an example, but the process is similar for other AI tools that support large file uploads. 1. Download the charting-library-context.txt file. 2. Go to the [Google AI Studio](https) website and sign in. 3. Start a new chat with the assistant. 4. Upload the file to the prompt box. 5. Start asking questions in the prompt box. For example: "How can I hide the toolbar on the left?" The AI will answer your question using only the information contained in the file you provided. See the example below. ![LLM answer example](https://www.tradingview.com/charting-library-docs/img/llm-context-example.png) ## Best practices To get the most out of this feature, follow these tips: - **Be specific.** The more detailed your question, the better the answer. - **Start a new chat for new topics.** To prevent context confusion, start a fresh chat when switching between major topics (e.g., from custom indicators to data integration). - **Tune the AI for accuracy.** If your AI tool allows it, adjust the model settings for better results: - **Choose the best model.** Always select the latest, most powerful model available. - **Set a low temperature.** To minimize AI "creativity" and force it to stick to the facts, adjust the temperature setting to a low value. - **Ask for code.** Explicitly ask the AI to "provide a full JavaScript code example" or "show me the TypeScript interface for this." - **Verify with the documentation.** The AI is trained to provide direct links to the official documentation. Use these to double-check critical information and explore topics further. ## Limitations and disclaimers Please keep the following in mind when using this feature: - **The official documentation is the source of truth.** While the AI is highly accurate, it is still a tool. This documentation website should always be considered the definitive source of information. - **Your code, your control.** The AI-generated responses and code are for informational purposes only and should not be considered official TradingView advice. It is **your responsibility** to thoroughly test, verify, and validate any code or suggestions before implementing them in a production environment. TradingView assumes no responsibility for any outcomes resulting from the use of AI-generated content. - **AI can make mistakes.** The model may misinterpret a question or "hallucinate." If an answer seems incorrect, try rephrasing your question or refer to the official documentation website. - **No support for third-party tools.** TradingView doesn't provide technical support for any third-party LLM service. [context window]: https://en.wikipedia.org/wiki/Large_language_model#Attention_mechanism_and_context_window URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/product-comparison ================================================================================================= # Other TradingView products TradingView provides several charting solutions to display financial data. This page contains brief overview of these products and highlights their differences from Advances Charts / Trading Platform. For detailed information, refer to the [Compare libraries](https) page. ## Lightweight Charts™ [Lightweight Charts™](https) is a free, open-source client-side library. It is 45 KB in size, which is smaller than a typical image of a chart. The main difference between this library and Advanced Charts is the way they retrieve data: - In Advanced Charts, you pass data in response to the library's request. - In Lightweight Charts™, you provide data directly to the library without any requests. :::info Neither Advanced Charts nor Lightweight Charts™ contains any market data. You should use data from your own source or third-party providers. Note that Lightweight Charts™ does not contain any built-in indicators. Therefore, you should implement them on your own if required. Consider the [Moving Average](https) implementation example. ::: If you want to migrate from Lightweight Charts™ to Advanced Charts, consider the following table that contains common methods with similar functionality: |Functionality|Lightweight Charts™| Advanced Charts| |-|-|-| |Create a chart|`createChart`| Specify the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor).| |Add a series of certain style|[`addLineSeries`](https) or [`addCandlestickSeries`](https)|Specify any [series style](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrideschart-styles) using the [`overrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions/#overrides) property of the Widget Constructor.| |Get a pixel coordinate|[`timeToCoordinate`](https)|Advanced Charts / Trading Platform does not contain such method. As an alternative, consider using methods from the [`ITimeScaleApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ITimeScaleApi) interface.| |Create a price line|[`createPriceLine`](https)|[`createOrderLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createorderline) or [`createShape`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createshape)| ## Widgets [Widgets](https) are free and simple standalone applications that do not require any code implementation. To embed a widget in your website, you just need to copy and paste the provided code. Widgets are hosted on the TradingView servers and display the TradingView data. Compared to libraries, widgets offer fewer customization options. However, widgets have some additional features, such as Heatmaps and Hotlists, that are [not supported](https://www.tradingview.com/charting-library-docs/latest/getting_started/Key-Featuresunsupported-features) in Advanced Charts. If you like the Advanced Charts library but do not have your own data, consider using the [Advanced Chart widget](https). :::info Note that you cannot connect your data to the widgets. ::: URL: https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-start ========================================================================================== # Quick start ## Getting access The [Advanced Charts](https) and [Trading Platform](https) repositories are private, and you should fill out the form on the [TradingView website](https) to request access. Otherwise, attempting to access the GitHub repositories or legacy documentation links will result in the _404 Not Found_ error. :::caution Advanced Charts and Trading Platform should only be downloaded from the official TradingView repositories provided within this documentation. Obtaining the library from third-party services is strictly prohibited and may lead to legal consequences. The library is not redistributable. Therefore, it is prohibited to use any part of the library in public repositories. ::: ## First steps You should complete the steps below to get started with Advanced Charts / Trading Platform: 1. [Run Advanced Charts / Trading Platform](https://www.tradingview.com/charting-library-docs/latest/tutorials/First-Run-Tutorial) for the first time. 2. Set up [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor). 3. [Connect data](https://www.tradingview.com/charting-library-docs/latest/connecting_data) and [implement real-time data streaming](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial). 4. [Explore](https://www.tradingview.com/charting-library-docs/latest/ui_elements) various parts of the interface and configure them to fit your needs. 5. [Customize](https://www.tradingview.com/charting-library-docs/latest/customization) your chart's appearance. We recommend that you also check out [Best Practices](https://www.tradingview.com/charting-library-docs/latest/getting_started/Best-Practices) and [Frequently Asked Questions](https://www.tradingview.com/charting-library-docs/latest/getting_started/Frequently-Asked-Questions) before you start development to avoid common mistakes. Additionally, for instant answers to your specific questions and to generate custom code examples, read our [Build AI docs assistant](https://www.tradingview.com/charting-library-docs/latest/getting_started/llm-context) guide. ## Integration examples You can integrate Advanced Charts / Trading Platform with Android WebView, iOS WKWebView, Angular, React, and other frameworks. Check out the [repository on GitHub](https) for some integration examples. ## Online code playgrounds You can use the libraries on some code playgrounds/editors such as JSFiddle and Codepen. The [Online editors](https://www.tradingview.com/charting-library-docs/latest/getting_started/Online-Editors) article provides several starter templates, that can help you quickly create your own examples, reproduce bugs, and experiment with the libraries. ## Hosting the library on a separate origin If you want to host an HTML page that contains the chart and the library bundles on different origins (domains), refer to [Cross-origin hosting](https://www.tradingview.com/charting-library-docs/latest/getting_started/Hosting-Library-Cross-Origin). URL: https://www.tradingview.com/charting-library-docs/latest/mobile_specifics =============================================================================== # Mobile app development import ThemedImage from '@theme/ThemedImage'; import useBaseUrl from '@docusaurus/useBaseUrl'; ## Overview Advanced Charts and [Trading Platform](https://www.tradingview.com/charting-library-docs/latest/trading_terminal) are compatible with mobile devices. The chart layout adapts to the device type and screen size by resizing/hiding elements. This means that the following features **may not be supported** on smaller devices: - The right widget bar that includes [Watchlist], [Details], [News], and Data Window widgets. - [Marks] on the time scale. - The [Account Manager] at the bottom bar. Instead, the Account Manager will be available through the *Broker* button () in the [legend]. You can disable this button by adding the [`broker_button`] featureset to the [`disabled_features`] array. The library supports mouse and touch-based inputs and recognizes single and multi-touch gestures. It is available on all major browsers such as Google Chrome, Firefox, Safari, Opera, and Microsoft Edge, including their mobile versions. ### Mobile specifics You should be aware of the following mobile specifics: - The chart legend shows a close price and percentage change. Open, high, and low prices and indicator values are displayed in tracking mode only. To activate this mode, a user should long tap on the bar and make a single tap on the chart to exit. - You should implement the [`getQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#getquotes) and [`subscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#subscribequotes) methods to display data in the [legend] if you use Trading Platform. Otherwise, [NaN values] will appear in the legend instead of the expected data. - The percentage change of the price is calculated based on intraday quotes, not the previous bar. - Only one price scale can be displayed on the chart. The following [featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) affect chart behavior on mobile devices: - `show_zoom_and_move_buttons_on_touch` enables zoom in/out and scroll left/right buttons. - `horz_touch_drag_scroll` and `vert_touch_drag_scroll` enable horizontal/vertical page scroll. - `pinch_scale` enables scaling using pinch gestures. ### Gestures - **Single tap** allows you to drag the chart left or right, as well as to adjust the [price](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale) and [time](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale) scales by dragging. - **Long press** - Opens a context menu for [price](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale) and [time](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale) scales. - Enables crosshair mode on the chart, allowing for detailed data visualization in the [legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend). - **Double tap** activates line movement mode: double-click a line, then drag it vertically to adjust its position. ## Mobile applications Native wrappers for iOS or Android are **not provided**. You can embed Advanced Charts and Trading Platform inside a mobile application using a WebView. The libraries are fully supported and guaranteed to work when running inside a WebView environment on both iOS and Android platforms. You should implement the communication between the native layer and the WebView. This communication typically involves creating a bridge that allows native methods to send commands to the WebView, triggering corresponding method calls within the embedded library. You have full control over how to implement this bridge and you can use any suitable method or framework that fits the app's architecture and platform constraints. Consider the following integration examples: - [TradingView Advanced Charts Android Integration Example](https) - [TradingView Advanced Charts iOS (Swift version) Integration Example](https) - [TradingView Advanced Charts React-Native Integration Example](https) We do not have an example of integrating the library with Flutter currently. You can consider the [How to Build a Native Communication Bridge in Flutter with WebView and JavaScript](https) article. ### Frequently Asked Questions #### The library Android Integration Example demonstrates a white screen. How to fix it? Make sure that the WebView version installed on your device supports ES6. We recommend you update to the latest WebView version to avoid potential issues. For more information, refer to the [WebView for Android](https) article. #### What is the minimum Android version required for the library? The minimum Android version for the library is Android 5.0 (Lollipop). Starting from this version, you can update WebView separately to the Android platform. For more information, refer to the [WebView for Android](https) article. #### How to check the library for errors? - For Android applications, use Chrome DevTools. Refer to the [Remote debug Android devices](https) and [Remote debugging WebViews](https) articles for more information. - For iOS applications, use [Safari Web Inspector](https). Refer to the [Enabling Web Inspector](https) article for more information. #### How to transfer data from native code to JavaScript code? You should use a mechanism that allows the execution of arbitrary code. Refer to the following articles for more information: - [evaluateJavascript](https)) for Android - [evaluateJavaScript](https) for iOS You can consider the following projects as examples of interaction between the native code and JavaScript library: - [Android Lightweight Charts](https) - [LightweightChartsIOS](https) #### How to open links in the built-in mobile browser instead of the web view on Android? You can use the [`shouldOverrideUrlLoading`](https)) method to implement custom logic for loading URLs. To open a built-in web browser, you should use [`Intent`](https) with the `ACTION_VIEW` parameter. import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; ```java Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.tradingview.com/")); startActivity(browserIntent); ``` ```kotlin val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.tradingview.com/")) startActivity(browserIntent) ``` You can also open links in Google Chrome Custom Tabs. Refer to [Implementation guide](https) for more information. #### How to resolve a truncated price and time scales issue? This issue occurs only when emulating a mobile device on a Chrome-based browser. However, when using the charts on an actual mobile device, both the price and time scales will display correctly. [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [`broker_button`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#broker_button [Details]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal#details [`disabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features [legend]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend [Marks]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Marks#marks-on-the-time-scale [NaN values]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend#nan-values-in-legend [News]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news [Watchlist]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List URL: https://www.tradingview.com/charting-library-docs/latest/releases/Update-Library ====================================================================================== # Update the library This article describes how to update Advanced Charts and Trading Platform. To do this, follow the steps below. :::info We are committed to keeping up with the latest technology trends and ensuring the library is compatible with evolving platforms and browsers. Therefore, we encourage you to regularly update the library's version. By keeping the library up-to-date, you can enhance your app performance and make sure it works smoothly on the latest browsers. ::: ## 1. Check a library version Check your current library version. To do this, run the following command in a browser console: ```javascript TradingView.version() ``` ## 2. Review release notes Review [release notes](https://www.tradingview.com/charting-library-docs/latest/releases/release-notes) that describe changes in a version you would like to install. If your current version is more than one release behind the desired one, you should also check release notes for the previous versions. Pay special attention to **breaking changes**. These changes can cause errors and require some enhancements in your code. ## 3. Download a new version Go to the [Advanced Charts](https) 🔐 or [Trading Platform](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )) repository and download the latest version of the `master` branch. ![Download a new version](https://www.tradingview.com/charting-library-docs/img/update_library.png) If you want to download a version that is older than the latest, find the desired version among commits and reset the repository state to that commit. ![Old versions](https://www.tradingview.com/charting-library-docs/img/old-versions.png) :::caution Advanced Charts and Trading Platform should only be downloaded from the official TradingView repositories provided within this documentation. Obtaining the library from third-party services is strictly prohibited and may lead to legal consequences. The library is not redistributable. Therefore, it is prohibited to use any part of the library in public repositories. ::: ## 4. Unzip an archive When you download a ZIP archive, extract files from it to any folder you prefer. We recommend that you do not replace an old version with a new one in the existing project, but put this version in a new place. In this case, you keep a working copy that you can check with. ## 5. Run the new version To test the new version, run the following command in a command line: ```javascript npx serve ``` As a result, you get a URL that you need to copy and insert into your browser's address bar. [Check the library version](#1-check-a-library-version) in a browser console to ensure you have installed the new version successfully. ## 6. Implement new features Implement new features if necessary. For more information about them, refer to the dedicated documentation sections that are introduced together with the features in the [release notes](https://www.tradingview.com/charting-library-docs/latest/releases/release-notes). Everything that you worked on in previous versions should be compatible with the new version. However, you should always test your project on any versions you update to. If issues appear, make sure you have addressed all breaking changes. URL: https://www.tradingview.com/charting-library-docs/latest/releases/release-notes ===================================================================================== # Release Notes :::tip You can check the library version by executing `TradingView.version()` in a browser console. ::: import ReleaseNoteAnchor from '@site/src/components/release-note-anchor' ## Version 29.5.0 *Date: Tue Aug 05 2025* ### Improvements \{#v29_5-improvement} - **Improved crosshair movement in tracking mode on mobile.** Previously, the crosshair moved incorrectly in tracking mode when `vert_touch_drag_scroll` was disabled. Now, page scrolling is disabled in tracking mode, allowing the crosshair to move on touch.
#### Trading Platform only \{#v29_5-improvement-tp-only} - **Added `setLayoutSizes` method to `IChartingLibraryWidget`.** The [`setLayoutSizes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#setlayoutsizes) method can be used to resize the charts in [multiple-chart layouts](https://www.tradingview.com/charting-library-docs/latest/trading_terminalmultiple-chart-layout).
### Bug Fixes \{#v29_5-bugfix} - **Fixed an issue where setMinimumAdditionalDepth would be ignored.** Fixed an issue where custom studies would sometimes not request enough historic bars after calling [`setMinimumAdditionalDepth`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IContext/#setminimumadditionaldepth).
- **Fixed an issue where pivot points could be drawn on the wrong bar for overnight sessions.** Fixed an issue where pivot points could be drawn on the wrong bars for symbols with overnight sessions when calculating with a daily timeframe.
--- ## Version 29.4.0 *Date: Tue Jun 25 2025* ### New Features \{#v29_4-feature} - **Added new legend property.** A new overrides property `paneProperties.legendProperties.showSeriesLegendCloseOnMobile` was added to hide/show the close value in the legend when on mobile. The default value is `true`.
#### Trading Platform only \{#v29_4-feature-tp-only} - **Support multiple tick resolution.** The library now supports multiple [tick resolutions](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolutionresolution-in-ticks). Previously, it was possible to set only `1T` resolution.
Note that the library does not support tick multipliers. This means it is not possible to build a higher resolution (e.g., `10T`) from a lower one (e.g., `1T`). Therefore, your datafeed must explicitly provide each required resolution.
- **Enabled custom price formatting for Watchlist values.** `priceFormatterFactory` from [`custom_formatters`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_formatters) can now be used to format values displayed in the Watchlist columns titled _Last_ and _Chg_.
### Improvements \{#v29_4-improvement} - **Updated snapshots functionality in the top toolbar.** Now, handling and storing [snapshots](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Snapshots) rely solely on the [`snapshot_url`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#snapshot_url) property. This means all server-side snapshot actions (*Copy link*, *Open in new tab*, *Tweet image*) must be implemented using your own server. For details on how to set up your own server, see our guide to [implementing a snapshot server](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement-snapshots-server).
- **Added the `use_symbol_name_for_header_toolbar` featureset.** This featureset allows you to show the symbol name over the ticker in the _Symbol Search_ dialog.
- **Added `searchSource` parameter to `searchSymbols`.** [`searchSymbols`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#searchsymbols) now receives a new parameter `searchSource` to indicate where the search was triggered from.
- **Added a new property to the `BrokerCustomUI` interface.** [`showReversePositionDialog`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerCustomUI#showreversepositiondialog) allows overriding the default *Reverse position* dialog with a custom implementation.
- **Added VWAP insufficient data warning.** Users will now see a warning icon and message in the legend if there isn't enough data loaded to calculate VWAP.
- **Add featureset to display inactivity gaps on intraday charts.** The new `intraday_inactivity_gaps` featureset enables the display of inactivity gaps on intraday charts. These gaps represent periods within the trading session when there has been no trading activity, resulting in missing bars on the chart.
When `intraday_inactivity_gaps` is enabled, a checkbox appears in the chart settings dialog, allowing users to toggle inactivity gaps on or off. The featureset also exposes the [`intradayInactivityGaps`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#intradayinactivitygaps) watched value on the Widget API for programmatic control.
- **Improved data loading efficiency by throttling data requests during user scrolling.** This significantly reduces the frequency of small, incremental requests to the Datafeed API.
#### Trading Platform only \{#v29_4-improvement-tp-only} - **Order & Position lines display the same information on desktop and mobile.** Users can now benefit from the same design on both desktop and mobile when an order/position is displayed on the chart.
### Bug Fixes \{#v29_4-bugfix} - **Fixed indicator template favorite menu bug.** Fixed an issue where favoriting an indicator template with leading whitespace in its name caused the quick access button in the header menu to appear empty.
- **Fixed Relative Strength Index indicator.** The Relative Strength Index indicator was broken in version 29.2.0 and has now been fixed.
- **Fixed a bug where switching chart type to a Japanese one would lead to an error in the console.**
- **Fixed vertical line drawing bug.** Fixed an issue where it was impossible to move an existing vertical line drawing to the right of the most recent bar on the chart.
- **Fixed an error when drawing execution shapes on the chart led to an invalid chart state.** Fixes [#9109](https)
- **Fixed the spread operator issue in the Compare symbol dialog.** Spread operators now function correctly in the _Compare symbol_ dialog, ensuring consistency with the _Symbol Search_ dialog.
- **Fix for sameorigin.html loading from relative path.** This fix ensures proper loading of the `sameorigin.html` file when using the `iframe_loading_same_origin` featureset and the current page is not the root page.
#### Trading Platform only \{#v29_4-bugfix-tp-only} - **The `_getStyleOverrides` error message.** Fixed a bug where the `_getStyleOverrides` error message could be seen in the console when instantiating the chart with pre-existing orders or positions.
- **Fix rendering of multiple execution shapes on a single bar.** Fixed an issue where adding multiple [execution shapes](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-apicreateexecutionshape) to a single bar would only render the first shape.
### Documentation \{#v29_4-documentation} - **New tutorial.** Check out our [new tutorial](https://www.tradingview.com/charting-library-docs/latest/api/implement-broker-api) on how to implement the required methods to enable basic trading functionality using the Broker API. By the end of this tutorial, you will learn how to enable trading UI and how to store, return, and update orders to make the trading flow functional.
- **New troubleshooting article.** Explore a new article on common [customization issues](https://www.tradingview.com/charting-library-docs/latest/customization/customization-issues) and potential solutions.
- **Other enhancements.** Updated the [Custom themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes) article and added a new [example](https) to demonstrate how chart colors can be adjusted using this API.
--- ## Version 29.3.0 *Date: Thu May 08 2025* ### New Features \{#v29_3-feature} - **Added HLC bars chart style.** The HLC bars chart style is the same as regular bars but doesn't display the open price. When exporting a series or [overlay](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicatorsadd-and-compare-new-series) indicator that uses the HLC bars chart style, open values are not included. Open values also do not appear in the data window or [legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend) for series or overlay indicators using this style.
### Improvements \{#v29_3-improvement} - **Added price scale details to context menu event.** When invoking the [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) on the price scale, it now returns the following details: - `id` of the price scale - `paneIndex` which is the index of the pane the price scale is linked to - `chartIndex` which is the index of the chart the price scale is linked to
- **Added icon to dropdown items.** A new property `icon` was added to the [`DropdownItem`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DropdownItem) interface.
### Bug Fixes \{#v29_3-bugfix} - **Empty context menu.** Fixed an issue where the [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) would be partially empty on mobile
- **onContextMenu callback received incorrect arguments.** Fixed a bug where the [`onContextMenu`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#oncontextmenu) callback received an object instead of the expected arguments.
- **Autosave won't trigger with empty text box created during autosave delay.**
- **Fixed an error where vertical lines would revert to their previous position when moved beyond latest bar.** Fixes [#8894](https)
### Documentation \{#v29_3-documentation} - **The following enhancements were made.**
- Added a new section explaining how to [programmatically open and close Symbol Search](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Searchopenclose-symbol-search). - Updated the [Customization overview](https://www.tradingview.com/charting-library-docs/latest/customization) and [Time zones](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezones) articles.
--- ## Version 29.2.0 *Date: Tue Apr 08 2025* ### New Features \{#v29_2-feature} - **Added new methods to Trading Host.** The [Trading Host](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-conceptstrading-host) now includes three new methods designed to clear specific caches and trigger fresh data fetches: - [`ordersFullUpdate`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#ordersfullupdate) - [`positionsFullUpdate`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#positionsfullupdate) - [`individualPositionsFullUpdate`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#individualpositionsfullupdate)
#### Trading Platform only \{#v29_2-feature-tp-only} - **Added cross-tab synchronization for watchlists.** This feature is enabled by default and requires the `use_localstorage_for_settings` [featureset](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) to be enabled. To disable the cross-tab synchronization, use the `watchlist_cross_tab_sync` featureset.
### Improvements \{#v29_2-improvement} - **New `resetCache` method.** The new `resetCache` method allows you to delete previously loaded data for all symbol and resolution combinations known to the datafeed at once. You can use this method instead of [`onResetCacheNeededCallback`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#subscribebars) to clear the cache before calling [`resetData`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#resetdata). In this case, you do not need to wait for [`subscribeBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#subscribebars) to be called to access the callback.
### Bug Fixes \{#v29_2-bugfix} - **Save button tooltip still shows shortcut when `save_shortcut` is disabled.** Fixed a bug where the _Save_ button's tooltip still showed the shortcut when the `save_shortcut` featureset was disabled. Fixes [#8925](https)
- **Compare Symbol search dialog behavior.** Fixed an issue where the library would try to resolve a symbol that may not exist when users pressed _Enter_ whenever the featureset `allow_arbitrary_symbol_search_input` would be enabled.
- **Adding a custom interval could cause an error.** Adding a custom interval after enabling the [`custom_resolution`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetscustom_resolutions) featureset used to cause a console error.
- **Fixed an issue where on some occasions PineJS functions would not return the right values when internally comparing it to MIN_VALUE or MAX_VALUE.**
- **Future bar time extrapolation with `disable_resolution_rebuild`.** Fixed an issue where future bar times would be extrapolated incorrectly when the `disable_resolution_rebuild` featureset was enabled, and daily bars that do not consider the January 1 to be the first day of the year were provided to the library.
- **Compare symbol legend context menu.** Fixed an issue where the context menu for compared symbols would show the _Add this indicator to favorites_ item.
- **Main series context menu.** Fixed an issue where the [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) for the main series would show a blank space instead of the _Add SYMBOL to watchlist_ item.
- **Watchlist item counter.** Fixed an issue where the watchlist item count would include section titles in its calculation.
- **Fixed an issue with time scale marks that couldn't contain any underscore character.**
- **Fixed a bug where `getBars` failed to display error messages containing semicolons.**
- **Fixed drawing keyboard shortcuts.** Fixed an issue where using keyboard shortcuts to add drawings would sometimes open the _Symbol Search_ dialog instead of adding the intended drawing.
### Documentation \{#v29_2-documentation} - **The following enhancements were made.**
- Added a new section explaining how to [display pre- and post-market price lines](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessionsenable-the-price-line). - Added a new section explaining how to [provide profit and loss values](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss) in Trading Platform. - Updated the [Trading Session](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessions) article with information on how to specify [session history](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessionssession-history)
--- ## Version 29.1.0 *Date: Fri Mar 07 2025* ### New Features \{#v29_1-feature} - **Added the _Another symbol_ input field to Moving Average Multiple, Moving Average Triple, and Pivot Points Standard.** This field allows users to specify a different symbol for calculating the indicator. By default, the current symbol on the chart is used.
#### Trading Platform only \{#v29_1-feature-tp-only} - **Pre-/post-market lines.** Added the `pre_post_market_price_line` featureset that allows you to enable or disable the pre-/post-market price lines. To display the pre-/post-market lines, you need to provide the `rtc` property in [quotes](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.DatafeedQuoteValues).
### Improvements \{#v29_1-improvement} - **Adds an offset input to the Bollinger Bands indicator.**
- **Allow overriding the default shortcuts.** Now, you can override the default shortcuts using the [`onShortcut`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#onshortcut) method. Note that modal dialogs shortcuts cannot be changed.
### Documentation \{#v29_1-documentation} - **New articles.** Explore our latest articles: - [Object tree](https://www.tradingview.com/charting-library-docs/latest/ui_elements/object-tree) — an overview of the feature. - [Quotes](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/quotes) — an article explaining the importance of quotes in Trading Platform.
- **Other updates.** The following enhancements were made: - Updated the guide on [how to add a custom page to the Account Manager](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-page-in-account-manager). It now describes how to make the symbol name clickable on the custom page. - Added a guide on how to troubleshoot when [quotes are not displayed or refreshed](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issuesquotes-are-not-displayed-or-refreshed). - Added a guide on how to troubleshoot [delays in Trading Platform UI elements](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issuesdelays-in-trading-platform-ui-elements). - Added a new FAQ — [Does the library set cookies](https://www.tradingview.com/charting-library-docs/latest/getting_started/Frequently-Asked-Questionsother-questions).
--- ## Version 29.0.0 *Date: Wed Feb 05 2025* This major release introduces new features and enhancements focused on expanding UI customization options. Users now have greater control over drawings and indicators, allowing for a more tailored and flexible experience. This release also includes several [breaking changes](https://www.tradingview.com/charting-library-docs/latest/releases/release-notesv29_0-breaking-change) that impact the library API. Consider them to ensure compatibility with your implementation. Key updates: - Better chart management with [leftmost bar visibility](https://www.tradingview.com/charting-library-docs/latest/releases/release-notesv29_0-leftmost_bar_visibility) - Advanced [customization](https://www.tradingview.com/charting-library-docs/latest/releases/release-notesv29_0-customize_order_and_position_lines) in Trading Platform - An alternative [loading mode](https://www.tradingview.com/charting-library-docs/latest/releases/release-notesversion-2810) - Enhanced [visualization](https://www.tradingview.com/charting-library-docs/latest/releases/release-notesv28_3-symbol_name_in_the_watchlist_and_details_widgets) in the Watchlist and Details widgets - Removal of [Trading API](https://www.tradingview.com/charting-library-docs/latest/releases/release-notesv29_0-removed_trading_api_methods_from_advanced_charts) methods from Advanced Charts For a detailed breakdown of changes, refer to the sections below. ### Breaking Changes \{#v29_0-breaking-change} - **Removed trading API methods from Advanced Charts.** The following methods are now available exclusively in Trading Platform. If you’re using Advanced Charts, these methods will no longer be accessible. - [`createOrderLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createorderline) - [`createPositionLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createpositionline) - [`createExecutionShape`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createexecutionshape)
- **Changed the `getPositionDialogOptions` signature.** The [`getPositionDialogOptions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerCommon#getpositiondialogoptions) method is asynchronous and returns a promise now. The method also expects a symbol as a parameter.
- **Broker API simplification.** To further improve and simplify the library, we have merged the two existing APIs, `IBrokerWithoutRealtime` and `IBrokerTerminal`, and now exclusively expose the latter. Additionally, we have removed the `subscribeDOM`/`unsubscribeDOM` methods, as they were rarely used and duplicated the functionality of [`subscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribedepth)/[`unsubscribeDepth`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#unsubscribedepth). This change ensures that the datafeed fully handles all data management responsibilities.
- **Removed the Anchored Note drawing.**
- **Renamed the Note drawing to Pin.**
- **Updated the default colors for drawings/indicators with Volume Profiles.**
- **Added MACD smoothing inputs.**
- **Drawing creation methods now return Promises instead of synchronous values.** The drawing creation methods ([`createShape`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createshape), [`createMultipointShape`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createmultipointshape), and [`createAnchoredShape`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createanchoredshape)) now return Promises that resolve to the drawing ID. The methods also throw an Error through a rejected Promise when the drawing creation fails, instead of returning `null`.
#### Trading Platform only \{#v29_0-breaking-change-tp-only} - **Trading Platform methods for drawing creation now return Promises instead of synchronous values.** The ([`createOrderLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createorderline), [`createPositionLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createpositionline), and [`createExecutionShape`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createexecutionshape)) methods now return Promises that resolve to the corresponding API interface.
### New Features \{#v29_0-feature} - **Added the _Another symbol_ input field to Ichimoku Cloud, Bollinger Bands, and Average Price.** This field allows users to specify a different symbol for calculating the indicator. By default, the current symbol on the chart is used.
#### Trading Platform only \{#v29_0-feature-tp-only} - **New properties for customizing order and position lines.** You can now override the style of order and position lines created with the [Broker API](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-conceptsbroker-api). The [`trading_customization`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#trading_customization) option in the Widget Constructor now supports `brokerOrder` and `brokerPosition` properties. For more details, see the [Trading Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/trading-overridescreated-with-broker-api) article.
### Improvements \{#v29_0-improvement} - **Added an option to keep the leftmost bar visible after resolution switching.** By default, the library resets the chart to the latest data when the resolution is changed. To keep the current time range, users can enable the Save chart left edge position when changing interval option in *Chart settings* → *Scales*.
- **Added option to hide/show scroll to the most recent bar button.** The presence of the *Scroll to the most* recent bar button now depends on the Navigation buttons settings (*Chart settings* → *Canvas* → *Buttons* → *Navigation*).
- **Added a new `paneIndex` getter to the `StudyAPI`.** The [`paneIndex`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IStudyApi#paneindex) function returns the index of the pane the indicator belongs to.
- **Enabled users to adjust coordinates of Parallel Channel within the drawing settings.**
- **Enabled users to reverse the Long/Short Position drawings.**
- **Buy/Sell buttons' visibility can now be changed for each chart in the layout.**
- **Added the Volume option for the Date Range and Date & Price Range tools.**
- **Added multiline option for Parallel Channel.** Additional level lines have been added.
- **Show price line of Heikin Ashi on real price when the real price label is selected.** On Heikin Ashi chart, the price line now matches the position of the *Last price* label when the *Real prices on price scale (instead of Heikin-Ashi price)* setting is enabled.
- **Added new time zone Azores (UTC-1).**
- **Added an error message for unsupported resolutions.** If the selected resolution is not supported by the current symbol, an error message appears on the chart along with a button to switch to a supported resolution.
- **Implemented dynamic loading for drawings to optimize bundle size.** Drawings have been refactored to utilize dynamic imports, reducing the initial bundle size by loading these components on-demand. This optimization results in faster initial page loads and improved application startup time, while maintaining full drawing functionality through lazy loading when tools are actually accessed by users.
- **Added a star icon to chart context menu for indicator.** This icon is displayed next to the _Add this indicator to favorites / Remove this indicator_ from favorites option in the indicator context menu.
#### Trading Platform only \{#v29_0-improvement-tp-only} - **Changed the return type for `OrderPreviewResult`.** When implementing [`previewOrder`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#previeworder), you can specify links to external URLs now. The links will be displayed within the `warnings` or `errors` block.
### Bug Fixes \{#v29_0-bugfix} - **Fixed unreliable onChartReady callback with cached bundles.** When using `iframe_loading_compatibility_mode` with cached library bundles, the `onChartReady` callback would sometimes fail to execute. Fixes [#8889](https)
- **Long/Short Position tools are extended to the right if the next bar crosses stop/profit level.** Fixed a bug where Long/Short Position would get partially extended to the right if the next bar crossed the stop/profit level.
- **Fixed hovering on the indicator legend.** Now, when an indicator is deleted via the legend, the hover state shifts to the legend of the next indicator below.
- **Fixed an issue when cloning drawings that were not selected.** Fixed a bug where _Ctrl+Drag_ would create copies of the last selected drawings on chart, even if they were no longer selected. Now, this shortcut enables area selection.
### Documentation \{#v29_0-documentation} - **New how-to guide.** Check out a new [guide](https://www.tradingview.com/charting-library-docs/latest/tutorials/add-custom-button-to-top-toolbar) on how to add a custom button to the top toolbar.
- **Other updates.** The following enhancements were made: - Added a new section that explains [multiple symbol resolving](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#multiple-symbol-resolving). - Updated information on how to [change colors of the *Buy/Sell* buttons](https://www.tradingview.com/charting-library-docs/latest/customization/styles/CSS-Color-Themesbuysell-buttons-properties). - Updated the [Toolbars](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Toolbars) article. - Added a new [section](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Chartexecute-action-by-id) that describes how to trigger specific actions, such as opening the *Chart settings* dialog, using the [`executeActionById`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#executeactionbyid) method. - Added an [overview](https://www.tradingview.com/charting-library-docs/latest/getting_started/product-comparison) of other TradingView products.
--- ## Version 28.5.0 *Date: Wed Dec 18 2024* **New Features** - **Added `baselinePosition` property for column series.** The [`baselinePosition`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ColumnStylePreferences#baselineposition) property allows column series to be drawn relative to the specified baseline value. - The default value is `'bottom'`, which draws columns with the bottom of the chart pane as their baseline. - Setting the value to `'zero'` draws columns with a baseline of 0, displayed as either 0% or 0.00 depending on the price scale mode. - **Added the _Another symbol_ input field to Moving Average Double.** This field allows users to specify a different symbol for calculating the indicator. By default, the current symbol on the chart is used. **Documentation** - **New how-to guide.** Check out a new [guide](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-page-in-account-manager) that explains how to create a custom page in the Account Manager. - **Other updates.** The following enhancements were made: - Added a new section that explains how to enable and specify [last day change values](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legendlast-day-change-values). - Updated information on [overnight sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Trading-Sessionsovernight-sessions). - Updated information on how to [close](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positionsclose-positions) and [reverse](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positionsreverse-positions) positions. - Updated API overview page. ## Version 28.4.0 *Date: Thu Nov 28 2024* **New Features** - **Added `includeOHLCValuesForSingleValuePlots` option when exporting data.** When set to `true`, this option forces all four OHLC plot values to be exported, even if the plot has a single value. This applies, for example, when the symbol has `visible_plots_set: 'c'` or when the exported plot is a single-value style (Area, Baseline, Line, Line with markets, Stepline, or Column). **Improvements** - **Added logging of quotes events.** Added extra logging of quote events when [debug mode](https://www.tradingview.com/charting-library-docs/latest/tutorials/enable-debug-modeenable-debug-mode-for-data-connection) is enabled. The logs will contain information about quote data requests, real-time subscribe and unsubscribe events, and alerts for data requests that do not respond within 10 seconds. **Bug Fixes** - **Fixed an issue where missing translations caused errors when opening the settings dialog of the Ichimoku Cloud indicator.** - **Fixed an issue where the Point and Figure series would not be displayed.** **Documentation** - **New articles.** Explore our latest articles: - [Positions](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions) — an article that overviews position types supported in the library and describes how to manage them. - [UI elements](https://www.tradingview.com/charting-library-docs/latest/ui_elements) — an overview of the library's UI elements. - [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news) — an article that explains how to connect data to the _News_ widget. - **Other updates.** The following articles were improved: - [NPM](https://www.tradingview.com/charting-library-docs/latest/getting_started/NPM) - [Custom themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes) - [CSS color themes](https://www.tradingview.com/charting-library-docs/latest/customization/styles/CSS-Color-Themes) - [Market Status](https://www.tradingview.com/charting-library-docs/latest/ui_elements/market-status) ## Version 28.3.0 *Date: Thu Oct 24 2024* **New Features** - **Symbol name in the Watchlist and Details widgets.** Now, the [`DatafeedQuoteValues.short_name`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.DatafeedQuoteValues#short_name) value is displayed as a symbol's short name in the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) and [Details](https://www.tradingview.com/charting-library-docs/latest/trading_terminaldetails). You can disable the [`prefer_quote_short_name`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsprefer_quote_short_name) featureset to revert to the old behavior. In this case, the [`ticker`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#ticker) value will be used instead.
**Bug Fixes** - **Anchored Note in multi-layout.** Fixed an issue where plotting a saved Anchored Note in multi-layout would raise an error.
- **Fixed symbol logo persistence in legend.** Resolved an issue where a failed image load (e.g., a 404 error) for a symbol logo would cause the previous logo to persist in the legend. Now, the legend correctly updates to reflect the absence of a logo when loading fails. See the [Symbol logos](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legendsymbol-logos) section of the Legend documentation for more details on the feature. - **Fixed ordering of symbol logos.** Fixed an issue where symbol logos with two URLs defined in [`logo_urls`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#logo_urls) were displayed in an inconsistent order. The order has been corrected on the chart legend and within the Account Manager table. ## Version 28.2.0 *Date: Tue Oct 01 2024* **New Features** - **Added `Rank Correlation Index` indicator.** - **Support building seconds bars from ticks.** Trading Platform now supports building seconds bars from ticks for symbols configured to support it. Compatible symbols must set the [`build_seconds_from_ticks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#build_seconds_from_ticks) flag to `true`. Additionally, [`has_seconds`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_seconds) and [`has_ticks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#has_ticks) must be `true`, and [`seconds_multipliers`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#seconds_multipliers) must be an empty array or only contain multipliers that the datafeed provides itself.
**Improvements** - **Added an option to customize the default Volume MA calculation in the Volume indicator.** By default, the Volume MA, optionally plotted in the Volume indicator, used the SMA calculation. We have now introduced two additional options: EMA and WMA. - **Added new event to `SubscribeEventsMap`.** The [`timeframe_interval`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap#timeframe_interval) event is triggered when the one of the bottom left intervals is selected or the [`setTimeFrame`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#settimeframe) API is used. - **Added a symbol change to MACD indicator.** It is now possible to change the targeted symbol when plotting MACD indicator without using the main series. - **Sped up sorting animation in the Account Manager.** Raised by [#8760](https)
## Version 28.1.0 *Date: Wed Sep 04 2024* **Breaking Changes** - **Deprecated API methods.** [`activateBottomWidget`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#activatebottomwidget) is now marked `deprecated`. Please use [`setAccountManagerVisibilityMode`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#setaccountmanagervisibilitymode) instead. If you want to retrieve the current state of the Account Manager please use [`getAccountManagerVisibilityMode`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#getaccountmanagervisibilitymode) **New Features** - **Added `iframe_loading_same_origin` featureset.** The `iframe_loading_same_origin` featureset ensures the library's iframe is loaded from the same domain as the `library_path` files. **Improvements** - **Added new event to `SubscribeEventsMap`.** The [`study_dialog_save_defaults`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap#study_dialog_save_defaults) event is triggered when the _Save as default_ option is selected in the indicator settings. - **Changed the return type for `OrderPreviewResult`.** When implementing [`previewOrder`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#previeworder), you can specify links to external URLs now. The links will be displayed within the `warnings` or `errors` block.
- **Added an item counter for custom pages.** By default, custom pages added to the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager) do not display the number of items in their corresponding table. Enabling [`displayCounterInTab`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerPage#displaycounterintab) will show this number next to the tab title.
**Bug Fixes** - **charting_library_debug_mode.** Fixed an issue where enabling the featureset `charting_library_debug_mode` was of no effect. - **Instant display of refreshed marks.** Fixed an issue where new [marks](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Marks) added after calling [`refreshMarks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#refreshmarks) were not immediately displayed on the chart. Previously, these marks only appeared after user interaction, but now they are instantly visible once the data is provided. - **Fixed an issue with `multiple_watchlists` featureset.** When the `multiple_watchlists` featureset was disabled, it was still possible to see the `Create a new list` option under the Watchlist drop-down menu. **Documentation** - **New how-to guide.** Check out a new guide on [enabling debug modes](https://www.tradingview.com/charting-library-docs/latest/tutorials/enable-debug-mode) to help identify potential issues when implementing your app and ensure it is running smoothly. ## Version 28.0.0 *Date: Wed Aug 14 2024* **Breaking Changes** - **Removed `full_name`.** The `LibrarySymbolInfo.full_name` property was removed from public API. The property contained strings in the `'EXCHANGE:SYMBOL'` format and was used to request data from the datafeed. Therefore: - Now, you should use either the [`name`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#name) or [`ticker`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#ticker) property to specify an identifier for a certain symbol. For more information, refer to the [Symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologysymbol-name) article. - Instead of `'EXCHANGE:SYMBOL'`, the library will send either `name` or `ticker` values to the datafeed when calling methods such as [`getBars`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#getbars), [`getQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#getquotes), and [`subscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi#subscribequotes). - The `'EXCHANGE:SYMBOL'` strings are no longer displayed in the Trading Platform UI. The symbol name will be used instead. You can disable the [`prefer_symbol_name_over_fullname`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsprefer_symbol_name_over_fullname) featureset to revert to the old behavior.
- **Deprecated API methods.** The following methods are now marked `deprecated` for the Advanced Charts users. - [`createOrderLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createorderline) - [`createPositionLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createpositionline) - [`createExecutionShape`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createexecutionshape) These methods will be removed from the Advanced Charts library in the next major version. However, they will still be available in Trading Platform. - **Make `cancelOrders` optional.** The [`cancelOrders`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#cancelorders) method is marked as optional because the library calls it only for the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminaldepth-of-market) widget.
- **Removed the `calculatePLUsingLast` flag.** The `calculatePLUsingLast` [broker configuration flag](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-features-configuration) has been removed.
- **Symbol search dialog behavior.** Previously, when users pressed _Enter_ in the [_Symbol Search_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search) dialog, they could enter arbitrary input directly. This input was passed to the datafeed for resolution and loading, regardless of whether the input matched any search results.
Now, pressing _Enter_ selects the top search result unless the user has explicitly chosen another item. If there are no search results, pressing _Enter_ will have no effect. You can enable the [`allow_arbitrary_symbol_search_input`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsallow_arbitrary_symbol_search_input) featureset to use the old behavior. - **Change custom translation API.** Change the [custom_translate_function](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_translate_function) interface to accept different parameters: the original text, the singular original text, and the translated text. For example "prices", "price", "prix". - **Changed the behavior of data display in the Depth of Market widget.** Now, data is displayed in static mode. This means that the price series is fixed, while the current price moves within, above, or below the designated range. To center on the current price, click the centering button () or use the *Shift + Alt/Option + C* shortcut. Previously, centering was applied dynamically. - **Renamed the Symbol Info dialog.** The _Symbol Info_ dialog and the corresponding items in context menus are called _Security Info_ now. [#8444](https) - **Renamed ErrorCallback to DatafeedErrorCallback.** `ErrorCallback` used in `IDatafeedChartApi` has been renamed to `DatafeedErrorCallback`. - **Updated `selectedCurrency` behavior.** In `CurrencyInfo`, the [`selectedCurrency`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CurrencyInfo#selectedcurrency) property now returns `null` instead of `"Mixed"` when price scales contain mixed currencies. - **Deprecated property.** The `brokerConfig` property in the [`TradingTerminalWidgetOptions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions) interface is deprecated and will be removed in the next major release. Use the [`broker_config`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#broker_config) property instead. **New Features** - **New Custom themes API.** This API allows you to customize colors of the chart elements including toolbars, dialogs, and buttons. To do this, you should specify your own theme with a custom color palette. For more information, refer to the [Custom themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes) article. - **Added Volume Candles chart style.** This chart style allows for a visual assessment of the volume of trades for each candle. These are still candlesticks, but the width of each candle depends on the volume of trades during the period of formation of this candle. The greater the trading volume during the formation period of the candle, the larger the width of the candle. To display Volume Candles, select the corresponding option in the drop-down menu on the top toolbar. **Improvements** - **Behavior change for `chartContextMenuActions`.** When the [`chartContextMenuActions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#chartcontextmenuactions) method returns an empty array, the _Trade_ item within the chart [context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) will not be displayed. Previously, the item was rendered but grayed out.
- **Added the `library_custom_fields` property to the `LibrarySymbolInfo` interface.** This property is used to include additional metadata in the symbol information. The metadata will not be processed by the library. - **Added extra properties to `symbolExt` method.** The [`symbolExt`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#symbolext) method now returns additional properties including `ticker`. - **Added the `debug_broker` option to the Widget Constructor.** When [`debug_broker`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#debug_broker) is specified, the library logs calls and responses to [`IBrokerTerminal`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal) and [`IBrokerConnectionAdapterHost`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost) in the browser console. You can set `debug_broker` to one of the debug levels defined by [`BrokerDebugMode`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#brokerdebugmode).
- **Updated the Anchored VWAP drawing.** Add bands settings to the Anchored VWAP drawing. - **Added new methods to the Trading Host.** The `getOrderTicketSetting` and `setOrderTicketSetting` methods have been added to the [`IBrokerConnectionAdapterHost`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost) interface. These methods allow you to read and adjust Order Ticket settings.
- **Changed `const enum` to `enum` in the library type declarations.** This change allows you to import enums from the library in a TypeScript environment with the [`isolatedModules`](https) option enabled, such as when using Vite or similar tools. - **Added the `hideStudiesFromLegend` option to `ClientSnapshotOptions`.** When `hideStudiesFromLegend` is set to true, the legend within the generated screenshots won't contain any studies applied to the chart. - **Exposed `connectionStatusUpdate` from `IBrokerConnectionAdapterHost`.** An existing [`connectionStatusUpdate`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#connectionstatusupdate) API has been exposed for [`IBrokerConnectionAdapterHost`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost) to help reflect connection status changes throughout the application lifecycle.
- **New keyboard shortcuts.** The following [shortcuts](https://www.tradingview.com/charting-library-docs/latest/getting_started/Shortcuts) were added: - _Shift_ + _Mouse wheel_ — scroll the chart horizontally - _Shift_ + _Alt_ + _B_ — place limit order to buy - _Shift_ + _Alt_ + _S_ — place limit order to sell - **Enabled in-place editing for drawing texts.** For the following drawings, users can now add custom text and edit it on the chart: - _Fib Retracement_ - _Trend-based Fib Extension_ - _Horizontal_ and _Vertical Line_ - _Trend Line_ - _Info Line_ - _Ray_ - _Extended Line_ - _Signpost_ - _Note_ - _Anchored Note_ - _Comment_ - _Rectangle_ - _Ellipse_ - _Circle_ To enter the text, users should click the _+Add text_ placeholder that appears on hover. - **Disabled color pickers in Chart settings.** If a certain price label or line is hidden on the chart, users cannot adjust the color of this label/line in the _Chart settings_ dialog. - **Time zones.** Time zone updates: - Changed the Almaty (UTC+6) time zone to Astana (UTC+5). - Added the new Kuala Lumpur (UTC+8) time zone. - **Visibility of price labels for risk-reward drawings.** Previously, price labels for the _Long position_ and _Short position_ drawings could be either hidden entirely or always displayed. Now, if the price labels are disabled for a certain drawing, the labels will be displayed when the drawing is selected. - **Accessibility improvement.** Users can now select the following elements in the _Legend_ when navigating with the keyboard. - The _More_ () button and items in the corresponding menu - The _Remove_ () button - **Added new multiple-chart layouts combinations.**
- **New style settings for the Note drawing.** Now: - The _Background_ and _Border_ settings are optional. - The default color of the drawing depends on the current chart [theme](https://www.tradingview.com/charting-library-docs/latest/customization/theme). **Bug Fixes** - **Fixed the _Pivot Points Standard_ compatibility with Japanese chart types.** The _Pivot Points Standard_ indicator used to cause the _Assertion failed: data must have unique sorted times_ error when applied to chart types such as Line Break, Renko, Kagi, and Point-and-Figure under certain data conditions. - **Workaround for corrupted chart layouts.** In rare cases, chart layouts can become corrupted and cause a _DEFAULT_SYMBOL is not defined_ error when loaded by the library. To work around this error, set [`symbol`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#symbol) to be used as a fallback for any corrupted charts. - **Fixed an issue where 0-volume data were not displayed in the Legend.** [#8662](https) - **Fixed the time indicator.** The time indicator now correctly moves across the timeline in the [Market Status](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Status) pop-up. - **Fixed resizing for risk-reward tools.** The resizing of _Long position_ and _Short position_ drawings works correctly now. [#8513](https) - **Fixed changing of drawing coordinates.** The setting dialog used to crash when users changed coordinates of drawings such as _Anchored Volume Profile_, _Fixed Range Volume Profile_, and _Regression Trend_. - **Fixed the drawing settings bug.** Previously, when users clicked _Hide/Show_ on a drawing, the settings applied to this drawing would override the default ones. Now, changing drawing visibility does not affect the default settings. [#8434](https) - **Fixed colors of the scale buttons.** The colors of the _A_ (auto) and _L_ (log) scale buttons match the chart background color now. [#8459](https) - **Fixed bugs on the multiple-chart layout.**
The following bugs were fixed: - The _Long/Short Position_ drawing used to cause errors if the drawing was hidden for a certain resolution and that resolution was currently displayed on the chart. - Synchronized _Path_ and _Polyline_ drawings were not displayed on larger resolutions if the first two points of the drawing were set at the same level on a smaller resolution. - The _Curve_ and _Double Curve_ drawings used to cause errors if a user moved the drawing before enabling layout synchronization. - Changing the Profit/Stop level of the synchronized _Long/Short Position_ drawing used to cause errors if the drawing was hidden for a certain resolution and that resolution was currently displayed on the chart. **Documentation** - **Updated types for overrides.** The following categories of overrides within the [`ChartPropertiesOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides) have been added or updated: - Added types for the Step line chart style (`mainSeriesProperties.steplineStyle.*`). - Updated the types for `paneProperties.*`. - Added overrides that affect Trading Platform features (`tradingProperties.*`). - **New articles.** Explore our latest articles: - [How to create a custom indicator](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator) — a step-by-step tutorial that demonstrates the Moving Average implementation. - [Custom indicators. Inputs](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo/Custom-Studies-Inputs) — an overview of how to specify and manage input parameters for a custom indicator. - [Authentication](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/authentication) — an article that outlines possible authentication approaches.
## Version 27.006 *Date: Tue May 21 2024* **Bug Fixes** - **Resolve quotes with ticker instead of symbol name.** The library will now request quote data using the [`ticker`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#ticker) property. If `ticker` is not provided in the `LibrarySymbolInfo` object, the `name` property will be used instead. This should resolve an issue some customers were experiencing where quote data was not being properly displayed in the [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) and [Legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend). ## Version 27.005 *Date: Tue May 07 2024* **Improvements** - **Update the Anchored AVWAP drawing.** Add bands settings to the Anchored VWAP drawing. - **Subscribe to widget bar visibility events.** A new [`study_event`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap#study_event) type was added: `widgetbar_visibility_changed`. It returns the visibility state of the widget bar. **Bug Fixes** - **Fixed a bug in the Market Status pop-up.** [Corrections](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessionscorrections-for-extended-sessions) specified for the extended session in the [`session-correction`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySubsessionInfo#session-correction) properties were not displayed in the _Market Status_ pop-up window. ## Version 27.004 *Date: Wed Apr 17 2024* **Breaking Changes** - **Fixed time parameters in CrossHairMovedEventParams.** In version 26.001, we changed the `time` property of [`CrossHairMovedEventParams`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CrossHairMovedEventParams) to be a timestamp in the selected time zone. In this version, we reverted that change, and `time` represents a UTC timestamp again. Additionally, we introduced a new [`userTime`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CrossHairMovedEventParams#usertime) property that represents a timestamp in the selected time zone. **Improvements** - **Added ability to disable pulse animation when chart type is set to Line.** New _disable_pulse_animation_ featureset allows users to disable the pulse animation when chart type is set to Line. **Bug Fixes** - **Fixed the price scale placement.** The [price scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale) should be placed back to its original position when a change made through the _Settings_ dialog is canceled. Fixes [#4991](https) - **Fixed the 52 Week High/Low indicator issue.** The 52 Week High/Low indicator no longer adds an empty space to the price scale when less than 52 weeks of historic bars are available. Fixes [#8137](https) [#8469](https) - **Only calculate VWAP value when entire anchor period is loaded.** The VWAP indicator will only calculate values for the input anchor period if all bars in that period have been loaded. - **Fixed a trailing stop modification dialog error.** Fixed a problem where opening the Order Ticket for a trailing stop position caused a "ReferenceError: isPositionLikeItem is not defined" error to be thrown. - **Fixed the incorrect point position for the Long Position drawing.** The `getPositionPoints()` method will now return correct point positions. Fixes [#8230](https) - **`BREAKING CHANGE` Position line price label does not use the correct price formatter.** The price scale will now correctly reflect the value when a formatter is used with [`createPositionLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createpositionline). Both [`createOrderLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createorderline) and [`createPositionLine`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createpositionline) methods behave similarly to the corresponding actions made in the UI via [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket). Fixes [#8413](https) [#8324](https) **Documentation** - **New User accounts article.** Refer to [User accounts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/user-accounts) for information on how to manage user accounts in the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager). - **Session documentation updates.** The [Symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologysession) and [Extended sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions) articles now include more information on how to specify sessions and corrections for them. - **New Save user settings article.** Refer to the [Save user settings](https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings) article for information on how to store user settings. - **Updated Watchlist article.** Explore our latest [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) article that describes how to customize and handle the watchlist's data. ## Version 27.003 *Date: Thu Mar 14 2024* **Improvements** - **Added the resetLayoutSizes method.** Use [`resetLayoutSizes`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#resetlayoutsizes) to reset the sizes of all charts within a multiple-chart layout back to their initial default values.
- **Added the unloadUnusedCharts method.** The [`unloadUnusedCharts`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#unloadunusedcharts) method deletes non-visible charts from a multiple-chart layout. Use this method to prevent the library's inherent behavior to restore previously displayed charts instead of creating new charts when changing layouts.
- **Added a new type that reflects the ID of the created indicator.** A new [`study_event`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap#study_event) type was added: `create`. It returns the `id` of the newly created indicator. **Bug Fixes** - **Displaying volume indicator on chart load when visible_plots_set is not specified.** The chart will now correctly display the volume indicator if the `create_volume_indicator_by_default` featureset is enabled even if the symbols [LibrarySymbolInfo](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) doesn't specify the optional [`visible_plots_set`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#visible_plots_set) property. - **Prioritise widget constructor symbol over saved state.** The [`symbol`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#symbol) property in the widget constructor will now have priority over symbols loaded from saved chart states when using [`saved_data`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#saved_data) or [`load_last_chart`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#load_last_chart). Fixes [#7922](https) [#8473](https) [#7926](https) [#8168](https) - **Fixed an issue where the time_frames description was ignored.** ## Version 27.002 *Date: Thu Feb 22 2024* **Improvements** - **Add positive and negative filled areas to Spread.** The Spread indicator now has a positive and negative filled area above and below the baseline value of 0. The colors of the filled areas are green and red respectively. **Bug Fixes** - **Brush drawing_event is now raising a `create` event when starting drawing.** **Documentation** - **Improved drawing documentation.** Explore our latest articles about drawings. - New [Drawings API](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api) article describes how to manage drawings in the code. - Updated [Drawing Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Drawings-Overrides) article now includes more information on how to customize drawings. ## Version 27.001 *Date: Fri Feb 2 2024* **Improvements** - **Custom indicators can now dynamically hide indicator inputs in the legend when plots are hidden.** The `hideWhenPlotsHidden` option has been added for a custom indicator's input. It enables you to hide an input's value in the legend text when the user hides all of the specified plots. **Bug Fixes** - **Allow studies that extend the time scale to load historic bars before the leftmost bar of the main series.** **Documentation** - **New articles** - [Context menu](https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu) - [Orders](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders) - [Snapshots](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Snapshots) ## Version 27 *Date: Wed Jan 17 2024* **Breaking Changes** - **Custom study plot style text property moved.** The chars and shapes custom study plots `text` style property was moved from `metainfo.defaults.styles.[plot id].text` to `metainfo.styles.[plot id].text`. See this GitHub issue for more details [#8184](https) - **Changed context menu behavior of the 'Plus' button and removed the 'show_context_menu_in_crosshair_if_only_one_item' featureset.** Now, the context menu of the *Plus* button opens even if the menu has only one item. Previously, the item's action was immediately executed if there was only one item in the context menu. Additionally, the `show_context_menu_in_crosshair_if_only_one_item` featureset has been removed. **Breaking Changes: Trading Platform** - **Changed parameter type in the showPositionDialog method.** The `position` parameter type of the [`showPositionDialog`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerCustomUI#showpositiondialog) method in the [`BrokerCustomUI`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerCustomUI) interface has been changed to `Position | IndividualPosition`. - **Renamed flags in the BrokerConfigFlags interface.** The following flags have been renamed in the [`BrokerConfigFlags`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags) interface: - `supportTrades` flag has been renamed to `supportPositionNetting`; - `supportTradeBrackets` flag has been renamed to `supportIndividualPositionBrackets`; - `supportCloseTrade` flag has been renamed to `supportCloseIndividualPosition`; - `supportPartialCloseTrade` flag has been renamed to `supportPartialCloseIndividualPosition`; - `requiresFIFOCloseTrades` flag has been renamed to `requiresFIFOCloseIndividualPositions`. - **Renamed TradeBase and Trade interfaces.** The `TradeBase` interface has been renamed to [`IndividualPositionBase`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IndividualPositionBase) and the `Trade` interface has been renamed to [`IndividualPosition`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IndividualPosition) respectfully. All fields and their types has been left unchanged. - **Renamed tradeColumns field in the AccountManagerInfo interface.** The `tradesColumns` field in the [AccountManagerInfo](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Broker.AccountManagerInfo) interface has been renamed to `individualPositionColumns`. - **Renamed Trade member to IndividualPosition in the ParentType enum.** The `Trade` member of the [`ParentType`](https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.ParentType) enum has been renamed to `IndividualPosition`. - **Renamed trade related methods in the IBrokerConnectionAdapterHost interface.** The following methods in the [`IBrokerConnectionAdapterHost`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost) have been changed: - the `tradeUpdate` method has been renamed to [`individualPositionUpdate`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#individualpositionupdate). The `trade` parameter of the method has been renamed to `individualPosition`. Also, the type of that parameter has been changed to `IndividualPosition`; - the `tradePartialUpdate` method has been renamed to [`individualPositionPartialUpdate`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#individualpositionpartialupdate). The type of the `changes` parameter has been changed to `Partial`; - the `tradePLUpdate` method has been renamed to [`individualPositionPLUpdate`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#individualpositionplupdate); - the type of the `position` parameter of the [`showPositionBracketsDialog`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#showpositionbracketsdialog) method has been changed to `Position | IndividualPosition`. - **Renamed methods in the IBrokerWithoutRealtime interface.** The following changes have been made in the [`IBrokerWithoutRealtime`](https) interface: - The `closeTrade` method has been renamed to `closeIndividualPosition`; - The `editTradeBrackets` method has been renamed to `editIndividualPositionBrackets`. - **Renamed trade method in the IBrokerCommon interface.** The `trades` method in the [`IBrokerCommon`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerCommon) has been renamed to `individualPositions`. The return type of that method has been changed to `Promise`. - **Removed the Order Panel button from the right toolbar.** To open [_Advanced Order Ticket_](https://www.tradingview.com/charting-library-docs/latest/trading_terminaladvanced-order-ticket), users should use the _Trade_ button in _Account Manager_ now. **New Features** - **Enabled in-place editing in Legend.** Users can change a symbol and resolution right from the [_Legend_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend) now. [#7966](https) - **Added Quick Search.** The _Quick Search_ dialog allows users to search for drawings, UI settings, and functions, such as _Remove Indicators_. To open this dialog, users should click the _Quick Search_ button on the top toolbar or use the _Ctrl/Cmd_ + _K_ shortcut. - **Added ability to show daily change in the chart legend.** New _Last day change values_ option allows users to show/hide the last day change values in the main series legend. To make this option available in the _Chart Settings_ dialog, use the [`legend_last_day_change`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetslegend_last_day_change) featureset. [#8193](https) - **Updated drawing icons.** New icons for the _Text_, _Anchored Text_, _Note_, and _Anchored Note_ drawings. [#8181](https) **Improvements** - **`BREAKING CHANGE` Refactoring of the Ichimoku Cloud indicator.** Following feedback we've re-written the Ichimoku indicator and have brought the following changes: - 'Leading Span B' input is now 'Leading Span Periods'. - 'Lagging Span' input is now 'Lagging Span Periods'. - 'Leading Shift Periods' is a brand new input that aligns better to the original definition of the indicator. - Previously, 'Lagging span' was shifting both cloud and lagging lines. This should no longer apply as 'Leading Shift Periods' now handles the offset change for 'Lagging Span'. - **`BREAKING CHANGE` Inputs renaming for Stochastic indicator.** Inputs for the Stochastic indicator have been renamed for consistency across our products. - **`BREAKING CHANGE` Broker API clean up.**
The `positionDialogOptions` object has been removed from the Broker's Configuration. Please use the `getPositionDialogOptions` method to customize the Position dialog. - **Added new keyboard navigation shortcut.** Starting from version [26.002](https://www.tradingview.com/charting-library-docs/latest/releases/release-notesversion-26002), the library supports a keyboard navigation activated via the _Alt/Opt_ + _Z_ shortcut. Now, you can change this default navigation shortcut to _Tab_. To do this, enable the new [`accessible_keyboard_shortcuts`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsaccessible_keyboard_shortcuts) featureset. For more information, refer to [Keyboard navigation](https://www.tradingview.com/charting-library-docs/latest/getting_started/accessibilitykeyboard-navigation). - **Added ability to cancel order dragging by pressing Esc.** If a user presses _Esc_ while dragging the order, the order will be returned to its initial position. **Bug Fixes** - **Market status text during pre-market and post-market sessions.** The countdown text in the market status pop-up tooltip (in the legend area) has been fixed for pre-market and post-market sessions. The market status icon now shows an orange sunrise icon for pre-market and a blue moon icon for post-market. - **Floating drawing toolbar context menu.** It wasn't possibly to override the context menu for the floating drawing toolbar. - **Missing translation for No data here.** No data here message that is displayed on the chart whenever no bars are returned for a given symbol was missing its translation. - **Disabling the 'open_account_manager' featureset now works as expected.**
- **Order Panel Custom Input Fields Reactivity.**
The reactivity of UI elements within the order panel when using custom fields has been improved (Fixes [#6607](https)). - **Fixed the pane buttons on the collapsed pane.** The pane buttons used to overlap the _Scroll to the Most Recent Bar_ button when the pane is collapsed. [#8213](https) - **The precision setting can be applied to all charts now.** To do this, users should specify precision in the _Chart settings_ dialog and click the _Apply to all_ button. [#8343](https)
- **Fix the color of high/low price label.** Now, the color of high/low labels on the price scale corresponds to the color of the high/low lines. Users can specify this color in the _Chart settings_ dialog. [#8255](https) **Documentation** - **Chart customization precedence article added.** The library offers multiple approaches for changing the chart appearance and behavior. Explore our latest article on [customization precedence](https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedence) for a comprehensive understanding of customization methods/properties and the sequence in which they are applied. - **Order Ticket dialog article added.** Refer to [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) to learn how to provide custom fields, enable an order preview, implement your custom Order Ticket, and more. - **New how-to guide on metainfo.** Explore our latest [guide](../tutorials/create-custom-indicator/metainfo-implementation) on how to implement the `metainfo` field when you create a custom indicator. For more information about custom indicators and `metainfo`, refer to the updated [Custom indicators](https://www.tradingview.com/charting-library-docs/latest/custom_studies) and [Metainfo](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo) articles. - **Bracket orders article added.** Explore our latest article on [bracket orders](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/brackets) in Trading Platform. - **Account Manager article added.** Refer to [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager) for more information on creating pages, customizing columns, and configuring the Account Manager behavior. - **Accessibility article added.** Refer to the new [Accessibility](https://www.tradingview.com/charting-library-docs/latest/getting_started/accessibility) article for information about accessibility features that the library includes. - **Other documentation updates.** The new documentation version includes: - Updated [Resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution) and [Price Scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale) articles. - A full list of overrides for built-in indicators. Refer to the [Indicator Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrideslist-of-overrides) article for information. **Other** - **`BREAKING CHANGE` Deprecated customFormatters and brokerFactory.** Use [`custom_formatters`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_formatters) and [`broker_factory`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#broker_factory) instead. - **`BREAKING CHANGE` Deprecated RawStudyMetaInfo.precision.** Use the [`format`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RawStudyMetaInfo#format) property instead. For more information, refer to the [Metainfo](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo) article. ## Version 26.004 *Date: Thu Nov 16 2023* **New Features** - **Add methods to handle trading quantity.** The broker API now exposes a getter [getQty](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#getqty) and a setter [setQty](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#setqty) along with a subscription [subscribeSuggestedQtyChange](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#subscribesuggestedqtychange) and its dependant to unsubscribe [unsubscribeSuggestedQtyChange](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#unsubscribesuggestedqtychange). **Improvements** - **Added anchor option to VWAP indicator.** The VWAP indicator now has input options for source and anchor. - Source allows customisation of the price source for the indicator. Defaults to `hlc3`. - Anchor period setting specifies how frequently the VWAP calculation will be reset. This Defaults to `'Session'`. **Bug Fixes** - **VWAP Indicator behaviour.** The default behaviour for the VWAP indicator has been fixed. Previously it would anchor to the earliest available data point instead of the start of each session. - **Displaying DOM widget data on non-tradable symbols.**
When a symbol is non-tradable (`isTradable()` in the Broker API is returning `false`) it is now possible to display depth data in the DOM widget provided via the datafeed. - **The price source text is visible in the screenshot.** - **Fix display of price sources in Overlay study.** Price sources for symbols in the Overlay study were not being shown when the main series symbol did not have the same price source - **Both Trend Strength Index and Linear Regression Slope indicators were missing their zero-based property to properly plot them using a histogram.** - **onChartReady inconsistency on Safari.** Fixed an issue where `onChartReady` wouldn't reliably get called on specific versions of Safari. **Documentation** - **New article on core trading concepts.** We have added a new article describing [trading concepts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts) in Trading Platform. Learn how to integrate trading functionality into your application using the Broker API and Trading Host. ## Version 26.003 *Date: Thu Oct 05 2023* **Bug Fixes** - **Do not save to localstorage when the use_localstorage_for_settings feature is disabled.** Fixed a bug where use_localstorage_for_settings did not stop some settings from being saved to localstorage. - **Disabling `drawing_templates` completely removes the ability to save it when using line tools.** - **Renaming a section within watchlist was throwing an error.** - **Fixed an issue where it wasn't possible to set the background colour of a Renko bar to transparent.** ## Version 26.002 *Date: Mon Sep 18 2023* **Improvements** - **IOrderLineAdapter and IPositionLineAdapter now support positioning with pixel units.** The [setLineLength](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IOrderLineAdapter#setlinelength) method in the IOrderLineAdapter (returned by [createOrderLine](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createorderline)) and IPositionLineAdapter ([createPositionLine](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createpositionline)) interfaces now support setting the unit to `'pixel'`. - Additionally, when using pixel unit, you can specify a negative number to position from the left edge of the chart instead. - **Added keyboard navigation.** Keyboard navigation (activated via alt/opt + z keyboard shortcut) and many other accessibility improvements have been added to the library. - A featureset `accessibility` (on by default) has been added to control this behaviour. - **Menu name is provided to items_processor (context menu API).** [items_processor](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ContextMenuOptions#items_processor) within the [context_menu](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#context_menu) API now includes details about the name of menu, and the ids of the related item (such as the series, drawing, study, order, or position). - **Support more kinds of extended sessions.** The library now supports specifying only one of the postmarket or premarket sessions without the other. **Bug Fixes** - **On mobile devices, fixed an issue for when scrolling the pricescale with one finger while another one was holding the crosshair.** - **Fixed an issue where it wasn't possible to set the background colour of a candle to transparent.** - **52 Week High/Low indicator compatibility with empty supported_resolutions array.** Fixes [#7884](https) issue. - **Fixed an issue where any added indicator on the chart couldn't be undone.** - **Fixed issue with locking visible time range while resizing chart.** When resizing the chart window with percentage right margin, and the `lock_visible_time_range_on_resize` featureset enabled then the visible range wasn't locked correctly. - **SuperTrend Indicator Starting Point.** The SuperTrend would previously start drawing from zero for the first bar, instead of only drawing the indicator after the initial length (defined in the indicator's inputs) when all the possible data for a symbol has been loaded. - **Changing the LineStyle for a position is again available.** - **Styles tab for Pivot Point Standard indicator.** Resolved an issue where the style tab for the Pivot Point Standard indicator would not function correctly when the type option was set to 'Floor'. **Other** - **Custom Translation Function.** The following changes have been made to the [custom_translate_function](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_translate_function) - The interface name for the options has changed from `TranslateOptions` to `CustomTranslateOptions`. - The `plural` field in `CustomTranslateOptions` can now be either a single string, or an array of strings. - A third boolean argument is now provided. When this is true then the key provided is already translated. ## Version 26.001 *Date: Tue Aug 08 2023* **New Features** - **Add series and study values to crosshair move event.** The [`crossHairMoved` subscription](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#crosshairmoved) now exposes the study and series values in the event object. The values are the same as the values shown in the data window. - **Adding a new Floor type for calculating Pivot.** - **Add the onHoveredSourceChanged method to the widget API.** See [`onHoveredSourceChanged`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#onhoveredsourcechanged). **Improvements** - **Added optional variable_tick_size property to symbol info.** - **Added onMoving to the Order Line Adapter.** [onMoving](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IOrderLineAdapter#onmoving) **Bug Fixes** - **Selecting an incorrect symbol within a study no longer prevents the study from recovering when a valid symbol is chosen later.** - **Fix drawing tools not affecting undo/redo stack and chart layout saving buttons.** Drawing actions can now be undone/redone and will affect the saving of the chart layout - **Disabling the 'open_account_manager' featureset now works as expected.** **Other** - **Watchlist sections featureset added for adjusting the visibility of the 'Add Section' button.** The UI for creating watchlist sections can now be hidden by disabling the [watchlist_sections](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetswatchlist_sections) featureset. ## Version 26 *Date: Tue Jul 18 2023* **Breaking Changes** - **Remove Lines item and submenu from background and symbol context menu.** The "lines" item has been removed from the context menu of the chart and the legend of the main series. **New Features** - **In bottom toolbar, tooltip text for date ranges has changed.** Hovering over the time frame buttons will provide more details to understand how chart is constructed. - **Add setting for visibility of A (auto) and L (log) scale buttons.** In Chart settings, Scale tab, a new setting has been introduced to enable shortcuts for Auto & Logarithmic modes. - **Bug in compare data displayed in Data window.** There was an issue where OHLC values would only be displayed in the data window widget when using the cross hair selection instead of displaying the data from the latest available bar if nothing was selected. Fixes [#7769](https) - **Update chart maximization icon and remove animation.** Maximization button restyled - **Price scale resizing while scrolling chart in mobile browser.** When scrolling into history the price scale expands to accommodate the values, but doesn't retract when the values become shorter. This is done to make the scale less twitchy during scrolling. The scale's width is reset on data loading. **Improvements** - **Fixed a bug where on some DPR there was no separator between the right widget panel and the order panel.** Now the separator line is always visible. - **No bracket settings in chart settings.** Bracket settings were added to the Chart settings in the Trading tab. - **Symbol logos within the Legend and Account Manager.** Symbol logos can now be displayed within the [Legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legendsymbol-logos) and the Account Manager panel (
) if the `show_symbol_logos` featureset is enabled. - `show_symbol_logo_in_legend` featureset can be disabled to hide the logos within the legend. - `show_symbol_logo_for_compare_studies` featureset can be disabled to hide the logos within the legend for compare overlay studies. - `show_symbol_logo_in_account_manager` featureset can be disabled to hide the logos within the Account Manager panel (
). - **Added setter and getter methods for CSS custom properties defined within the iframe.** The widget API now includes [setCSSCustomProperty](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#setcsscustomproperty) and [getCSSCustomPropertyValue](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#getcsscustompropertyvalue) methods for controlling CSS custom properties within the chart's iframe element. **Other** - **Deprecated properties and methods.** The following properties and methods are marked as deprecated and will be removed in the next major release: - `customFormatters` in the [ChartingLibraryWidgetOptions](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions) interface. Use [`custom_formatters`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_formatters) instead. - `customFormatters` and `brokerFactory` in the [TradingTerminalWidgetOptions](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions) interface. Use [`custom_formatters`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#custom_formatters) and [`broker_factory`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#broker_factory) instead. ## Version 25.002 *Date: Wed Jul 12 2023* **New Features** - **Add 52 Week High/Low study.** - **Enable hiding price scales when all studies or series are hidden.** Adds the `hide_price_scale_if_all_sources_hidden` feature. When enabled price scales will be hidden when all studies (or the main series) attached to the price scale are hidden. - **Option to always show legend values for studies on mobile.** By default, when on mobile, the legend won't display any values for studies. Enabling this new `always_show_legend_values_on_mobile` featureset allows you to display the values. **Improvements** - **Sections can now be added within the Watchlist.** Sections dividers can now be added within the watchlist (
). - Any item within a list which is prefixed with `###` will be considered a section divider. [API Reference](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#watchlist) - **Symbol and exchange logos can now be shown within the Compare Dialog.** The [symbol info](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) provided by [resolveSymbol](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol) should now include 'exchange_logo' if you would like to use the 'show_exchange_logos' featureset. **Bug Fixes** - **Watermark API's content provider is now used for all charts within a multi-chart layout.** - **Fixed issue with resetData.** When resetting the data for a chart, any existing studies would become unlinked from the data source. Fixes [#7802](https) - The `request_only_visible_range_on_reset` featureset now defaults to `disabled`. ## Version 25.001 *Date: Mon Jun 26 2023* **Breaking Changes** - **price_sources moved to symbol info.** To allow price sources resolved on-demand with the associated symbol the `price_sources` property has been removed from [the datafeed configuration object](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration) and added to the [symbol info object](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo). **New Features** - **Added Market status state getter.** [marketStatus](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#marketstatus) method is provided within [IChartWidgetApi](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi) which returns a watched value of the charts symbols current [market status](https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.MarketStatus). - **Symbol and exchange logos.** It is now possible to specify logo images for symbols and exchanges. These will be visible within the search dialog, and watchlist (Trading Platform). The `show_symbol_logos` and `show_exchange_logos` featuresets should be enabled, and your datafeed should be updated to provide urls as part of the symbol info supplied by the `resolveSymbol` method, and results supplied by the `searchSymbols` method. - **Enable custom studies to extend the time scale.** Enable custom studies to extend the time scale with points that don't exist in the main series. - [See this article for more info](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Studies-Extending-The-Time-Scale) - **Added Custom Symbol Status API.** The new [Custom Symbol Status API](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ICustomSymbolStatusApi) enables the creation and customisation of an additional status to be displayed for the symbol within the legend area. - The Custom Symbol Status API can be accessed via the [`customSymbolStatus`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#customsymbolstatus) method on the chart widget. - An example is provided on the [Symbol Status](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Status) page. - **Featureset added for clearing the price scale on errors.** Added new `clear_price_scale_on_error_or_empty_bars` featureset to automatically clear pane price scales when the main series has an error or has no bars. - **Adding Anchored VWAP in Trend line tools.** A new Trend line tool has been added to the already long list: Anchored VWAP. **Improvements** - **Added Watermark API.** The new [Watermark API](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatermarkApi) enables the customisation of the watermark text in addition to providing [WatchedValues](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatchedValue) for the color and visibility properties. - The Watermark API can be accessed via the [`watermark`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#watermark) method on the chart widget. - **Updated broker API sample to support bracket orders.** The sample broker API has been updated to support brackets (stop loss, and take profit) orders.
- **Drawings in saved charts now restore with the saved settings for lock and disableSelection.** The `lock` and `disableSelection` settings for a created shape will now be saved and restored correctly. [#6761](https) - **Fullscreen button can now be used to exit fullscreen mode as well.** When using the `header_in_fullscreen_mode` featureset, it is now possible to use the fullscreen button to exit fullscreen mode. - **Added method to programmatically set the time frame for the active chart.** The [setTimeFrame](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#settimeframe) method has been added to the widget which can set the time frame in a similar manner to the [Timeframes at the bottom of the chart](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scaletimeframes-at-the-bottom-of-the-chart) buttons. - **Renaming precision dropdown values in Chart settings.** To limit confusion when dealing with the Chart settings/Precision dropdown values, some fractional ones have been renamed to more readable ones. - **Changing Source option in line-break & renko chart.** In Trading Platform, it was unnecessary to offer the option to change the source of data for both Renko and Line Break, as the data is taken from the close value. **Bug Fixes** - **Timescale marks will adjust correctly when widget theme is changed.** - **onAutoSaveNeeded event emitted when removing all drawings via toolbar button.** - **removeChart within the save load adapter will await the promise before updating the UI.** - **First getBars request after resetting data no longer has a countback of zero.** - **Market status pop up text could sometimes display Infinity or NaN values and not update on the dot.** - **Fix custom field validators.** Fixes a bug where custom broker field validator functions were not called if provided. - **Fixed rendering on price and time axes when a Trend Angle line drawing is selected.** **Other** - **Changed validation warning message within the close position UI.** Message changed from 'Specified value is more than the instrument maximum' to 'The amount entered exceeds the position size'. - **Corrected the strings for the ThemeName type definition.** The possible values should have been lowercase: 'dark' & 'light'. - **Moved Session breaks from Events to Appearance tab in chart options.** This reverts a breaking change made in `v25.0`. - **Adding snippets for Trading Platform datafeed methods.** Some functions were lacking an out of the box snippet to use within their application. ## Version 25 *Date: Mon May 22 2023* **Breaking Changes** - **Save and Load Chart Templates.** Add methods to the [save/load adapter](https://www.tradingview.com/charting-library-docs/latest/saving_loading) to support chart templates. - **Renew design for send order and buy sell buttons.** Renew design for send order and buy sell buttons: - Buttons are now rounded - Selected item and underline are now black - **New TV logo.** What is changing: - Changing the size, boldness of the text - Indentation of the logo from the borders of the chart - **One row for grid lines settings.** The grid lines settings have been combined into one row. - **Remove magnet icon near cursor - Reverting feature.** Following reviews this piece of work was reverted. - **Update the library branding.** Branding font and position is slightly changed. - **Do not load Euclid font for the branding logo on chart.** The Euclid font will not load if there is an animated logo on the chart. - **When the chart data is reset, the new request for data will only be for the visible range.** The previous behavior was that when [resetData](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#resetdata) was evoked, that the datafeed would be requested to provide data for the entire range of data already loaded for that symbol. The new behavior is that the request is now only for the current visible range. This more closely matches the behavior of the first load. If you require the old behavior then you can disable the `request_only_visible_range_on_reset` featureset. - **Remove timezone & session breaks section from scale gear menu.** Time zone and Session breaks section has been removed from gear menu. - **Update chart types icons.** Changed icons for Line, Area and Baseline chart types. - **Move Session breaks from Appearance to Events tab.** Session breaks setting is moved to events tab. - **Changed the gear icon.** Changed the icon for price scale settings button ('gear' in bottom-right corner). - **Chart navigation buttons.** Navigation buttons at the bottom of the chart have a slightly new design. **New Features** - **Adding a new chart type HLC Area.** HLC Area is a new chart type available. - **Handle variable-tick-size.** Added support for variable tick size. - **Add new stats position for info line drawing "auto".** Option of automatic positioning of information block for infoline drawings was added "auto" (in addition to existing left, center, right). - **Add new checkboxes for price range in Info Line drawing box.** Added 2 settings in linetools context menu: - Percent change - Change in pips - **Add ability to move anchors continuously - not by bars.** Smooth resizing of icons, stickers and emojis was implemented. - **Correct Chart settings text Price scale labels.** "LABELS" group in "Scales" tab of Chart settings has been renamed to "LABELS ON PRICE SCALE". - **Show + button on cursor by hotkey.** Added hotkeys Alt+Ctrl (win) or Opt+Command (mac) for the appearance of the plus button under the cursor. - **Add Data window item to context/legend three dots menu.** Added new item to context/legend three dots menu - "Data window..." with a shortcut. Opens Data Window in the right panel. - **Add Volume profile indicators on the top of chart series.** Changed the default z-order for Volume Profile indicators and VP drawings. They are now located above the main series. - **Added new time zone Anchorage Alaska.** Added new time zone Anchorage Alaska (UTC-9). - **Separate chart types Line with markers and Stepline.** Step line and Line with markers types are added to the top toolbar chart types menu. - **Added new time zone Casablanca.** Timezone Casablanca (UTC) has been added. - **Try to load line tools code dynamically.** Fixed floating toolbar for Price Note to show color and text settings like for other drawings. - **Add sticker drawing tool.** Add the ability to use stickers with `createMultipointShape` or `selectLineTool`. - **Add Accelerator Oscillator indicator.** **Improvements** - **Theming support for pop-up menus.** Additional CSS custom properties have been added for styling pop-up menus. Pop-up (as known as 'pop-over') menus include toolbar menus, and context menus. See the full list of CSS custom properties in the [CSS Color Themes](https://www.tradingview.com/charting-library-docs/latest/customization/styles/CSS-Color-Themes) article. - **Add date and time input UI for custom studies.** [Custom studies](https://www.tradingview.com/charting-library-docs/latest/custom_studies) now support defining inputs of the `'time'` type and having a GUI element (date and time pickers) in the indicators settings dialog window. - **setActiveChart added to the Widget API.** The currently active chart in a multi-chart layout (available on Trading Platform only) can now be changed using the `setActiveChart` method. [more info](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#setactivechart) **Bug Fixes** - **Include missing PriceAxisLastValueMode and LineStyle enums in type documentation.** **Documentation** - **The Overrides article update.** We have updated the [Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides) article. Now it contains general information about the Overrides API. For information on how to customize elements on the chart, refer to a new [Chart Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides) article. ## Version 24.004 *Date: Mon Apr 24 2023* **New Features** - **Indicators can now be favorited.** Indicators can now be favorited by tapping on the star icon to the left of the indicator name. Favorited indicators will appear at the top of the indicator list. - The `items_favoriting` featureset should be enabled. [more info](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) - **Adding two featuresets to hide the right_toolbar or its tabs.** There are 2 new featuresets `hide_right_toolbar` & `hide_right_toolbar_tabs` plus an additional WidgetBar API [changeWidgetBarVisibility](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWidgetbarApi#changewidgetbarvisibility) to control the right toolbar. - `hide_right_toolbar` allows you to instantiate the toolbar without showing it in the UI. - `hide_right_toolbar_tabs` will do the same with the exception of not showing tabs when displaying the right toolbar. **Improvements** - **Added a middle band for the RSI indicator.** Unlike on tradingview.com RSI was not presenting the option to plot a middle limit. - **Indicators favorites can now be defined within widget constructor.** Indicators can now be defined as favorites using the [`favorites`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#favorites) property of the widget constructor options. See [Favorites.indicators](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Favorites#indicators) for more information. - **Add a way to independently clear bar marks/timescale marks.** [`clearMarks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#clearmarks) method has been enhanced to pass in an option to choose which marks should be cleared on the chart. - By default behaviour will remain similar and both bar & TimeScale marks will be removed. - Passing `ClearMarksMode.BarMarks` will only remove bar marks. - Passing `ClearMarksMode.TimeScaleMarks` will only remove TimeScale marks. - **`BREAKING CHANGE` Discrepancy in chart style/type methods.** Only TypeScript breaking change as an interface has been renamed to better reflect its purpose. `SeriesStyle` is now [SeriesType](https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.SeriesType). **Bug Fixes** - **load_study_template event is not emitted.** load_study_template event was not emitted when applying a template on the chart. - **Fixed autosize bug occurring on Chrome iOS when rotating the device.** Workaround fix for a browser bug until Chrome resolves the issue on their side. - **Fixed the type definitions for a few of the PineJS Std library functions.** [PineJSStd documentation](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PineJSStd). **Documentation** - **New Key Features article.** We have added the [Key Features](https://www.tradingview.com/charting-library-docs/latest/getting_started/Key-Features) article that lists features supported/unsupported in Advanced Charts and Trading Platform. - **How to connect data via Datafeed API.** We have added a new [tutorial on connecting data via Datafeed API](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial). It will help you implement datafeed and real-time data streaming to the library step-by-step. **Other** - **Incorrect watermark property key.** Deprecated `symbolWatermarkProperties` property has now been removed. Please use [settings_adapter](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#settings_adapter) with `symbolWatermark` key instead or `applyOverrides` to change values. ## Version 24.003 *Date: Tue Apr 11 2023* **New Features** - **Images within bar marks.** Bar marks now support the rendering of images as the background by specifying the `imageUrl` property. Please see the [Mark](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Mark) interface for more details. - **Price Source and Long Description symbol info fields.** Add support for displaying the price source and long description fields from the symbol info. - To enable the price source first add `symbol_info_price_source` to the list of enabled features. Then it will be shown in the legend, if available. It can be hidden through the legend context menu and the series property dialog. - To enable the long description first add `symbol_info_long_description` to the list of enabled features. Then it will be shown in the legend, if available. It can be hidden through the legend context menu and the series property dialog. **Improvements** - **Added more styling options for bar marks.** The styling options for bar marks has been expanded to include options for styling the border. - Border color can be set using the `border` property within `color` of the Mark interface. See [MarkCustomColor](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.MarkCustomColor) - Border width can be set using `borderWidth` and `hoveredBorderWidth`. See [Mark](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Mark) - **Drawing tools favorites can now be defined within widget constructor.** Drawing tools can now be defined as favorites using the [`favorites`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#favorites) property of the widget constructor options. See [Favorites.drawingTools](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Favorites#drawingtools) for more information. - **Context menu API can now be used within the Watchlist.** `watchlist_context_menu` featureset is enabled by default. See [onContextMenu](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#oncontextmenu) for more details. - **Improved typings within package.json.** The `package.json` bundled with the library has been improved to support newer versions of node, and offer improved typings. See [NPM](https://www.tradingview.com/charting-library-docs/latest/getting_started/NPM) for more details. - **Price scale now supports numbers with more than 10 decimal points.** - **Timezone data has been updated.** **Bug Fixes** - **Chart type won't change when restoring default options.** The chart type will no longer change when restoring the default options within the chart settings dialog. - **Last visible bar value in legend for overlay studies.** When `use_last_visible_bar_value_in_legend` featureset is enabled, overlay studies will display the value for the last visible item on the chart. This now matches the behavior for the main series. - **Fixed zoom behavior for percentage right margin option.** Incorrect zooming behavior has been fixed for zoom buttons appearing on the chart, and the keyboard shortcuts. See `show_percent_option_for_right_margin` [featureset](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) for more information. **Documentation** - **Add FAQ about unsubscribeBars delay.** Added [a new FAQ](https://www.tradingview.com/charting-library-docs/latest/getting_started/Frequently-Asked-Questions) about [`unsubscribeBars`](https://www.tradingview.com/charting-library-docs/latest/api/required-methods#unsubscribebars) being called with a delay. **Other** - **Added symbol information to datafeed error messages.** Added symbol information to realtime subscription error messages to improve the developer experience. - **Updated localisation list.** The [list of support localisations](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Localization) has been updated. Additionally, the chart will now fallback to english (with a console warning) if an unsupported locale is specified in the widget constructor options. ## Version 24.002 **New Features** - **Added support for specifying custom timezones.** - Additional custom timezones can now be specified for use within the library. Please see the [Adding Custom Timezones](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezonescustom-time-zones) section within the Timezones page. - **Images within timescale marks.** - Timescale marks now support the rendering of images within the circular shape by specifying the `imageUrl` property. Please see the [TimescaleMark](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TimescaleMark) interface for more details. - **Support different margin rates for different order types.** [6607](https) - `marginRate` has been deprecated - A [`supportLeverageButton`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Broker.BrokerConfigFlags#supportleveragebutton) flag that displays a leverage button has been added to the Broker configuration. - The [`supportLeverage`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Broker.BrokerConfigFlags#supportleverage) flag enables leverage calculation by getting information from `leverageInfo`. **Enhancements** - Add horizontal line at 0 for Momentum study. **Bug fixes** - [`setUserEditEnabled`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IStudyApi#setusereditenabled) does not hide 3 dots in Legend. [6765](https) | [6165](https) widget.activeChart().getAllStudies().forEach((\{ id }) => \{ console.log(id); tvWidget.activeChart().getStudyById(id).setUserEditEnabled(false); }); - setUserEditEnabled(false) should mask all icons except the "eye". - setUserEditEnabled(true) should restore all the icons. - `priceFormatter` could previously only be used for main series. `priceFormatter` now applies to secondary series as well. - `right_toolbar` featureset didn't have a default `on` value. - Empty time frames at the bottom toolbar if `data_status: endofday` - Export data doesn’t include projected data. - Projected data can be included by setting [`includeOffsetStudyValues`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ExportDataOptions#includeoffsetstudyvalues) to `true`. - `await widget.activeChart().exportData({ includeOffsetStudyValues: true });` - Highest PineJS.Std function doesn’t work correctly with negative numbers. - Missing types in bundled definition file. [7445](https) | [7446](https) - Exposing `icon` prop in `CreateShapeOptionsBase`. [6723](https) - Wrong extended session background color [7443](https) **Documentation** - Added [migration guide](https://www.tradingview.com/charting-library-docs/latest/trading_terminalhow-to-migrate-from-advanced-charts) from Advanced Charts to Trading Platform. - Added additional documentation for [Drawings](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings). - Missing overrides in documentation. [7457](https) - Updated documentation for [Marks](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Marks). - Align ChartMetaInfo & ChartData. **Other** - Removed `Australia/ACT` from the list of [timezones](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezones) within our documentation. Please use either the Sydney timezone or [specify your own custom timezone](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezonescustom-time-zones). ## Version 24.001 **New Features** - **Adding originalText as an additional field to UndoRedoState.** Event should mention the name of the action in plain English in addition to also being translated to the corresponding language. [UndoRedoState](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.UndoRedoState#originalundotext) - **Add the ability to change X-Axis margin % from Chart Properties.** A new [featureset](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) has been added `show_percent_option_for_right_margin` that adds additional percentage option to the right margin section of the chart settings dialog. - **Display rightmost visible value when in percent mode.** A new [featureset](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) has been added `use_last_visible_bar_value_in_legend` to show the most recent “global” bar value. When this feature is enabled the rightmost bar in the visible range is used instead. - **Ability to change on the fly the Currency and Unit label setting.** [currencyAndUnitVisibility API](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#currencyandunitvisibility) - **Add simple SSR support.** Allow the library to be imported within a NodeJS context. This improves support for frameworks such as Remix. - **Added [`clearUndoHistory`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#clearundohistory).** **Improvements** - **Name to be used instead of ticker.** Allow a human friendly name to be returned from [`symbol_search_complete`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#symbol_search_complete). **Bug Fixes** - **Incomplete indicators when using Heikin-Ashi.** Indicator line should draw to all the visible data points. - **Compare study doesn’t save and restore ticker name correctly.** The compare study should work for custom ticker names just like it does for ticker names which match our format (with the colon). - **VPFR: Right point is automatically moving when dragging start point.** When drawing the VPFR, or moving one of the anchor points, it is expected that the right anchor point should not move one bar further to the right. - **Selecting Apply Defaults option within chart settings doesn’t work.** Some Settings even if not validated are not restored to their original values when Apply Defaults is selected. - **Decentralised app browser loading error.** Chart fails to load in wallet apps like MetaMask, Trust & Phantom. Enable the `iframe_loading_compatibility_mode` [featureset](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) to enable compatibility with these browsers. - **When disabled, widget bar still present a significant margin.** Even when there aren't any pages or widget in the right toolbar and IF right_toolbar is disabled, contrary to the drawing toolbar that vanishes the widget bar stays there with the pill button to expand it whereas there isn't anything to expand. - **Can’t enable header_compare feature without header_symbol_search.** - Disabling header_symbol_search should only hide the search button - Disabling header_compare should only hide the compare button - **Removed section of PostCSS syntax in bundled css files.** **Other** - **New Documentation site.** 🎉 - **Add `shape` to TimeScale.** Shape property is described in [TimescaleMark interface](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TimescaleMark#shape). - **Remove magnet icon near cursor.** ## Version 24 - `preset` Widget-Constructor parameter has been removed. Users can still use some featuresets to mimic the same behavior by disabling the following list: - `'left_toolbar', 'header_widget', 'timeframes_toolbar', 'edit_buttons_in_legend', 'context_menus', 'control_bar', 'border_around_the_chart'` - `chart_style_hilo` featureset is now enabled by default. This adds the High-low option to chart style controls dropdown. This featureset has been available since 1.15 but was previously disabled by default. - Added typings for custom indicators. Typescript equivalents of our existing examples are available here: [Custom Studies Typescript Examples](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examples). - [`symbol_search_complete`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#symbol_search_complete) has changed. The function now takes an additional search result object parameter, and returns an additional human-friendly symbol name. - [Mark](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Marks) tooltips do not support HTML anymore. **UI changes** - With this version you will notice that the top toolbar has been redesigned with the following changes: - Button padding & separator size have been reduced - Compare button has shifted next to Symbol - Drawing icon is now more prominent - New fullscreen icon - Save button style better highlights when there's a change - Top toolbar now extends to left & right edges - UI font changes to a default system one - Undo/redo buttons are now relocated next to the save button **Trading Platform** - Default formatter `textNoWrap` has been removed. - `columnId` field of [SortingParameters](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Broker.SortingParameters) has been renamed to `property`. - Required `id` field has been added to [column description](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Broker.AccountManagerColumnBase#id). - Type of `formatter` field in [column description](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Broker.AccountManagerColumnBase#formatter) has been changed to [StandardFormatterName | FormatterName](https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.StandardFormatterName). - `property` field has been removed from `column description`. Use [dataFields](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Broker.AccountManagerColumnBase#datafields) field instead. - Type of `formatter` field in [SummaryField](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Broker.AccountManagerSummaryField) has been changed to [StandardFormatterName](https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.StandardFormatterName). ## Version 23 - `Average close price line` is now masked by default in Chart settings and can be shown by using `show_average_close_price_line_and_label` featureset. ## Version 22 - Methods getTimezone and setTimezone have been deprecated and will be removed in future versions. Use [getTimezoneApi](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#gettimezoneapi) instead. - POST request data format sent to [snapshot_url](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#snapshot_url) has been changed. Since this version this request contains `multipart/form-data` with the field `preparedImage` that represents binary data of the snapshot image in `image/png` format. - Optional `inputs` arguments for [createStudy](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createstudy) has been changed from using an array of ordered values to an object with named properties. You can still use array-like inputs but it will be removed in further releases. - The set of inputs for Moving Average study has been changed and the first input now is a symbol. If you used `createStudy` to create Moving Average study you will have to modify the list of inputs by simply adding an empty string as the first element: ```javascript tvWidget.activeChart().createStudy('Moving Average', true, false, ['', 9]); ``` instead of ```javascript tvWidget.activeChart().createStudy('Moving Average', true, false, [9]); ``` - Study `Ichimoku` has been modified with some `Inputs` & `Style` properties renamed. - Both `scrollPosition` and `defaultScrollPosition` from [Chart-Methods](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi) have been deprecated in favour of [rightOffset](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ITimeScaleApi#rightoffset) and [defaultRightOffset](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ITimeScaleApi#defaultrightoffset) accordingly. - The `rest.html` file and `datafeeds/rest` directory have been removed. - When [subscribed](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#subscribe) to `drawing_event` a `click` is no longer emitted when a drawing is created. A `create` event is emitted instead. - Study `True Strength Indicator` has been renamed to `True Strength Index` and modified with its style elements being properly named with 1st `Plot` becoming `True Strength Index` & second `Plot` becoming `Signal`. **Trading Platform** - The `watchList` method now returns a promise that resolves a watchlist API object when the watchlist widget has loaded. - `suggestedQty` has been removed from the `Trading Host`. - `dome_widget` featureset which controls the DOM widget visibility has be deprecated in favour of `dom_widget`. ## Version 21 - Featureset `show_dialog_on_snapshot_ready` has been removed. [takeScreenshot](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#takescreenshot) makes a snapshot silently, so you can use the URL from [onScreenshotReady](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#subscribe) callback to show your own dialog instead. - Field `holidays` from [SymbolInfo](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) has been renamed to [`session_holidays`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#session_holidays). - `changeTheme` from [Widget Methods](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget) now returns a Promise. You can apply other style modifications after the promise is fulfilled. - Symbol type `bitcoin` has been renamed to `crypto`. - The symbol search dialog suggestions list uses the `full_name` instead of the `exchange` and `symbol` value. This data is provided by your implementation of [searchSymbols](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#searchsymbols). **Trading Platform** - `supportModifyOrder` flag has been marked deprecated and will be removed in future versions. Use `supportModifyOrderPrice`, `supportEditAmount` and `supportModifyBrackets` instead. - `empty` formatter has been removed. - Flag `durationForMarketOrders` has been removed from Broker Configuration `configFlags` object. To use duration with market orders, add appropriate order type to `supportedOrderTypes` array. - `supportReducePosition` flag has been removed from the Broker Configuration `configFlags` object. - `supportExecutions` flag has been added. If broker supports executions you need to set the flag to `true`. - The default value of `asc` field of the [SortingParameters](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Broker.SortingParameters#asc) has been changed to `true`. - The `customFormatters` field has been removed from the [accountManagerInfo](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager). - `id`, `modificationProperty`, `fixedWidth`, `showOnMobile` and `showTooltipOnCell` fields have been removed from the [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager) `column description`. The `property` field has been made mandatory, so you can use it instead of `id`. - The string `id` field has been made mandatory in each `table` ([Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager)) row. - The return value of the method `placeOrder` in the [Broker API](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-conceptsbroker-api) has been changed from `Promise` to `Promise`. - `contextMenuEvent` type in `contextMenuActions` in `AccountManagerInfo` interface has been changed from `MouseEvent` to `MouseEvent | TouchEvent`. - The shape of the `news_provider` property in the [Widget Constructor options](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#news_provider) has changed. The `is_news_generic` and `get_news` properties have been replaced with a single function. URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/low-level-api =========================================================================================== # Low-level API for saving and loading ## Overview The low-level API is recommended when you want to use save/load UI elements that are not part of the TradingView UI. With the low-level API, you can save and load [chart layouts] and [indicator templates]. Note that the low-level API methods are meant to be called directly by your JavaScript code. :::info This approach does not support saving [chart templates]. Consider implementing the [API handlers] instead. ::: ## How to implement To access the chart layout content directly, use the [`save`] and [`load`] methods. These methods are defined in the [`IChartingLibraryWidget`] interface and allow controlling the `widget` object. ```js // Function to store the chart layout function storeChartLayout(layout) { // Implement your logic here }; const widget = new TradingView.widget(/* Widget properties */); widget.save((layout) => { storeChartLayout(layout) }); // Save the layout using the save() method widget.load(storedLayout); // Later in your code, you can load the stored layout ``` To access the indicator templates, use the [`createStudyTemplate`] and [`applyStudyTemplate`] methods. Note that you can access these methods through the [`chart`] or [`activeChart`] widget methods. ```js widget.onChartReady(() => { const options = { saveSymbol: true, saveInterval: true }; const template = widget.activeChart().createStudyTemplate(options); widget.activeChart().applyStudyTemplate(template); }); ``` The content is saved as a JSON object which you can save where you wish. For example, you can embed it in your saved pages or in the user's working area. ## Hide save/load layout buttons You can disable the [`header_saveload`] featureset to hide the built-in *Save layout* and *Load layout* buttons from the header toolbar. [`activeChart`]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methods#activechart [API handlers]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapter [`applyStudyTemplate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#applystudytemplate [`chart`]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methods#chart [chart layouts]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#chart-layouts [chart templates]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#chart-templates [`createStudyTemplate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createstudytemplate [`header_saveload`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#header_saveload [`IChartingLibraryWidget`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget [indicator templates]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#indicator-templates [`load`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#load [`save`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#save URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapter =============================================================================================== # API handlers for saving and loading ## Overview You can use the API handlers instead of the [predefined REST API] to store: - [chart layouts] - [chart templates] - [indicator templates] - [drawing templates] When users click the save or load buttons in the UI, these actions initiate the saving and loading processes. API handlers allow implementing custom logic for save/load actions coming from UI. For example, you can add authorization headers or manage specific errors. Note that you need to have your own backend service to use API handlers. ## How to implement Add the [`save_load_adapter`] property to the [Widget Constructor]. `save_load_adapter` is an [`​IExternalSaveLoadAdapter`] object that contains the save/load functions. The library calls these functions when users click save/load UI elements. ## Examples ### localStorage The TypeScript example below shows how to implement in-memory saving logic, so that the data is saved within the browser's [localStorage]. ### In-memory The JavaScript example below shows how to implement in-memory saving logic, so that the data is saved only within the memory of the current tab. You can use this example for testing purposes or improve it by replacing the internals of these methods with calls to an external server. [chart layouts]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#chart-layouts [chart templates]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#chart-templates [drawing templates]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#drawing-templates [`​IExternalSaveLoadAdapter`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IExternalSaveLoadAdapter [indicator templates]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#indicator-templates [localStorage]: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage [predefined REST API]: https://www.tradingview.com/charting-library-docs/latest/api/save-load-rest-api [`save_load_adapter`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#save_load_adapter [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapter =============================================================================================== [ { "anchorName": "status", "cells": [ "status", "ok or error" ] }, { "anchorName": "data", "cells": [ "data", "Data object with the following properties:
  • timestamp — UNIX time when the chart was saved (example: 1449084321)
  • symbol — base symbol of the chart (example: AA)
  • resolution — chart resolution (example: 1D)
  • id — unique integer identifier of the chart (example: 9163)
  • name — chart name (example: Test)
" ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapter =============================================================================================== [ { "anchorName": "status", "cells": [ "status", "ok or error" ] }, { "anchorName": "data", "cells": [ "data", "Data object with the following properties:
  • content — saved content of the chart
  • timestamp — UNIX time when the chart was saved (example: 1449084321)
  • id — unique integer identifier of the chart (example: 9163)
  • name — chart name
" ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapter =============================================================================================== [ { "anchorName": "status", "cells": [ "status", "ok or error" ] }, { "anchorName": "data", "cells": [ "data", "Data object with the following properties:
  • name — template name
  • content — saved content of the template
" ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-rest-api/chart-layout-methods ===================================================================================================================== # Chart layout methods ## List charts GET request: `charts_storage_url/charts_storage_api_version/charts?client=client_id&user=user_id` ### Response content The response is a JSON object containing the following properties: import AnchoredTable from '@site/src/components/anchored-table'; import listChartsProperties from './_saving_loading_tables/list-charts-properties.json'; --- ## Save chart POST request: `charts_storage_url/charts_storage_api_version/charts?client=client_id&user=user_id` ### Request body | Parameter | Description | |-|-| | `name` | Chart name | | `content` | Chart content | | `symbol` | Chart symbol (example: `AA`) | | `resolution` | Chart resolution (example: `1D`) | ### Response content The response is a JSON object containing the following properties: | Parameter | Description | |-|-| | `status` | `ok` or `error` | | `id` | Unique string identifier of the chart (example: `9163`) | --- ## Save as chart POST request: `charts_storage_url/charts_storage_api_version/charts?client=client_id&user=user_id&chart=chart_id` ### Request body | Parameter | Description | |-|-| | `name` | Chart name | | `content` | Chart content | | `symbol` | Chart symbol (example: `AA`) | | `resolution` | Chart resolution (example: `1D`) | ### Response content The response is a JSON object containing the `status` property, which may have values of either `ok` or `error`. --- ## Load chart GET request: `charts_storage_url/charts_storage_api_version/charts?client=client_id&user=user_id&chart=chart_id` ### Response content The response is a JSON object containing the following properties: import loadChartProperties from './_saving_loading_tables/load-chart-properties.json'; --- ## Delete chart DELETE request: `charts_storage_url/charts_storage_api_version/charts?client=client_id&user=user_id&chart=chart_id` ### Response content The response is a JSON object containing the `status` property, which may have values of either `ok` or `error`. URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-rest-api/drawing-methods ================================================================================================================ # Drawing methods :::info These endpoints are only required when the [`saveload_separate_drawings_storage`] featureset is enabled. This allows [saving drawings separately] from the chart layout. ::: ## Save drawings POST request: `charts_storage_url/charts_storage_api_version/drawings?client=client_id&user=user_id&chart=chart_id&layout=layout_id` ### Request body The request body contains a JSON with the `state` property, which holds a [`LineToolsAndGroupsState`] object. ### Response content The response is a JSON object containing the `status` property, which may have values of either `ok` or `error`. --- ## Load drawings GET request: `charts_storage_url/charts_storage_api_version/drawings?client=client_id&user=user_id&chart=chart_id&layout=layout_id&symbol=symbol` ### Response content The response is a JSON object containing the following properties: | Parameter | Description | |-|-| | `status` | `ok` or `error` | | `data` | An object containing the `state` property, which holds a [`LineToolsAndGroupsState`] object | [`LineToolsAndGroupsState`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LineToolsAndGroupsState [`saveload_separate_drawings_storage`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#saveload_separate_drawings_storage [saving drawings separately]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/saving_drawings_separately URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-rest-api/drawing-template-methods ========================================================================================================================= # Drawing template methods :::info These endpoints are only available in [Trading Platform]. ::: ## List drawing templates GET request: `charts_storage_url/charts_storage_api_version/drawing_templates?client=client_id&user=user_id&tool=toolName`, where `toolName` is a name of a drawing. ### Response content The response is a JSON object containing the following properties: | Parameter | Description | |-|-| | `status` | `ok` or `error` | | `data` | An array containing items with the `name` property. This property represents template names (example: `Test`) | --- ## Save drawing template POST request: `charts_storage_url/charts_storage_api_version/drawing_templates?client=client_id&user=user_id&tool=toolName&name=templateName`, where: - `toolName` is a drawing name - `templateName` is a custom template name ### Request body The request body contains a JSON object with the `content` property. This property represents the saved content of a template. ### Response content The response is a JSON object containing the `status` property, which may have values of either `ok` or `error`. --- ## Load drawing template GET request: `charts_storage_url/charts_storage_api_version/drawing_templates?client=client_id&user=user_id&chart=chart_id&tool=toolName&name=templateName`, where: - `toolName` is a name of a drawing - `templateName` is a name of a template to get ### Response content The response is a JSON object containing the following properties: | Parameter | Description | |-|-| | `status` | `ok` or `error` | | `data` | Data object containing the `content` property. This property represents saved content of the template. | --- ## Delete drawing template DELETE request: `charts_storage_url/charts_storage_api_version/drawing_templates?client=client_id&user=user_id&chart=chart_id&tool=toolName&name=templateName`, where: - `toolName` is a name of a drawing - `templateName` is a name of a template to remove ### Response content The response is a JSON object containing the `status` property, which may have values of either `ok` or `error`. [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-rest-api/indicator-template-methods =========================================================================================================================== # Indicator template methods ## List indicator templates GET request: `charts_storage_url/charts_storage_api_version/study_templates?client=client_id&user=user_id` ### Response content The response is a JSON object containing the following properties: | Parameter | Description | |-|-| | `status` | `ok` or `error` | | `data` | Array of objects where each object has a `name` property representing the template name (example: `Test`) | --- ## Save indicator template POST request: `charts_storage_url/charts_storage_api_version/study_templates?client=client_id&user=user_id` ### Request body | Parameter | Description | |-|-| | `name` | Template name | | `content` | Template content | ### Response content The response is a JSON object containing the `status` property, which may have values of either `ok` or `error`. --- ## Load indicator template GET request: `charts_storage_url/charts_storage_api_version/study_templates?client=client_id&user=user_id&chart=chart_id&template=name`, where `name` is a template name. ### Response content The response is a JSON object containing the following properties: import AnchoredTable from '@site/src/components/anchored-table'; import loadIndicatorTemplateProperties from './_saving_loading_tables/load-indicator-template-properties.json'; --- ## Delete indicator templates DELETE request: `charts_storage_url/charts_storage_api_version/study_templates?client=client_id&user=user_id&template=name`, where `name` is a template name. ### Response content The response is a JSON object containing the `status` property, which may have values of either `ok` or `error`. URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-rest-api ================================================================================================ # Save and load REST API import AnchoredTable from '@site/src/components/anchored-table'; ## Overview The library provides a predefined REST API to save [chart layouts] and [indicator templates] on your server. When users click the save or load buttons in the UI, these actions initiate the saving and loading processes. This article describes the [request formats](#develop-your-own-storage) sent by the library. Additionally, you can find a server-side [storage example](#storage-example), which can serve as a starting point for implementation. :::info This approach does not support saving [chart templates]. Consider implementing the [API handlers] instead. Besides, using API handlers is recommended for greater flexibility and control over operations such as adding authorization headers or managing errors. ::: ## Use demo storage You can use a demo chart storage for saving and loading charts and indicator templates as soon as you build your application. To use this storage, specify [`charts_storage_url`] in the [Widget Constructor] as shown below: ```javascript const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-next-line charts_storage_url: "https://saveload.tradingview.com", }) ``` Note that the demo storage is provided "as is", and its stability is not guaranteed. The data within the storage is regularly deleted. Therefore, we recommend using this storage for testing purposes only. ## Storage example Refer to our [GitHub repository] for a storage example implemented with Python and PostgreSQL. You can use this storage and run it on your server to process your users' saved data. Note that this storage does not support the endpoints that allow [saving and loading drawings separately]. Follow the steps below to get started: 1. Clone the repository to your host machine. 2. Run the data service or use our demo service.
If you are not familiar with Django, follow the steps below. 1. Install Python 3.x and pip. 2. Install PostgreSQL or any other Django-friendly database engine. 3. Navigate to your chart storage folder and install the required dependencies: ```bash cd your-repository pip install -r requirements.txt ``` 4. Configure your database connection in `charting_library_charts/settings.py` (see `DATABASES` at [line 16]). Do not forget to create the appropriate database in your PostgreSQL instance. 5. Run migrations to create the database schema without any data: ```bash python manage.py migrate ``` 6. Start a test instance of your database: ```bash python manage.py runserver ``` **Note:** for production environments, avoid using `runserver` and instead use a suitable WSGI (Web Server Gateway Interface) server like Gunicorn.
3. Set [`charts_storage_url`] in the [Widget Constructor] to the URL of your chart storage. Additionally, ensure to set [`client_id` and `user_id`](#manage-access-to-saved-charts). ```javascript const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-start charts_storage_url: "https://example.com", client_id: "tradingview.com", user_id: "public_user_id", // highlight-end }) ``` :::info - Manual database filling/editing is not recommended as it may disrupt the Django infrastructure. - This example does not support authorization. We do not recommend it for production use without implementing proper security measures. ::: ## Develop your own storage If you want to develop your own storage that accepts predefined REST API requests, implement the endpoints described in this section. Note that your implementation should process 4 requests: save, load, delete, and list. The library sends HTTP/HTTPS commands to the following endpoints: - [For chart layouts](https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-rest-api/chart-layout-methods): `charts_storage_url/charts_storage_api_version/charts?client=client_id&user=user_id` - [For indicator templates](https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-rest-api/indicator-template-methods): `charts_storage_url/charts_storage_api_version/study_templates?client=client_id&user=user_id` - [For drawings](https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-rest-api/drawing-methods): `charts_storage_url/charts_storage_api_version/drawings?client=client_id&user=user_id` - [For drawing templates](https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-rest-api/drawing-template-methods): `charts_storage_url/charts_storage_api_version/drawing_templates?client=client_id&user=user_id` These endpoints include arguments that correspond to the properties defined within the [Widget Constructor]. import saveLoadRest from '../../core_concepts/_widget_constructor_tables/saving-loading-chart-rest.json'; ## Manage access to saved charts You should manage how the charts are accessible to users. Each user can view and load charts associated with their [`client_id`] and [`user_id`]. - `client_id` represents a user group, typically set as your site's URL `client_id = your-site-URL`. Use this property for scenarios where you manage multiple user groups or when several sites share the same chart storage. - `user_id` uniquely identifies each user within a `client_id` group. You can configure it: - for individual users providing private storage for each user - for all users or user groups allowing public access to the storage Here are a few examples: | `client_id` | `user_id` | Effect | |-|-|-| | Your site URL or other link | Unique user ID |Each user has a private chart storage that other users cannot see. | | Your site URL or other link | Same value for all users | Each user can see and load any saved chart. | | Your site URL or other link | Unique user ID for registered users, along with a separate setting for anonymous users | Each registered user has a private chart storage, not visible to other users. All anonymous users share a single storage. | [API handlers]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapter [`charts_storage_url`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#charts_storage_url [chart templates]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#chart-templates [`client_id`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#client_id [GitHub repository]: https://github.com/tradingview/saveload_backend [line 16]: https://github.com/tradingview/saveload_backend/blob/master/charting_library_charts/settings.py#L16 [saving and loading drawings separately]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/saving_drawings_separately [`user_id`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#user_id [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor [chart layouts]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#chart-layouts [indicator templates]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#indicator-templates URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/saving_drawings_separately ======================================================================================================== # Saving drawings separately The library API offers an alternative approach for saving charts where the drawings can be stored separately from the chart layout. This behaviour is activated by the [`saveload_separate_drawings_storage`] featureset found in the library settings. ## Key advantages Storing drawings independently boasts several benefits: - **Per-symbol Drawings**: Drawings can now be associated with individual symbols, enabling reuse and flexibility across different layouts or charts. - **Efficient Data Size Management**: Separating drawings and chart layout properties potentially reduces the size of saved objects, optimizing load times and data storage on your server. ## Save load adapter When you enable the [`saveload_separate_drawings_storage`] featureset, two extra methods `saveLineToolsAndGroups` and `loadLineToolsAndGroups` are expected in your implementation of the [`IExternalSaveLoadAdapter`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IExternalSaveLoadAdapter) interface. Consider the following example which implements the new methods: ```js class SaveLoadAdapterWithDrawings extends SaveLoadAdapter { constructor() { super(); this.drawings = {}; } async saveLineToolsAndGroups(layoutId, chartId, state) { const drawings = state.sources; if (!this.drawings[this._getDrawingKey(layoutId, chartId)]) { this.drawings[this._getDrawingKey(layoutId, chartId)] = {} } for (let [key, state] of drawings) { if (state === null) { delete this.drawings[this._getDrawingKey(layoutId, chartId)][key]; } else { this.drawings[this._getDrawingKey(layoutId, chartId)][key] = state; } } } async loadLineToolsAndGroups(layoutId, chartId) { const rawSources = this.drawings[this._getDrawingKey(layoutId, chartId)]; if (!rawSources) return null; const sources = new Map(); for (let [key, state] of Object.entries(rawSources)) { sources.set(key, state); } return { sources }; } _getDrawingKey(layoutId, chartId) { return `${layoutId}/${chartId}` } } ``` ### Saving drawings per symbol If you want to save the drawings independently of the chart layout, you can use the following TypeScript example, which extends the [localStorage example](https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapterlocalstorage). ```typescript const drawingSourceStorageKey = 'LocalStorageSaveLoadAdapter_drawingSourceSymbol'; export class LocalStorageDrawingsPerSymbolSaveLoadAdapter extends LocalStorageSaveLoadAdapter { private _drawingSourceSymbols: Record = {}; public constructor() { super(); this._drawingSourceSymbols = this._getFromLocalStorage>(drawingSourceStorageKey) ?? {}; } protected override _saveAllToLocalStorage(): void { super._saveAllToLocalStorage(); this._saveToLocalStorage(drawingSourceStorageKey, this._drawingSourceSymbols); } public override async saveLineToolsAndGroups(layoutId: string, chartId: string | number, state: LineToolsAndGroupsState): Promise { const drawings = state.sources; if (!drawings) return; for (let [key, state] of drawings) { const symbolCheckKey = `${layoutId}/${chartId}/${key}`; const symbol = state?.symbol ?? this._drawingSourceSymbols[symbolCheckKey]; if (!this._drawings[symbol]) this._drawings[symbol] = {}; if (state === null) { delete this._drawings[symbol][key]; delete this._drawingSourceSymbols[symbolCheckKey]; } else { this._drawings[symbol][key] = state; this._drawingSourceSymbols[symbolCheckKey] = symbol; } } } public override async loadLineToolsAndGroups( _layoutId: string | undefined, _chartId: string | number, _requestType: LineToolsAndGroupsLoadRequestType, requestContext: LineToolsAndGroupsLoadRequestContext ): Promise | null> { // We only care about the symbol of the chart const symbol = requestContext.symbol; if (!symbol) return null; const rawSources = this._drawings[symbol]; const sources = new Map(); for (let [key, state] of Object.entries(rawSources)) { sources.set(key, state); } return { sources }; } } ``` ### saveLineToolsAndGroups This method lets you capture and store the current drawings state from your chart. It accepts three parameters: - `layoutId`: Denotes the specific chart layout - `chartId`: Identifies a particular chart within the layout - `state`: An instance of a `LineToolsAndGroupsState` object encapsulating the present state of the drawings ### loadLineToolsAndGroups Enables the loading of saved drawings back to the chart. It takes these parameters: - `layoutId`: Represents the current chart layout - `chartId`: Specifies a distinct chart within the layout - `requestType`: Defines the type of load request ('mainSeriesLineTools', 'lineToolsWithoutSymbol', 'allLineTools', or 'studyLineTools') - `requestContext`: Captures contextual details for the request. It can contain specific data useful for certain custom behaviors but isn't always needed for creating the response ## REST API If you use the [REST API](https://www.tradingview.com/charting-library-docs/latest/api/save-load-rest-api) for chart storage, you should implement the following endpoints in addition to the endpoints mentioned in the [Develop your own storage](https://www.tradingview.com/charting-library-docs/latest/api/save-load-rest-api#develop-your-own-storage) section. ### Save drawings `POST` request: `charts_storage_url/charts_storage_api_version/drawings?client=client_id&user=user_id&chart=chart_id&layout=layout_id` 1. `state`: `LineToolsAndGroupsState` object RESPONSE: JSON Object 1. `status`: `ok` or `error` ### Load drawings `GET` request: `charts_storage_url/charts_storage_api_version/drawings?client=client_id&user=user_id&chart=chart_id&layout=layout_id` RESPONSE: JSON Object 1. `status`: `ok` or `error` 2. `data`: Object 1. `state`: `LineToolsAndGroupsState` object ## Low-level API methods The [low-level API] has additional methods on the chart widget when you enable the [`saveload_separate_drawings_storage`] featureset. ### getLineToolsState This function captures the current drawings state from the chart. You can benefit from this if you need to programmatically capture and store the drawings state. ```js const state = widget.activeChart().getLineToolsState(); // Send or save state as required... ``` ### applyLineToolsState Enable restoring the drawings on the chart by implementing a previously saved `LineToolsAndGroupsState` object. ```js const state = // previously saved state widget.activeChart().applyLineToolsState(state).then(() => { console.log('Drawings state restored!'); }); ``` ### reloadLineToolsFromServer Triggers a re-request of drawings from the server (via the Save Load Adapter or REST API depending on your implementation). ```js widget.activeChart().reloadLineToolsFromServer(); ``` ## Customizing the chart save method The `save` method on the [`IChartingLibraryWidget`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget) interface now includes options to adjust its behavior. There is an `includeDrawings` option in `SaveChartOptions` which determines whether to include drawings in the chart layout object returned by the `save` method. This can be useful in conjunction with the [low-level API methods](#low-level-api-methods) described above. ```js widget.save(state => { // Handle saved state... }, { includeDrawings: false }); ``` ## Understanding the LineToolsAndGroupsState interface The [`LineToolsAndGroupsState`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LineToolsAndGroupsState) interface plays a crucial role in maintaining the state of chart drawings, providing a structure for both individual drawings and drawing groups. The `sources` property is a `Map`, which constructs key-value pairs to represent a distinct drawing. The key, in this case, is an identifier or UUID for a drawing, and the value accompanies a state object exclusive to that drawing. The state object also encapsulates the symbol associated with the drawings, adding another defining layer to the data representation. Similarly, the `groups` property is a `Map` accounting for groups of drawings. Each key-value pair comprises an identifier key or UUID and an array of UUIDs forming the drawing group. For both `sources` and `groups`, a UUID associated with a `null` value indicates that the respective drawing or drawing group is to be removed. This signifies when a previously existing drawing has been deleted by the user and is no longer present on the chart. :::caution It's important to note that the state objects (`LineToolState` and `LineToolsGroupState`) which represent the drawings' state should be treated essentially as black boxes. They are managed by the library and are not expected to be directly modified outside of it. ::: ## Migration The process of migrating chart layouts saved with the [`saveload_separate_drawings_storage`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetssaveload_separate_drawings_storage) featureset, after the feature is enabled, can be undertaken following certain steps. The library will still support loading chart layouts with drawings even when the [`saveload_separate_drawings_storage`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetssaveload_separate_drawings_storage) featureset is enabled. This allows you to load layouts saved using the pre-existing combined approach (when the drawings are saved in the chart layout) and then save them with the new separated approach (when this featureset is enabled). Along with the saved data, it is recommended that you store a flag that signifies in which mode the layout was saved. Such that when you load the layout you know whether you need to migrate the data or not. Handling the saving and loading of this optional flag falls outside the API's scope and remains a detail to be implemented within your code. To migrate a layout, listen for the [`chart_load_requested`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap#chart_load_requested) event to occur and then evoke the [`saveChartToServer`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#savecharttoserver) method on the widget to trigger the layout to be saved again. If you use the [low-level API methods](#low-level-api-methods), saving the chart layout would require storing the following two pieces of data. ```js widget.save( (chartLayoutState) => { const drawings = widget.activeChart().getLineToolsState(); // Send or save state as required... // save drawings // save chartLayoutState }, { includeDrawings: false } ); ``` [low-level API]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/low-level-api [`saveload_separate_drawings_storage`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#saveload_separate_drawings_storage URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading ============================================================================= # Saving and loading charts ## Overview The library allows users to save their [chart layouts](#chart-layouts), [chart templates](#chart-templates), [drawing templates](#drawing-templates), [indicator templates](#indicator-templates), and restore them when users get back. ### Chart layouts A **chart layout** is a single chart in Advanced Charts or a group of charts in [Trading Platform]. The chart layout includes [drawings][drawing], [indicators], and various chart settings, such as colors and styles. Note that the visible time range is not included in the chart layout. The library is designed to always display the most recent data to users. Users can save and load the layouts using the built-in *Save layout* and *Load layout* buttons on the header toolbar. import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Saving chart layout Loading previously stored chart layout To hide these buttons, include the [`header_saveload`] featureset in the [`disabled_features`] array. ### Chart templates :::info Available in [Trading Platform] only. ::: A **chart template** is a set of colors used for the main series. For example, this can include candle up/down colors, wick colors, line colors, background colors, and more. To enable saving chart templates, include the [`chart_template_storage`] featureset in the [`enabled_features`] array. Users can save and apply the chart templates in the *Chart settings → Template* drop-down menu. Chart settings menu ### Indicator templates An **indicator template** is a set of applied [indicators] and their settings, such as inputs and styles. :::info By design, all settings are saved except for **precision**. For most indicators, the optimal precision depends on the symbol's precision and is inherited from it. Therefore, it does not make sense to save a setting that may not be relevant, depending on the symbol it is used on. ::: Users can save and apply the indicator templates through the *Indicator Templates* button on the top toolbar. To display this button in the UI, include the [`study_templates`] featureset in the [`enabled_features`] array. Indicator templates ### Drawing templates :::info Available in [Trading Platform] only. ::: A **drawing template** is a set of properties of a particular [drawing]. This can include the drawing's line style, text alignment, and more. Users can save and apply the drawing templates through the *Templates* button on the floating drawing toolbar. Drawing templates To disable this feature, include the [`drawing_templates`] featureset in the [`disabled_features`] array. ### Implementation To store users' content, you should implement a storage. If you want users to have only one chart layout, you can consider using [`localStorage`]. However, due to the `localStorage` size limits, we recommend storing content on a server. To simplify the storage development, the library provides three approaches. The table below describes these approaches and what they allow you to store. | Approach | Description | Chart layout | Chart template | Drawing template | Indicator template | |-|-|:-:|:-:|:-:|:-:| | [REST API] | The predefined REST API is a set of methods that you need to implement. When users click the save or load buttons in the UI, these actions initiate the saving and loading processes. | ✔️ | ❌ | ✔️ | ✔️ | | [API Handlers] | The API handlers allow implementing custom logic for save/load actions coming from UI. For example, when users click the save or load buttons, you can add authorization headers or manage specific errors within these processes. | ✔️ | ✔️ | ✔️ | ✔️ | | [Low-level API] | The low-level API is recommended when you want to use save/load UI elements that are not part of the TradingView UI. The low-level API methods are meant to be called directly by your JavaScript code, giving you flexibility to implement custom save and load functionality. | ✔️ | ❌ | ❌ | ✔️ | ## Save drawings separately By default, drawings are saved within the [chart layout](#chart-layouts) through the built-in *Save layout* button. However, the library provides an alternative method for saving charts in which drawings are stored separately from the chart layout. This method is beneficial for optimizing load times and data storage on your server. Additionally, it allows associating drawings with individual symbols. This enables drawing reuse and flexibility across different layouts or charts. Refer to the [Saving drawings separately] article for more information. ## User settings User settings are settings that remain regardless of the applied [chart layout](#chart-layouts). They are stored separately from chart layouts to ensure that users have control over their specific preferences. Refer to [Save user settings] for more information. ## Additional use cases ### Save charts automatically You might want to automatically save chart layouts. Here are the steps to implement it: 1. Set a [threshold delay] in seconds that is used to reduce the number of the [`onAutoSaveNeeded`] calls. 2. [Subscribe] to the `onAutoSaveNeeded` event. 3. Call the [`saveChartToServer`] method. ### Restore last saved chart Usually, users open an empty chart and load their chart layouts using the *Load layout* dialog. However, if you want to open the last saved chart layout on start, you can do the following: - If you use the [low-level API], set the chart layout content to the [`saved_data`] field in the [Widget Constructor]. - Otherwise, set the [`load_last_chart`] property to `true`. [API handlers]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapter [`chart_template_storage`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#chart_template_storage [`disabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features [drawing]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings [`drawing_templates`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#drawing_templates [`enabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#enabled_features [`header_saveload`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#header_saveload [indicators]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators [`load_last_chart`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#load_last_chart [`localStorage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage [low-level API]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/low-level-api [`onAutoSaveNeeded`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap#onautosaveneeded [REST API]: https://www.tradingview.com/charting-library-docs/latest/api/save-load-rest-api [`saveChartToServer`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#savecharttoserver [`saved_data`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#saved_data [Save user settings]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings [Saving drawings separately]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/saving_drawings_separately [`study_templates`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#study_templates [Subscribe]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#subscribe [threshold delay]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#auto_save_delay [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings =========================================================================================== # Save user settings ## Overview User settings are settings that remain regardless of the applied [chart layout]. They are stored separately from chart layouts to ensure that users have control over their specific preferences. For example, the *Instant orders placement* setting in [Trading Platform] allows users to place orders without confirmation. This setting is a part of user settings and is not saved when users save the chart layouts. Saving this setting within a chart layout could lead to unexpected user experiences and is considered a bad practice. ### Settings list User settings include: - [Resolution] - Order type and quantity in the [Order Ticket] - *Chart settings → Trading* - *Buy/Sell buttons* - *Instant orders placement* - *Play sound for executions* - *Notifications* - *Summary row* in the [Account Manager] - Right and bottom widget bars view - Chart style - [Watchlist] ### How to store There are two options for storing user settings: - Using the browser's [`localStorage`], which is enabled by default. To disable this option, include the [`use_localstorage_for_settings`] featureset in the [`disabled_features`] array. - Implementing your preferred storage method, including the server-side one. For this, use the [`settings_adapter`](#settings-adapter) property of the [Widget Constructor]. ## Settings adapter You can save user settings using the [`settings_adapter`] property of the [Widget Constructor]. This property allows not only storing settings in the preferred storage but also applying them to the chart. :::info The library provides multiple approaches to modify the chart's appearance and behavior, and `settings_adapter` is one of them. These approaches have a specific application order, meaning they may override any styles or settings applied by other approaches lower on the list. Refer to [Customization precedence] for more information. ::: The `settings_adapter` property accepts the [`ISettingsAdapter`] object. In the [`initialSettings`] property of `ISettingsAdapter`, specify the settings the chart should be initiated with. You should also implement two methods [`setValue`] and [`removeValue`], which are triggered upon changes in settings. Consider the code sample below that does the following: - Sets a watermark on the chart when the chart is initialized. - Sets settings (10 units of shares and the *limit* order type) for the Order Ticket when the chart is initialized. - Logs actions in the console when settings are set or removed. ```js new TradingView.widget({ /* Other properties */ settings_adapter: { initialSettings: { "symbolWatermark": '{ "visibility": "true", "color": "rgba(244, 67, 54, 0.25)" }', "trading.Broker": '{"qty": {"AAPL": 10, "NasdaqNM:AAPL": 10}, "orderType": {"NasdaqNM:AAPL": 3}}', }, setValue: function (key, value) { console.log(`set value: ${key} ${value}`); }, removeValue: function (key) { console.log(`remove value: ${key}`); }, } }) ``` [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [chart layout]: https://www.tradingview.com/charting-library-docs/latest/saving_loading#chart-layouts [Customization precedence]: https://www.tradingview.com/charting-library-docs/latest/customization/customization-precedence [`disabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features [`initialSettings`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISettingsAdapter#initialsettings [`ISettingsAdapter`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISettingsAdapter [`localStorage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage [Order Ticket]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket [`removeValue`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISettingsAdapter#removevalue [Resolution]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution [`settings_adapter`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#settings_adapter [`setValue`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISettingsAdapter#setvalue [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [`use_localstorage_for_settings`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#use_localstorage_for_settings [Watchlist]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Trading-Primitives ================================================================================================== # Trading primitives ## Overview **Trading primitives** is a low-level mechanism that allows you to draw order, position, and execution lines directly on the chart. This approach is fundamentally different from the standard [Broker API] integration. While the Broker API requires implementing a backend trading server to display real trading data, trading primitives act as specialized drawing tools. This allows creating visual elements without needing a full trading logic implementation. :::caution Starting from version 29, the methods for creating trading primitives are only available in [Trading Platform]. ::: ## Create trading primitive You can create primitives using the following methods of the chart's API object ([`IChartWidgetApi`]). - [`createOrderLine`] - [`createPositionLine`] - [`createExecutionShape`] After the primitive is created, you can customize and interact with it using the API adapter. For example, the code sample below adds a new order line on the chart using the `createOrderLine` method. ```javascript const orderLine = await widget.activeChart().createOrderLine() orderLine .setTooltip("Additional order information") .setModifyTooltip("Modify order") .setCancelTooltip("Cancel order") .setText("STOP: 73.5 (5,64%)") .setQuantity("2"); ``` You can also attach callback functions to handle actions like modifying, canceling/closing, or moving/reversing lines. Inside a callback function, the `this` keyword refers to the API adapter of the primitive itself (e.g., `IOrderLineAdapter`). This allows you to call methods directly on the object in response to an event. ```javascript const orderLine = await widget.activeChart().createOrderLine(); orderLine .setQuantity("5") .setPrice(160) // Enables the "Cancel" button .onCancel(function() { console.log('Order cancelled. Removing line.'); // Removes the line from the chart this.remove(); }); ``` The callback registration methods (like [`onModify`], [`onCancel`]) are overloaded. You can pass a single callback function, or you can pass a data object as the first argument and the callback as the second. This data object will then be passed to your callback. ```javascript // These are the static details of the order that your backend needs to identify it const orderDetails = { avgPrice: 150, qty: 120, }; // Create the order line on the chart const orderLine = await widget.activeChart().createOrderLine(); orderLine .setQuantity("100") .setPrice(160) .setText("LIMIT BUY 100 @ 160.00") .onModify(orderDetails, function(data) { // 'this' refers to the orderLine object itself // 'data' is the orderDetails object we passed in // Set new price and quantity this.setPrice(data.avgPrice); this.setQuantity(data.qty); // Update the UI to give feedback to the user this.setText(`LIMIT BUY ${data.qty} @ ${data.avgPrice}`); }); ``` Note that the buttons on an order or position line (e.g., *Modify*, *Cancel*, *Close*, *Reverse*) are displayed dynamically. If you do not provide a callback for a specific action, its button is hidden from the UI. ## Customize appearance You can set the default styles for order and position lines by using the [`trading_customization`] property in the [Widget Constructor]. For more information, refer to [Customize trading primitives](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/trading-overridescreated-with-trading-primitives). ### Styling reference When customizing primitives, you can use the following formats for colors, fonts, and line styles: #### Colors - `#RGB` - `#RRGGBB` - `rgb(red, green, blue)` - `rgba(red, green, blue, alpha)` #### Fonts You can use a string in the format: ` pt `. For example, `"bold 12px Verdana"`. #### Line Styles Style|Value ---|--- Solid|0 Dotted|1 Dashed|2 [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor [`createOrderLine`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createorderline [`createPositionLine`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createpositionline [`createExecutionShape`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createexecutionshape [`IChartWidgetApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi [`onCancel`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IOrderLineAdapter#oncancel [`onModify`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IOrderLineAdapter#onmodify [`trading_customization`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#trading_customization URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List ========================================================================================== # Watchlist ## Overview The **Watchlist** is a widget that allows users to track price movements and volume of specific financial instruments in real-time. Watchlists also allow users to quickly switch between the symbols. The Watchlist widget is displayed on the widget panel on the right side of the chart. ![Watchlist widget](https://www.tradingview.com/charting-library-docs/img/watchlist.png) Users can manage their lists through the UI. For example, they can create new lists, modify existing ones, export active lists, and perform other actions. You can also programmatically manage user lists using the [Watchlist API](#watchlist-api). ![Watchlist widget menu](https://www.tradingview.com/charting-library-docs/img/watchlist-menu.png) ## Enable the widget :::info The Watchlist widget requires quote data. Therefore, you need to implement the [`getQuotes`], [`subscribeQuotes`], and [`unsubscribeQuotes`] methods within your Datafeed API. ::: The [`widgetbar`] property of the [Widget Constructor] allows managing the widget panel, including the Watchlist widget. To enable the widget, set the [`watchlist`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.WidgetBarParams#watchlist) property to `true`. You can also select the default symbols for the default watchlist and make it read-only using the [`watchlist_settings`] property. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", //highlight-start widgetbar: { watchlist: true, watchlist_settings: { default_symbols: ["AAPL", "IBM", "MSFT"], readonly: true, }, }, //highlight-end }) ``` ## Watchlist API The Watchlist API provides extensive ways to interact with watchlists. For example, you can modify watchlist values on the fly or subscribe to events to keep track of user watchlists. Use the [`watchList`] method to retrieve the [`IWatchListApi`] object for interacting with the watchlist. ```js const watchlistApi = await widget.watchList(); // Get the Watchlist API ``` Watchlist items should be symbol names that your datafeed [`resolveSymbol`] method can resolve. This means that generally shorter names such as `AAPL` can be used if your datafeed understands it. However, it is recommended that you provide the symbol names as they appear within the [`LibrarySymbolInfo`] object, for example, `NASDAQ:AAPL`. ### Create multiple watchlists You cannot instantiate the widget with multiple watchlists directly from the Widget Constructor. Instead, you should use the API to create multiple watchlists. The code sample below shows how to create lists with and without specific items. ```js const watchlistApi = await widget.watchList(); // Get the Watchlist API const firstList = watchlistApi.createList("First list"); // Create a new empty list const secondList = watchlistApi.createList("Second list", ["AMZN", "ADBE"]); // Create another list with items ``` ### Retrieve watchlist data Use the [`getAllLists`] method to get all watchlists' data such as their IDs, titles, and symbol IDs. ```js const watchlistApi = await widget.watchList(); // Get the Watchlist API watchlistApi.getAllLists(); ``` This method returns an instance of the `WatchListSymbolListMap` interface that contains watchlists' IDs and the corresponding [`WatchListSymbolList`] objects. ```json { "id123456789": { "id": "id123456789", "symbols": [ "###TOP SECTION", "AAPL", "IBM", "###SECOND SECTION", "MSFT", "###NEW SECTION", "AMZN" ], "title": "Watchlist" }, "id987654321": { "id": "id987654321", "symbols": [ "MSFT", "ADBE", "AMZN" ], "title": "My list" } } ``` You can also call the [`getActiveListId`] method to get an ID of the active watchlist. ## Add sections The more symbols users add, the more difficult it becomes to manage and navigate the list. Sections in watchlists help users organize their lists more effectively. Sections can be named, moved, and deleted. You can also programmatically add sections to watchlists using sections dividers. Any list item that has the `###` prefix is considered a section divider. - Adding sections to the default watchlist within the [Widget Constructor](#enable-the-widget). ```js widgetbar: { watchlist: true, watchlist_settings: { default_symbols: ["###TOP SECTION", "AAPL", "IBM", "###SECOND SECTION", "MSFT"], readonly: true, }, }, ``` - Adding sections with items to a new and existing watchlist using [API](#watchlist-api). ```js // Create new watchlist with a section and items const watchlistApi = await widget.watchList(); const mySymbolList = watchlistApi.createList("My new list", ["###TEST SECTION", "AMZN", "ADBE"]); // Add new section and item to the active watchlist const activeListId = watchlistApi.getActiveListId(); const activeListItems = watchlistApi.getList(activeListId); watchlistApi.updateList(activeListId, [...activeListItems, "###NEW TEST SECTION", "AAPL", "MSFT"]); ``` ## Store watchlist items Watchlist items are saved as part of the [user settings]. By default, user settings are saved into the browser's [`localStorage`], but you can also save them using [`settings_adapter`] in your preferred storage. If you want to store watchlist items separately from other settings, you can implement your logic to store the watchlist data on your server. You can use the `IWatchListApi` methods such as [`onListAdded`], [`onListChanged`], [`onListRemoved`], and [`onListRenamed`] to know when something has changed and you should save it. ## Display logos If you want to display logos for symbols within the Watchlist widget, follow the steps below: 1. Add the [`show_symbol_logos`] featureset to the [`enabled_features`] array. 2. Provide URLs for symbols in the [`logo_urls`] property of the [`LibrarySymbolInfo`] object. Pass the object as a parameter to the callback of the [`resolveSymbol`] method. 3. Implement the [`getQuotes`], [`subscribeQuotes`], and [`unsubscribeQuotes`] methods within your Datafeed API. [`getActiveListId`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatchListApi#getactivelistid [`getAllLists`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatchListApi#getalllists [`getQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes [`enabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#enabled_features [`IWatchListApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatchListApi [`LibrarySymbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo [`localStorage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage [`logo_urls`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#logo_urls [`onListAdded`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatchListApi#onlistadded [`onListChanged`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatchListApi#onlistchanged [`onListRemoved`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatchListApi#onlistremoved [`onListRenamed`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatchListApi#onlistrenamed [`resolveSymbol`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol [`settings_adapter`]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings#settings-adapter [`show_symbol_logos`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#show_symbol_logos [`subscribeQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribequotes [`unsubscribeQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#unsubscribequotes [user settings]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings [`watchList`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#watchlist [`WatchListSymbolList`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.WatchListSymbolList [`watchlist_settings`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.WidgetBarParams#watchlist_settings [`widgetbar`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#widgetbar [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal =============================================================================== [ { "anchorName": "name", "cells": [ "name", "Yes", "Unique formatter name. You should typecast it to FormatterName." ] }, { "anchorName": "formatText", "cells": [ "formatText", "Yes", "A function that is used for formatting a cell value to string. formatText is required because it is used to generate exported data. However, if you choose not to display this data, you can return an empty string." ] }, { "anchorName": "formatElement", "cells": [ "formatElement", "No", "A function that is used for formatting a cell value to a string or an HTML element. If the formatElement function is provided, it only handles the formatting of displayed values. Otherwise, the formatText function is used. For optimal performance, it is recommended to only use formatText if you intend to display only string values." ] }, { "anchorName": "isPriceFormatterNeeded", "cells": [ "isPriceFormatterNeeded", "No", "Allows usage of priceFormatter." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal =============================================================================== [ { "anchorName": "date", "cells": [ "Date", "\"date\"", "Displays the date or time.

Expected data type: [date]." ] }, { "anchorName": "dateOrDateTime", "cells": [ "DateOrDateTime", "\"dateOrDateTime\"", "Displays either the date or both the date and time. This formatter accepts an object in the following format:
{ dateOrDateTime: number, hasTime: boolean }.
If hasTime is set to true, both the date and time are displayed; otherwise, only the date is displayed.

Expected data type: [date]." ] }, { "anchorName": "default", "cells": [ "Default", "\"default\"", "Displays data as a string with space-separated values.

Expected data type: [string]." ] }, { "anchorName": "empty", "cells": [ "Empty", "\"empty\"", "Displays an empty string instead of a value.

Expected data type: [string]." ] }, { "anchorName": "fixed", "cells": [ "Fixed", "\"fixed\"", "Displays a number with two decimal places.

Expected data type: [number].
Often used for the following dataFields values: [\"balance\"] or [\"equity\"]." ] }, { "anchorName": "fixedInCurrency", "cells": [ "FixedInCurrency", "\"fixedInCurrency\"", "Displays a number with two decimal places and adds the currency symbol.

Expected data types: [number, string].
Often used for the following dataFields values: [\"balance\", \"currency\"] or [\"equity\", \"currency\"]." ] }, { "anchorName": "formatPrice", "cells": [ "FormatPrice", "\"formatPrice\"", "Displays a symbol's price.

Expected data type: [number].
Often used for the following dataFields values: [\"limitPrice\"], [\"stopPrice\"], [\"avgPrice\"]." ] }, { "anchorName": "formatPriceForexSup", "cells": [ "FormatPriceForexSup", "\"formatPriceForexSup\"", "Displays the price of the symbol with the last character shown in superscript. This formatter works only if the instrument type is set to forex.

Expected data type: [number].
Often used for the following dataFields values: [\"last\"]." ] }, { "anchorName": "formatPriceInCurrency", "cells": [ "FormatPriceInCurrency", "\"formatPriceInCurrency\"", "Displays a symbol's price and adds the currency symbol.

Expected data type: [number, string].
Often used for the following dataFields values: [\"limitPrice\", \"currency\"], [\"stopPrice\", \"currency\"], [\"avgPrice\", \"currency\"]." ] }, { "anchorName": "formatQuantity", "cells": [ "FormatQuantity", "\"formatQuantity\"", "Displays an integer or floating-point quantity with a space to separate thousands groups.

Expected data type: [number].
Often used for the following dataFields values: [\"qty\"] or [\"filledQty\"]." ] }, { "anchorName": "integerSeparated", "cells": [ "IntegerSeparated", "\"integerSeparated\"", "Displays integer values with thousands separated by non-breaking spaces.

Expected data type: [number].
Often used for the following dataFields values: [\"qty\"] or [\"filledQty\"]." ] }, { "anchorName": "localDate", "cells": [ "LocalDate", "\"localDate\"", "Displays the local date or time.

Expected data type: [date]." ] }, { "anchorName": "localDateOrDateTime", "cells": [ "LocalDateOrDateTime", "\"localDateOrDateTime\"", "Displays either the date or both the date and time in the local time zone. This formatter accepts an object in the following format:
{ dateOrDateTime: number, hasTime: boolean }.
If hasTime is set to true, both the date and time are displayed; otherwise, only the date is displayed.

Expected data type: [date]." ] }, { "anchorName": "marginPercent", "cells": [ "MarginPercent", "\"marginPercent\"", "Displays numeric values as percentages. If the value is below 0.01, the formatter returns the raw value with a percentage sign. If the value is non-finite, the formatter returns \"> 200%\". If the value is undefined, the formatter returns an empty string.

Expected data type: [number].
Often used for the following dataFields value: [\"marginRate\"]." ] }, { "anchorName": "percentage", "cells": [ "Percentage", "\"percentage\"", "Displays numeric values as percentages.

Expected data type: [number]." ] }, { "anchorName": "pips", "cells": [ "Pips", "\"pips\"", "Displays numbers as pips.

Expected data type: [number].
Often used for the following dataFields value: [\"pipValue\"]." ] }, { "anchorName": "positionSide", "cells": [ "PositionSide", "\"positionSide\"", "Displays the position side: Short or Long.

Expected data type: [number].
Often used for the following dataFields value: [\"side\"]." ] }, { "anchorName": "profit", "cells": [ "Profit", "\"profit\"", "Displays profit in the account currency. It also adds the + (plus) sign, separates thousands, and changes the cell text color to red or green.

Expected data type: [number]." ] }, { "anchorName": "profitInInstrumentCurrency", "cells": [ "ProfitInInstrumentCurrency", "\"profitInInstrumentCurrency\"", "Displays profit in the instrument currency. It also adds the + (plus) sign, separates thousands, and changes the cell text color to red or green.

Expected data types: [number, string]." ] }, { "anchorName": "side", "cells": [ "Side", "\"side\"", "Displays the order side: Sell or Buy.

Expected data type: [number].
Often used for the following dataFields value: [\"side\"]." ] }, { "anchorName": "status", "cells": [ "Status", "\"status\"", "Formats the order status.

Expected data type: [number].
Often used for the following dataFields value: [\"status\"]." ] }, { "anchorName": "symbol", "cells": [ "Symbol", "\"symbol\"", "Displays brokerSymbol and is used for a symbol field. Note that when you click a symbol, the chart changes according to the symbol field.

Expected data types: [string, string, string].
Often used for the following dataFields value: [\"brokerSymbol\", \"symbol\", \"message\"]." ] }, { "anchorName": "text", "cells": [ "Text", "\"text\"", "Displays a text value.

Expected data type: [string].
Often used for the following dataFields value: [\"message\"]." ] }, { "anchorName": "type", "cells": [ "Type", "\"type\"", "Displays the order type: Limit / Stop / Stop-limit / Market.

Expected data types: [number, string, number]. Often used for the following dataFields values: [\"type\", \"parentId\", \"stopType\"]." ] }, { "anchorName": "variablePrecision", "cells": [ "VariablePrecision", "\"variablePrecision\"", "Displays a number with variable precision.

Expected data type: [number].
Often used for the following dataFields value: [\"qty\"]." ] } ] URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager =============================================================================================== # Account Manager The **Account Manager** is an interactive widget that displays trading information, such as orders, positions, an account balance, and more. ![Account Manager](https://www.tradingview.com/charting-library-docs/img/account-manager-full.png) :::tip This article provides an overview of the Account Manager. For a hands-on understanding, refer to the [Broker API implementation][broker-sample] 🔐 (access is [restricted][get-access]) on GitHub. This example is used on the [Trading Platform demo page] where you can test trading features, including the Account Manager. ::: ## Create Account Manager To enable the Account Manager, implement the [`accountManagerInfo`] method within the [Broker API]. This method should return an [`AccountManagerInfo`][am-type] object containing the information that will be displayed in the Account Manager. The Account Manager consists of the [*Account Summary* row](#account-summary-row) and different [pages](#pages). The Account Manager includes the default [*Orders* and *Positions*](#orders-and-positions) pages, but you can also add [*History*](#history), [*Notifications log*](#notifications-log), or your [custom](#custom-pages) pages. ```js accountManagerInfo() { return { accountTitle: "Sample title", // Account Manager title summary: [], // Custom fields that are displayed in the Account Summary row orderColumns: [], // Columns that build the Orders page positionColumns: [], // Columns that build the Positions page pages: [], // Columns that build your custom pages }; } ``` ## User accounts The Account Manager is designed to display the trading data of a particular user account. Users can have multiple accounts and switch between them using the drop-down menu in the Account Manager. Refer to [Multiple accounts] for more information. ## Account Summary row The *Account Summary* row is a line that is always displayed at the top-right corner of the Account Manager. Usually, it contains the most important information about the account's current state, such as balance and equity. ![Account Summary row](https://www.tradingview.com/charting-library-docs/img/account-summary-row.png) Use the [`summary`] property to build the *Account Summary* row. Each [`AccountManagerSummaryField`] object passed within `summary` creates a separate field. ```js // Here, balanceValue = host.factory.createWatchedValue(value); summary: [ { text: "Balance", // The summary field title wValue: balanceValue, // A WatchedValue object that is used to read the field state formatter: "fixed", // The formatter name that formats the field isDefault: true, // Displays the field by default }, ] ``` ### Watched values The values defined in the row use [watched values]. This means that these values should be constantly updated, so the users have up‑to‑date data about their account state. To create a `WatchedValue` object, use the [`createWatchedValue`] method within the [Trading Host]. To update the values, use the [`setValue`] method. ## Pages The Account Manager has the [*Orders*, *Positions*](#orders-and-positions), [*History*](#history), and [*Notifications log*](#notifications-log) pages. You can also create your [custom pages](#custom-pages). Each page represents a table where you define [columns](#columns) and the data to be displayed. ### Orders and Positions When implementing the [Broker API], you should implement the [`orders`] and [`positions`] methods. The library calls these methods to retrieve data objects about the user's orders and positions. This data is then displayed on the [*Orders* and *Positions*](#orders-and-positions) pages of the Account Manager. To specify the data you want to display on these pages, define the [`orderColumns`] and [`positionColumns`] properties in the `AccountManagerInfo` object. These properties represent arrays of objects where each object is a separate [column](#columns). import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; The Orders page in the Account Manager The Positions page in the Account Manager ### History The *History* page shows details about all orders with their final [statuses]. To enable order history, follow the steps below: 1. Set the [`supportOrdersHistory`] flag, which adds the *History* tab to the Account Manager, to `true`. Refer to the [Trading features configuration] section for more information about configuration flags. 2. Provide the order history via the [`ordersHistory`] method. The returned orders should have final statuses like `rejected`, `filled`, or `cancelled`. 3. Add the [`historyColumns`] property to the [`AccountManagerInfo`][am-type] object to define and display data columns. Optionally, use the [`historyColumnsSorting`] property for sorting values. ### Notifications log The *Notifications log* page logs trading actions like placing or canceling orders. This page is visible by default, however, you can hide it via the [`showNotificationsLog`] flag. Refer to the [Trading features configuration] section for more information about configuration flags. ![Notifications log](https://www.tradingview.com/charting-library-docs/img/notifications-log.png) You can also create notifications via the [`showNotification`] method. These notifications appear as toast messages at the bottom-left corner and are also recorded in the *Notifications log* page. If you want to display custom fields' information from orders or positions in notifications, use the [`customNotificationFields`] property within the [`broker_config`] object of the [Widget Constructor]. ### Custom pages Custom pages can be created via the [`pages`] property of [`AccountManagerInfo`]. Additionally, you have the flexibility to include multiple tables within your custom pages by specifying them in the [`tables`] property. See [How to create custom page in Account Manager]. ## Columns Each Account Manager page is a table, where each column is an [`AccountManagerColumnBase`] object. The order of column display aligns with the sequence of objects added to the columns array. ```javascript { id: "id", // Unique ID label: "Order id", // Column title dataFields: ["id"], // Data that is displayed in the column }, ``` `AccountManagerColumnBase` has three required properties: - `id` — a unique identifier of a column. - `label` — the title that is displayed in the column's header. - `dataFields` — an array of strings that match the property names in the [order]/[position] data object. `dataFields` is used to generate the values displayed in a column. The displayed value in the column updates only when the corresponding values in the data object change. For example: - For a column with `dataFields` set as `["avgPrice", "qty"]`, the displayed value updates only when the `avgPrice` or `qty` values in the data object change. - For a column with an empty `dataFields` array, the displayed value updates if any values in the data object change. To manage how the values are displayed in the columns, use the [`formatter`] property. ## Configure behavior ### Disable Account Manager The [`accountManagerInfo`] method is required for implementation. However, if you do not want to display the Account Manager, you can use the sample code from the [Broker API implementation][broker-sample-am-method] and disable the [`trading_account_manager`] featureset. ### Hide Account Manager on startup By default, the Account Manager is always opened. If you want to keep it hidden on startup, disable the [`open_account_manager`] featureset. The [`getAccountManagerVisibilityMode`] and [`setAccountManagerVisibilityMode`] methods in the [Trading Host] can be used to either get the visibility state of the Account Manager or change it. [am-type]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [broker-sample]: https://github.com/tradingview/trading_platform/tree/master/broker-sample "The repository is private." [broker-sample-am-method]: https://github.com/tradingview/trading_platform/blob/5b6575760cb6d52dc3cedce0009ccb6d16dc85d7/broker-sample/lib/broker.js#L174 [How to create custom page in Account Manager]: https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-page-in-account-manager [get-access]: https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-start#getting-access "Click to open the 'Getting Access' section." [order]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PlacedOrder [position]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Position [statuses]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders#order-statuses [Trading features configuration]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-features-configuration [Trading Host]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#trading-host [Trading Platform demo page]: https://trading-terminal.tradingview-widget.com/ [Multiple accounts]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/multiple-accounts [watched values]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerSummaryField#wvalue [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor [`AccountManagerColumnBase`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerColumnBase [`accountManagerInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#accountmanagerinfo [`AccountManagerSummaryField`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerSummaryField [`getAccountManagerVisibilityMode`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#getaccountmanagervisibilitymode [`setAccountManagerVisibilityMode`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#setaccountmanagervisibilitymode [`broker_config`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#broker_config [`createWatchedValue`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterFactory#createwatchedvalue [`customNotificationFields`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SingleBrokerMetaInfo#customnotificationfields [`formatter`]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters [`historyColumns`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo#historycolumns [`historyColumnsSorting`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo#historycolumnssorting [`open_account_manager`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#open_account_manager [`orderColumns`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo#ordercolumns [`orders`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#orders [`ordersHistory`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#ordershistory [`pages`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo#pages [`positionColumns`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo#positioncolumns [`positions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#positions [`setValue`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatchedValue#setvalue [`showNotification`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#shownotification [`showNotificationsLog`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#shownotificationslog [`summary`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo#summary [`supportOrdersHistory`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportordershistory [`tables`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerPage#tables [`trading_account_manager`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#trading_account_manager URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/multiple-accounts ================================================================================================================= # Multiple accounts :::info Creating broker accounts, handling authentication and authorization processes should be implemented on your backend side. Your backend server should also process users' trades and provide the library with users' data through the [Broker API]. The library only displays users' trading data and notifies your Broker API implementation about user actions. Refer to [Authentication] for more information on authentication approaches and how the library handles users logging into their broker accounts. ::: The [Account Manager] is designed to display the trading data of a particular user account. Users can have multiple accounts and switch between them using the drop-down menu in the Account Manager. Drop-down menu for selecting multiple accounts This menu appears automatically when [`accountsMetainfo`] returns an array of objects. When users switch accounts, the library calls the [`setCurrentAccount`] method, providing your backend server with the ID of the requested account. See the CodePen example below. [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [Authentication]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/authentication [`accountsMetainfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#accountsmetainfo [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [`setCurrentAccount`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#setcurrentaccount URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters ================================================================================================================ # Value formatters You can determine how the values appear in the [Account Manager] tables by using the [`formatter`] property of [`AccountManagerColumnBase`]. If no `formatter` is set, values are displayed as they are, separated by spaces. When a `formatter` is defined, it processes only the values specified in the `dataFields` property. If `dataFields` is an empty array, the `formatter` will receive the entire [order]/[position] data object. ```js // AccountManagerColumnBase object { id: "limitPrice", label: "Limit Price", dataFields: ["limitPrice"], // highlight-next-line formatter: "formatPrice", // Standard formatter that displays symbol's price }, ``` The `formatter` property can contain either `StandardFormatterName` or `FormatterName` object. - `StandardFormatterName` refers to the [built-in formatters](#built-in-formatters). - `FormatterName` is a general type that can be a built-in name or any other string corresponding to a [custom formatter](#custom-formatters). ## Formatter and dataFields dependency The `formatter` property expects that the [`dataFields`] property has certain types of values defined in a specific order. `dataFields` is an array of strings that match the property names in the [order]/[position] data object. The values for these properties in the data object are expected to be a number, string, date, etc. The mapping of the `formatter` and `dataFields` values is described in the [`StandardFormattersDependenciesMapping`] interface. ### Example Assume that your data object has two custom fields: `balance` and `currency`. ```js { // <...other object fields...> balance: 1000.00, currency: "EUR", } ``` You want to display the user's balance in a column. The balance value should have two decimal places and a currency symbol. For this purpose, you can use the built-in [`fixedInCurrency`](#fixedInCurrency) formatter that expects the following arguments: 1. A number that represents the price. 2. A string that represents the currency code. This means that `dataFields` should have the values of the followings types: `[number, string]`. Then, the `AccountManagerColumnBase` object for the balance column should look as follows: ```js { id: "balance", label: "Balance", dataFields: ["balance", "currency"], formatter: "fixedInCurrency", }, ``` ## Built-in formatters The table below lists the built-in formatter values, expected types of the properties within `dataFields`, and the default fields of the [order]/[position] data object. import AnchoredTable from '@site/src/components/anchored-table'; import standardFormatterName from '../_tables/standard-formatter-name.json'; ## Custom formatters You can implement your custom formatter using the [`customFormatters`] property in the [`AccountManagerInfo`] object. Each custom formatter is an object with the following fields. import customFormatterProperties from '../_tables/custom-formatter-properties.json'; ### Example The CodePen example below implements two custom formatters that display the following: - Dynamically changing text - A button These formatters are used to format values for custom columns of the *Positions* page. [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [order]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PlacedOrder [position]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Position [`AccountManagerColumnBase`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerColumnBase [`accountManagerInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#accountmanagerinfo [`customFormatters`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo#customformatters [`dataFields`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerColumnBase#datafields [`formatter`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerColumnBase#formatter [`StandardFormattersDependenciesMapping`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StandardFormattersDependenciesMapping URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues ============================================================================================= # Common Broker API issues This article describes common issues that you might face when implementing the [Broker API]. ## Timeout issue You may encounter one of the following timeout issues: - *Failed to close position: Position closing timeout*. - *Failed to modify order: timeout waiting for new order*. - *Failed to reverse position: Position reversing timeout*. These issues happen because the library either received incorrect information or failed to receive timely updates for an order or a position from your Broker API implementation. To avoid these issues, ensure that: - Your Broker API implementation calls [`orderUpdate`]/[`positionUpdate`] within 10 seconds after the library sends a request to place/modify/cancel order or close/reverse position. This update is confirmation to the library that your backend server received the request. - Your backend server and Broker API implementation provide the correct information to the library. Consider the following example: a user closes a position of 10 AAPL shares. In this case, the library calls the [`closePosition`] method to notify your backend server about the user's intent. As a parameter, it provides your server with `positionId`. After that, the library expects your backend server to close the position and provide an update on its new state within 10 seconds. Your Broker API implementation should call the [`positionUpdate`] method on the Trading Host to provide updates. As a parameter, it should send the correct [`Position`] object to the library, which means that: - the `id` property should match `positionId` - the `qty` property should be `0` - other required properties are specified - all properties correspond to the declared types When the library gets a position update, for example with a non-zero quantity or a different ID, it assumes the data is for a different position and waits for the correct data. If the library waits more than 10 seconds, it returns *Failed to close position: Position closing timeout*. ## Order and position IDs mismatch In some backend implementations, you might change the ID of an [order] or [position] between the time it’s submitted and the time it’s processed by your backend. When this happens, the library may still reference the original ID, which no longer matches what's on your backend. This mismatch can lead to issues in the UI. For example, incorrect data may be displayed, and users may be unable to modify or cancel orders/positions because the library is referencing an invalid or unknown ID. To recover from this mismatch, you can call the [`ordersFullUpdate`] and [`positionsFullUpdate`] methods. These methods force the library to clear existing data and refetch the full list of orders or positions as if it was the first-time load. Use these methods when you're unable to maintain a stable mapping between frontend and backend IDs. :::warning `ordersFullUpdate` and `positionsFullUpdate` are intended only for rare edge cases, such as dynamic ID changes. These methods should not be used as part of your regular update flow. If you need to notify the chart about a new or updated order/position, use [`orderUpdate`] or [`positionUpdate`] instead. These methods are designed to update the UI without clearing and reloading all data. They should be your **default approach** for keeping the chart in sync with your backend events. ::: ## Empty fields in bracket controls You may encounter an issue when the input fields for bracket controls are empty. Besides, users cannot enter values when accessing the *Edit position brackets* dialog. Empty bracket controls This issue occurs because the library has not received all the necessary values for these fields. To solve this issue, ensure that your integration meets the following requirements. - The [`resolveSymbol`] method returns all required fields within the `LibrarySymbolInfo` object. - The [`symbolInfo`] method returns all required fields within the `InstrumentInfo` object. - You provide the library with the following updates: - Quote values via the [`getQuotes`]/[`subscribeQuotes`] method of the Datafeed API. - Pip values via the [`pipValueUpdate`] method of the Trading Host if [`subscribePipValue`] is implemented. Ignore this update if `subscribePipValue` is not implemented. - Equity values via the [`equityUpdate`] method of the Trading Host. :::tip It is advisable to send the equity updates once the broker has been created. If you want to provide updates while constructing the broker, encapsulate the updates within the [`setTimeout`] method. ```js setTimeout(() => { this._host.equityUpdate(12345678); }, 5); ``` ::: ## Symbol quantity is overridden The default symbol quantity should be provided in the [`qty`] field of [`InstrumentInfo`] when the library calls [`symbolInfo`]. When a user modifies the quantity in the [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket), the library saves the new value using either local storage or [`settings_adapter`]. This user-defined quantity is then used instead of the default one for the next orders. This is intended behavior. You can use the following methods to control quantity: - [`getQty`] - [`setQty`] - [`subscribeSuggestedQtyChange`] - [`unsubscribeSuggestedQtyChange`] If you want to override the user-defined quantity, call the [`subscribeSuggestedQtyChange`] method to track quantity changes and then reset its value using [`setQty`]. ```javascript var widget = (window.tvWidget = new TradingView.widget({ // Other widget properties broker_factory: function (host) { window.host = host; return new Brokers.BrokerDemo(host, datafeed); }, })); // Declare a callback const cb = (qty) => { console.log(`Quantity changed to ${qty}`); }; // Subscribe to quantity changes for BTCUSD using the callback host.subscribeSuggestedQtyChange('COINBASE:BTCUSD', cb); // Change the quantity host.setQty('COINBASE:BTCUSD', 24); // Unsubscribe from quantity changes for BTCUSD host.unsubscribeSuggestedQtyChange('COINBASE:BTCUSD', cb); ``` [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [`closePosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#closeposition [`equityUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#equityupdate [`getQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes [`getQty`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#getqty [`InstrumentInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.InstrumentInfo [order]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders [`ordersFullUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#ordersfullupdate [`orderUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#orderupdate [`pipValueUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#pipvalueupdate [position]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions [`Position`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Position [`positionsFullUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#positionsfullupdate [`positionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#positionupdate [`qty`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.InstrumentInfo#qty [`resolveSymbol`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol [`setQty`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#setqty [`setTimeout`]: https://developer.mozilla.org/en-US/docs/Web/API/setTimeout [`settings_adapter`]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings#settings-adapter [`subscribePipValue`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#subscribepipvalue [`subscribeQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribequotes [`subscribeSuggestedQtyChange`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#subscribesuggestedqtychange [`symbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#symbolinfo [`unsubscribeSuggestedQtyChange`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#unsubscribesuggestedqtychange URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market =============================================================================================== # Depth of Market ## Overview The **Depth of Market** (DOM) widget allows users to see the volume of bids and asks for an asset at different prices. The widget supports frequent data updates, giving users a comprehensive view of supply and demand. DOM widget :::tip You can find more information about interacting with the widget's UI in the [Depth of Market: what it is and how traders can use it] article. ::: ## Connect widget :::info This widget is part of the [Trading Platform]. Trading on the platform relies on two key components: the Broker API and the Trading Host. Before implementing this widget, ensure that you have implemented the required Broker API methods. We recommend reading the [Core concepts] section for a better understanding. ::: ### 1. Provide data The DOM widget displays data in static mode. This means that the price series is fixed, while the current price moves within, above, or below the designated range. The widget sources its data from the [`DatafeedQuoteValues`] and [`DOMData`] objects. To provide this data, you need to implement the following [Datafeed API] methods: - [`getQuotes`] - [`subscribeQuotes`] - [`unsubscribeQuotes`] - [`subscribeDepth`] - [`unsubscribeDepth`] ### 2. Enable the widget 1. Add the [`dom_widget`] featureset to the [`enabled_features`] array of the [Widget Constructor] object. 2. Set the [`supportLevel2Data`] flag, which enables [Level 2] data, to `true`. Refer to the [Trading features configuration] section for more information about configuration flags. 3. Implement the [`cancelOrders`] method within your [Broker API] implementation. This method is required for the DOM widget. ### Example The CodePen example below demonstrates how to enable the DOM widget in the UI and implement [`subscribeDepth`] and [`unsubscribeDepth`] to populate the DOM with fake data. Since the DOM is supported only on larger viewports, it will not be displayed within the iframe below. We recommend clicking the *Edit on CodePen* button to view the full example on CodePen, where the DOM widget is visible. To open the DOM, click the *Trade* button in the [Account Manager]. ## Display DOM on start If you want to display the DOM widget when a user opens the chart for the first time, add the [`show_dom_first_time`] featureset to the [`enabled_features`] array of the [Widget Constructor] object. [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [Core concepts]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts [Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api [Depth of Market: what it is and how traders can use it]: https://www.tradingview.com/support/solutions/43000516459-depth-of-market-dom-what-it-is-and-how-traders-can-use-it/ [Level 2]: https://www.investopedia.com/terms/l/level2.asp [Trading features configuration]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-features-configuration [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor [`cancelOrders`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#cancelorders [`dom_widget`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#dom_widget [`enabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#enabled_features [`getQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes [`show_dom_first_time`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#show_dom_first_time [`subscribeDepth`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribedepth [`subscribeQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribequotes [`supportLevel2Data`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportlevel2data [`unsubscribeDepth`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#unsubscribedepth [`unsubscribeQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#unsubscribequotes [`DatafeedQuoteValues`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedQuoteValues [`DOMData`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DOMData URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news/News-Api-Examples ====================================================================================================== # News API Usage Examples :::caution This page has moved here: [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news) ::: URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news ==================================================================================== # News Widget :::caution This page has moved here: [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news) ::: URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news ==================================================================================== # News ## Overview The **News** widget allows you to displays latest news on a symbol, exchange, or symbol type. ![News widget]() ## Enable the widget :::info The _News_ widget requires quote data. Therefore, you need to implement the [`getQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes), [`subscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribequotes), and [`unsubscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#unsubscribequotes) methods within your [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api). ::: The [`widgetbar`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#widgetbar) property of the [Widget Constructor] allows managing the widget panel, including the _News_ widget. To enable the widget, set the [`news`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.WidgetBarParams#news) property to `true`. ```js const widget = new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", //highlight-start widgetbar: { news: true, }, //highlight-end }) ``` ## Connect news The library does not contain any built-in news providers. Therefore, you should connect a [RSS feed](#rss-feed) or your own [news source](#custom-news-source) using the [`rss_news_feed`] or [`news_provider`] properties, respectively. :::info If both `news_provider` and `rss_news_feed` properties are specified, `rss_news_feed` is ignored. ::: ### RSS feed Use the [`rss_news_feed`] property of the [Widget Constructor] to connect RSS feeds to the library. To do this, specify a [`RssNewsFeedParams`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RssNewsFeedParams) object that should contain at least the default RSS configuration. For each configuration, provide the following properties: - [`url`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RssNewsFeedInfo#url) — a URL that the library should request. The URL can contain tags in curly brackets, such as `{SYMBOL}`, `{TYPE}`, or `{EXCHANGE}`, that the library replaces with values. - [`name`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.RssNewsFeedInfo#name) — a feed name that is displayed underneath the news. ```javascript rss_news_feed: { "default": { url: "https://articlefeeds.nasdaq.com/nasdaq/symbols?symbol={SYMBOL}", name: "NASDAQ" } } ``` You can specify a different RSS for each symbol type or use only one for all symbols. The names of the properties should match the symbol types. ```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" } } ``` ### Custom news source You should implement [`GetNewsFunction`](https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#getnewsfunction) and assign it to the [`news_provider`] property to connect any custom news source to the library. The library calls this function to request data for the widget. In response, you should pass a [`GetNewsResponse`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.GetNewsResponse) object to the callback function. In this object, specify an array of [`newsItem`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.NewsItem) objects that contain data for each news item. ```javascript const widget = new TradingView.widget({ news_provider: function getNews(symbol, callback) { const newsItems = [ { title: "Title 1", source: "Source Name", published: new Date("2023-12-20 12:34").valueOf(), shortDescription: "Hello World, Article 1.", }, { title: "Title 2", source: "Source Name", published: new Date("2023-12-19 12:34").valueOf(), shortDescription: "Hello World, Article 2.", }, ]; callback({ title: "Latest News Stories", newsItems, }); }, }); ``` You can specify a URL to the external source in the [`link`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.NewsItem#link) property of `newsItem`. This link is opened in a pop-up dialog when a user clicks on the corresponding news item. If `link` is not provided, the information from the [`fullDescription`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.NewsItem#fulldescription) property is displayed instead. ```javascript const newsItems = [ { // .. link: "https://www.example.com/test", }, ] ``` To request news from scratch, for example, when an event occurs, call the [`refresh`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.INewsApi#refresh) method from `INewsApi`, which can be retrieved with the [`news`](https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methodsnews) method. ```javascript const widget = new TradingView.widget({ // Widget options }); async function someEventHandler() { const newsApi = await widget.news(); newsApi.refresh(); } ``` [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor [`rss_news_feed`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#rss_news_feed [`news_provider`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#news_provider URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket ============================================================================================ # Order Ticket The **Order Ticket** (also known as Order Panel) is a dialog that allows users to place orders. Users can open this dialog in several ways: - By clicking the *Trade* button in the [Account Manager]. - By clicking the *Plus* button on the [Price Scale]. - By clicking the *Buy Market* and *Sell Market* buttons in the [Legend]. - By right-clicking the chart and selecting *Trade → Create new order…* in the context menu. The Order Ticket is enabled by default, but you can disable it using the [`order_panel`] featureset. Order Ticket ## Configure order types The library supports four [order types]: limit, market, stop, and stop-limit. By default, users can select market, limit, and stop orders in the Order Ticket. But you can disable support for these order types via the [`supportMarketOrders`], [`supportLimitOrders`], and [`supportStopOrders`] flags, respectively. You can also enable a stop-limit order type by setting [`supportStopLimitOrders`] to `true`. Refer to the [Trading features configuration][config-flags] section for more information on setting configuration flags. ## Change text for quantity units To customize the text displaying quantity units in the Order Ticket, use the [`units`] field within the `InstrumentInfo` object. You should return this object when the library calls the [`symbolInfo`] method. ## Add custom fields If you want to add custom fields to the Order Ticket dialog, implement the [`getOrderDialogOptions`] method within your [Broker API] implementation. The method should return the [`OrderDialogOptions`] object. This object should contain the `customFields` property of the [`TradingDialogCustomField`] type. Note that the available custom field types are limited to combobox and checkbox. Similarly, you can add custom fields to the *Positions* dialog by implementing the [`getPositionDialogOptions`] method. :::info The library does not support adding custom fields to the *Order info* section of the Order Ticket. The information displayed there, such as pip value, is derived from the [`InstrumentInfo`] interface when certain broker [configuration flags][config-flags] are enabled. Consider providing additional details in the [order preview dialog](#enable-order-preview). ::: ## Enable order preview You can show users additional order details before modifying or placing orders. For example, you can display the estimated order cost, commission, expiry date, and any warning or error messages as a part of the order preview dialog. In these messages, you can provide links to external URLs, such as specific T&Cs. Note that users can still clear the *Show order confirmations* checkbox in the [ellipsis menu](#order-confirmations), meaning that the order preview dialog will not appear. To enable order preview, follow the steps below: 1. Set the following flags to `true`: - [`supportPlaceOrderPreview`] enables an order preview dialog before users place orders. - [`supportModifyOrderPreview`] enables an order preview dialog before users modify orders. Refer to the [Trading features configuration][config-flags] section for more information on setting configuration flags. 2. Implement the [`previewOrder`] method within your Broker API implementation. When users click *Buy order* or *Modify order* in the Order Ticket, the library calls `previewOrder`. This method returns the [`OrderPreviewResult`] object with the necessary information that is displayed in the order preview dialog. Within the object, you can: - Set a unique confirmation ID via `confirmId`. Note that it should be passed as a parameter to `modifyOrder` or `placeOrder`. - Customize extra fields using `sections`. - Set up text for warnings and errors using the `warnings` and `errors` properties. The warnings and errors are displayed below the order details in colored boxes. :::caution You will get the *Order preview is not supported* issue in the console if `supportPlaceOrderPreview` and `supportModifyOrderPreview` are enabled, but `previewOrder` is not implemented. ::: 3. Implement the [`modifyOrder`] and [`placeOrder`] methods. The library calls them right after users click *Send Order* in the order preview dialog: - `modifyOrder` is called when users want to modify existing orders. - `placeOrder` is called when users want to place new orders. You can check the implementation of the order preview dialog in the CodePen below. ## Enable bracket controls You can display controls for adding bracket orders in the Order Ticket dialog. [Bracket orders] allow users to protect their positions. To add controls, enable the [`supportOrderBrackets`] flag. You can also disable bracket controls only for market orders by setting the [`supportMarketBrackets`] flag to `false`. ## Manage ellipsis menu Users can access additional Order Ticket settings in the ellipsis menu. You can also programmatically [get and set values](#get-and-set-settings) for these settings. ### Default settings By default, and without specifying any [configuration flags][config-flags], the Order Ticket has the following settings shown in the ellipsis menu: - *Show Order Price in Ticks* - *Show Quantity in Money Risk* - *Show Quantity in % Risk* Default settings in the ellipsis menu of the Order Ticket ### Brackets settings If you set the [`supportOrderBrackets`], [`supportMarketBrackets`], or [`supportPositionBrackets`] flags to `true`, the *Show TP/SL inputs in Money* and *Show TP/SL inputs in %* settings will appear in the ellipsis menu. Bracket settings in the ellipsis menu of the Order Ticket :::info Note that these settings will not have any impact when used in [crypto brackets](#enable-crypto-brackets-settings). Selecting and clearing these checkboxes will not be visually reflected. ::: ### Order confirmations :::tip The [`supportPlaceOrderPreview`] and [`supportModifyOrderPreview`] flags enable order preview. It allows showing users additional order details before modifying or placing orders. Refer to [Enable order preview](#enable-order-preview) for more information. ::: If you set the [`supportPlaceOrderPreview`] or [`supportModifyOrderPreview`] flags to `true`, the *Show order confirmations* will appear in the ellipsis menu. Order Ticket Settings Order Confirmations ### Get and set settings You can programmatically access and change settings, available in the ellipsis menu. To do this, use the [`getOrderTicketSetting`] and [`setOrderTicketSetting`] methods of the [Trading Host]. You can find the full list of properties in the [OrderTicketSettings] interface. ## Enable crypto brackets settings The [`supportCryptoBrackets`] flag enables crypto brackets and displays additional settings within the *Take Profit* and *Stop Loss* brackets: *Money* and *%*. import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Order Ticket settings: crypto bracket in currency Order Ticket settings: crypto bracket in percent You can also programmatically [get or set these settings](#get-and-set-settings) using the [`showCryptoBracketsInCurrency`] and [`showCryptoBracketsInPercent`] properties. Note that these settings are not shown in the ellipsis menu. ## Enable Time in force menu You can enable the *Time in force* drop-down menu that allows users to specify order duration. Duration determines how long the order remains active. The durations drop-down menu in the Order Ticket To enable the menu, provide [`durations`] within the `SingleBrokerMetaInfo` object assigned to [`broker_config`]. The `durations` property is an array of [`OrderDurationMetaInfo`] objects that specify the order duration settings. For example, you can adjust a duration value or title that is displayed in the UI. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", broker_factory: function(host) { return new Brokers.BrokerDemo(host, datafeed); }, broker_config: { configFlags: { // Configuration flags }, // highlight-start durations: [ { name: 'DAY', value: 'DAY' }, // Day orders { name: 'GTC', value: 'GTC' }, // Good-Til-Canceled orders ], // highlight-end }, }) ``` Note that the duration options are displayed for limit, stop, and stop-limit order types by default. However, if you want to specify a different set of duration options for a particular type, you need to provide this information in the [`supportedOrderTypes`] array of the `durations` property. ## Implement custom Order Ticket You can display your own Order Ticket instead of the built-in one. To do this, you should provide [`customUI`] within the `SingleBrokerMetaInfo` object assigned to [`broker_config`]. The values of [`customUI`] are functions that Trading Platform calls to show several dialogs, including the Order Ticket. Each function returns a Promise object that should be resolved when the operation is finished or canceled. Note that the returned Promise object should be resolved with either a `true` or `false` value. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", broker_factory: function(host) { return new Brokers.BrokerDemo(host, datafeed); }, broker_config: { configFlags: { // Configuration flags }, // highlight-start customUI: { showOrderDialog: (order, focus) => Promise; }, // highlight-end }, }) ``` [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [Bracket orders]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/brackets [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [Legend]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend [order types]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders#order-types [Price Scale]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale [config-flags]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-features-configuration [`broker_config`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#broker_config [`customUI`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SingleBrokerMetaInfo#customui [`durations`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SingleBrokerMetaInfo#durations [`getOrderDialogOptions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#getorderdialogoptions [`getOrderTicketSetting`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#getorderticketsetting [`getPositionDialogOptions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#getpositiondialogoptions [`InstrumentInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.InstrumentInfo [`modifyOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#modifyorder [`OrderDialogOptions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.OrderDialogOptions [`OrderDurationMetaInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.OrderDurationMetaInfo [`order_panel`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#order_panel [`OrderPreviewResult`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.OrderPreviewResult [OrderTicketSettings]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.OrderTicketSettings [`placeOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#placeorder [`previewOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#previeworder [`setOrderTicketSetting`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#setorderticketsetting [`showCryptoBracketsInCurrency`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.OrderTicketSettings#showcryptobracketsincurrency [`showCryptoBracketsInPercent`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.OrderTicketSettings#showcryptobracketsinpercent [`supportLimitOrders`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportlimitorders [`supportMarketBrackets`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportmarketbrackets [`supportMarketOrders`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportmarketorders [`supportModifyOrderPreview`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportmodifyorderpreview [`supportedOrderTypes`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.OrderDurationMetaInfo#supportedordertypes [`supportOrderBrackets`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportorderbrackets [`supportPlaceOrderPreview`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportplaceorderpreview [`supportPositionBrackets`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpositionbrackets [`supportStopLimitOrders`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportstoplimitorders [`supportStopOrders`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportstoporders [`supportCryptoBrackets`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportcryptobrackets [`symbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#symbolinfo [`TradingDialogCustomField`]: https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#tradingdialogcustomfield [Trading Host]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#trading-host [`units`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.InstrumentInfo#units URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/authentication =============================================================================================================== # Authentication Trading Platform provides trading capabilities. Users can have accounts to trade, manage orders, track positions, monitor their potential profits and losses, and more. :::info Creating broker accounts, handling authentication and authorization processes should be implemented on your backend side. Your backend server should also process users' trades and provide the library with users' data through the [Broker API]. The library only displays users' trading data and notifies your Broker API implementation about user actions. ::: You can design the authentication and authorization processes to fit your needs. This article outlines [possible approaches](#authentication-approaches) and describes [how the library handles users logging](#how-the-library-handles-login) into their broker accounts. ## Authentication approaches ### Before accessing the app One approach is to handle authentication and authorization before users access your app. This ensures that only authenticated users can enter the app and interact with their trading data. ### Through the top toolbar button Another approach is to integrate authentication through a button in the top toolbar of the chart. You can add this button using the [`createButton`] or [`createDropdown`] methods. Such a button can trigger the authentication process, allowing users to access their trading data once authenticated. ### Through Account Manager The [Account Manager] is designed to display the trading data of a particular user account. Users can manage [multiple accounts] and switch between them using the drop-down menu in the Account Manager. Authentication and authorization can be implemented when users select an account from the drop-down menu, ensuring that each selected account is properly authenticated before data access is granted. Drop-down menu for selecting multiple accounts ## How the library handles login On startup, the library calls [`accountsMetainfo`] to get the information about accounts of a particular user. This method should return an array that contains an ID and name for each account. In general, the user login process looks as follows: 1. A user logs into their broker account. Note that the library does not provide any login dialogs, you should implement them on your side. 2. Your backend server prepares the user's data and provides a response to your [Broker API] implementation with updated information. 3. Your Broker API implementation calls the [`currentAccountUpdate`] method to notify the library about changes in account details. 4. The library calls the [`accountsMetainfo`] and [`currentAccount`] methods. [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [`accountsMetainfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#accountsmetainfo [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [`createButton`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#createbutton [`createDropdown`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#createdropdown [`currentAccount`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#currentaccount [`currentAccountUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#currentaccountupdate [multiple accounts]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/multiple-accounts URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/brackets ========================================================================================================= # Bracket orders import ThemedImage from '@theme/ThemedImage'; import useBaseUrl from '@docusaurus/useBaseUrl'; ## Overview **Bracket orders** (brackets) are orders that protect positions. In other words, brackets help users limit their losses and secure their profits by bracketing positions with two opposing [stop-loss] and [take-profit] orders. The term **parent** refers to an order or position for which brackets are created. Bracket orders are linked to the parent order/position via the [`parentId`] and [`parentType`] properties. The quantity of the bracket order always matches the parent quantity. Brackets always have the opposite side compared to their parent, for example: - A buy order is bracketed by a sell-limit order or a sell-stop order. - A sell order is bracketed by a buy-stop order or a buy-limit order. Brackets can exist either in a pair as stop-loss and take-profit or independently. This means that an order or position can have only one bracket order: stop-loss or take-profit. :::caution This article requires a thorough understanding of the Trading Platform components and their interactions. Before continuing with this article, we recommend reading the [Core concepts] article for a better understanding. ::: ## UI interactions Users can add brackets to a new or existing order or to a position. import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Placing order with brackets Adding brackets to position via bracket buttons Adding brackets to position via Protect position button ## Order brackets To enable adding order brackets in the UI, set the [`supportOrderBrackets`] flag to `true`. Refer to the [Trading features configuration] section for more information about configuration flags. ### Place order with brackets Users can place orders with two brackets or only one — either a stop-loss or take-profit. When users place orders with brackets, the library calls the [`placeOrder`] method and passes a [`PreOrder`] object as a parameter. This object contains the [`stopLoss`] and [`takeProfit`] fields. Additionally, if a user places a [limit order] or [stop orders], the `PreOrder` object should contain the following fields: - For limit order, the [`limitPrice`] field. - For stop order, the [`stopPrice`] field. #### Example Consider the following example: a user places a [market order] with two brackets.
Expand to view the diagram illustrating the process of placing a market order with brackets.
The library calls the [`placeOrder`] method, requesting to create an order. You should implement this method within the Broker API. Refer to the [Order creation] section for a detailed explanation. After your backend server handles the order creation, it responds to your Broker API implementation with updated information. Your Broker API implementation then calls the [`orderUpdate`] method three times. 1. The first call provides the [`PlacedOrder`] object that contains information about the **parent order**. The [status][status-property] of the parent order should be [`Working`]. Other object values must be identical to the data provided within the `placeOrder` method. ```json { "id": "1", "symbol": "NasdaqNM:AAPL", "qty": 100, "side": 1, // Side.Buy "status": 6, // Status.Working "type": 2, // Type.Market "takeProfit": 174.5, "stopLoss": 173.32 } ``` :::info For limit and stop orders, make sure to include the `limitPrice` and `stopPrice` fields respectively in the [`PlacedOrder`] object when updating the parent order using the [`orderUpdate`] method. ::: 2. The second call provides the [`BracketOrder`] object that contains information about the **take-profit order**. The status of the take-profit order should be `Inactive`, and the `qty` and `symbol` values must be identical to the parent order values. The data object must also include: - The `parentId` field with a value **equal** to the `id` value of the parent order. - The `parentType` field, indicating that the parent type is **order**. - The `side` field with a value **opposite** to the `side` value of the parent order. - The `limitPrice` field with a value **equal** to the `takeProfit` value of the parent order. - The `type` value, indicating that the order type is **limit**.

```json { "id": "2", "symbol": "NasdaqNM:AAPL", "qty": 100, "parentId": "1", "parentType": 1, // ParentType.Order "side": -1, // Side.Sell "status": 3, // Status.Inactive "type": 1, // Type.Limit "limitPrice": 174.5 } ``` 3. The third call provides the `BracketOrder` object that contains information about the **stop-loss order**. The status of the stop-loss order should be `Inactive`, and the `qty` and `symbol` values must be identical to the parent order values. The data object must also include: - The `parentId` field with a value **equal** to the `id` value of the parent order. - The `parentType` field, indicating that the parent type is **order**. - The `side` field with a value **opposite** to the `side` value of the parent order. - The `stopPrice` field with a value **equal** to the `stopLoss` value of the parent order. - The `type` value, indicating that the order type is **stop**.

```json { "id": "3", "symbol": "NasdaqNM:AAPL", "qty": 100, "parentId": "1", "parentType": 1, // ParentType.Order "side": -1, // Side.Sell "status": 3, // Status.Inactive "type": 3, // Type.Stop "stopPrice": 173.32 } ``` ### Execute parent order Bracket orders are linked to the parent order by the *Order-Sends-Order (OSO)* condition. This means that once the parent order is executed and its status transitions to `Filled`, the bracket order [statuses][status] should change to `Working`. When the parent order is executed, it turns into a position. Therefore, you should update the `parentId` and `parentType` fields in the bracket order objects to be associated with this new parent position. Along with changing the order statuses, change the values of the following fields: - [`parentId`] should be equal to the `id` value of the position that resulted from the execution of the parent order. - [`parentType`] should be changed to `2`, indicating that the parent type is **position**. #### Example Consider the following example: a user has placed a [market order] with two brackets. Following this, your backend server is responsible for executing the order, creating a position, and updating the information within the bracket orders.
Expand to view the diagram illustrating the process of executing parent order.
Your Broker API implementation calls the [`executionUpdate`] and [`positionUpdate`] methods. Refer to the [Execution update] section for a detailed explanation for these methods. Then, your Broker API implementation calls the [`orderUpdate`] method three times to provide the library with updated information. 1. The first call provides updated information about the **parent order**. Its [status] should be `Filled`. ```json { "id": "1", "symbol": "NasdaqNM:AAPL", "qty": 100, "side": 1, // Side.Buy // highlight-next-line "status": 2, // Status.Filled "type": 2, // Type.Market "takeProfit": 174.5, "stopLoss": 173.32 } ``` 2. The second call provides the `BracketOrder` object that contains updated information about the **take-profit order**. The data object must contain the following changed values, while other fields should remain the same: - The `parentId` field with a value **equal** to the `id` value of the position (`NasdaqNM:AAPL` in this example). - The `parentType` field, indicating that the parent type is **position**. - The `status` value, indicating that the order status is **working**.

```json { "id": "2", "symbol": "NasdaqNM:AAPL", "qty": 100, // highlight-start "parentId": "NasdaqNM:AAPL", "parentType": 2, // ParentType.Position "status": 6, // Status.Working // highlight-end "side": -1, // Side.Sell "type": 1, // Type.Limit "limitPrice": 174.5 } ``` 3. The third call provides the `BracketOrder` object that contains information about the **stop-loss order**. The data object must contain the following changed values, while other fields should remain the same: - The `parentId` field with a value **equal** to the `id` value of the position. - The `parentType` field, indicating that the parent type is **position**. - The `status` value, indicating that the order status is **working**.

```json { "id": "3", "symbol": "NasdaqNM:AAPL", "qty": 100, // highlight-start "parentId": "NasdaqNM:AAPL", "parentType": 2, // ParentType.Position "status": 6, // Status.Working // highlight-end "side": -1, // Side.Sell "type": 3, // Type.Stop "stopPrice": 173.32 } ``` :::tip To keep the UI data up-to-date, you should constantly provide updates of users' entity and P&L values whenever changes occur. Refer to the [Equity update] section for more information. ::: ## Position brackets To enable adding position brackets in the UI, set the [`supportPositionBrackets`] or [`supportIndividualPositionBrackets`] flag to `true`. This activates buttons for creating brackets on the chart and enables the *Protect position* button. For more details on configuration flags, check the [Trading features configuration] section. ### Add position brackets By default, users can add two brackets at the same time or only one of them. However, you can set the [`supportOnlyPairPositionBrackets`] flag to `true`, so users can add two brackets together only. When users add brackets to the existing position, the library calls the [`editPositionBrackets`] method. In this method, the library provides the `stopLoss` and `takeProfit` fields. After that, the library expects you to call the [`positionUpdate`] method within 10 seconds. Note that the library will return a [timeout issue] if it fails to receive a timely position update. #### Example Consider the following example: the user has an APPL position and decides to place two bracket orders for this position.
Expand to view the diagram illustrating the process of adding two bracket orders to the position.
The library calls the [`editPositionBrackets`] method, providing the `stopLoss` and `takeProfit` fields. You should implement this method within your Broker API implementation and handle the user's request to add bracket orders. Note that the position update and order creation might be processed on external sources, such as exchanges. However, your backend server is expected to manage this information and provide it in the format required by the library. After your backend server handles the position update and order creation, it responds to your Broker API implementation with updated information. Your Broker API implementation then calls the [`positionUpdate`] and [`orderUpdate`] methods. 1. The `positionUpdate` call updates a [Position] object with the `stopLoss` and `takeProfit` fields. ```json { "id": "NasdaqNM:AAPL", "qty": 100, "side": 1, // Side.Buy "symbol": "NasdaqNM:AAPL", // highlight-start "takeProfit": 174.5, "stopLoss": 173.32 // highlight-end } ``` 2. The first `orderUpdate` call provides the `BracketOrder` object that contains information about the **take-profit order**. The status of the take-profit order should be `Working`, and the `qty` and `symbol` values must be identical to the parent position values. The data object must also include: - The `parentId` field with a value **equal** to the `id` value of the parent position. - The `parentType` field, indicating that the parent type is **position**. - The `side` field with a value **opposite** to the `side` value of the parent position. - The `limitPrice` field with a value **equal** to the `takeProfit` value of the parent position. - The `type` value, indicating that the order type is **limit**.

```json { "symbol": "NasdaqNM:AAPL", "qty": 100, "id": "2", "parentId": "NasdaqNM:AAPL", "parentType": 2, // ParentType.Position "side": -1, // Side.Sell "status": 6, // Status.Working "type": 1, // Type.Limit "limitPrice": 174.5 } ``` 3. The second `orderUpdate` call provides the `BracketOrder` object that contains information about the **stop-loss order**. The status of the stop-loss order should be `Working`, and the `qty` and `symbol` values must be identical to the parent position values. The data object must also include: - The `parentId` field with a value **equal** to the `id` value of the parent position. - The `parentType` field, indicating that the parent type is **position**. - The `side` field with a value **opposite** to the `side` value of the parent position. - The `stopPrice` field with a value **equal** to the `stopLoss` value of the parent position. - The `type` value, indicating that the order type is **stop**.

```json { "symbol": "NasdaqNM:AAPL", "qty": 100, "id": "3", "parentId": "NasdaqNM:AAPL", "parentType": 2, // ParentType.Position "side": -1, // Side.Sell "status": 6, // Status.Working "type": 3, // Type.Stop "stopPrice": 173.32 } ``` ### Execute bracket order Bracket orders are linked to each other by the *One-Cancels-the-Other (OCO)* condition. This means that when one of the bracket orders is executed, the other one gets canceled. In this case, the position linked to the executed bracket order should change its quantity to zero, closing the position. #### Example Consider the following example: the user has a position with two bracket orders. You broker server executes a stop-loss order and returns updated information.
Expand to view the diagram illustrating the process of executing a bracket order.
Your Broker API implementation then calls two consequent [`orderUpdate`] methods and then [`positionUpdate`]. 1. The first `orderUpdate` call provides information about the executed **stop-loss order**. The status of the order should be `Filled`. ```json { "symbol": "NasdaqNM:AAPL", "qty": 100, "id": "3", "parentId": "NasdaqNM:AAPL", "parentType": 2, // ParentType.Position "side": -1, // Side.Sell // highlight-next-line "status": 2, // Status.Filled "type": 3, // Type.Stop "stopPrice": 173.32 } ``` 2. The second `orderUpdate` call provides information about the canceled **stop-loss order**. The status of the order should be `Canceled`. ```json { "symbol": "NasdaqNM:AAPL", "qty": 100, "id": "3", "parentId": "NasdaqNM:AAPL", "parentType": 2, // ParentType.Position "side": -1, // Side.Sell // highlight-next-line "status": 1, // Status.Canceled "type": 1, // Type.Limit "limitPrice": 174.5 } ``` 3. The `positionUpdate` call changes the `qty` property to `0`. ```json { "id": "NasdaqNM:AAPL", // highlight-next-line "qty": 0, "side": 1, // Side.Buy "symbol": "NasdaqNM:AAPL", "takeProfit": 174.5, "stopLoss": 173.32 } ``` [Core concepts]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts [Equity update]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#3-equity-update [Execution update]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#2-execution-update [limit order]: https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#limit-order [market order]: https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#market-order [Order creation]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#1-order-creation [Position]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Position [status]: https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.OrderStatus [status-property]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PlacedOrder#status [stop-loss]: https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#stop-loss-order [stop orders]: https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#stop-order [take-profit]: https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#take-profit-order [timeout issue]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue [Trading features configuration]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-features-configuration [`BracketOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BracketOrder [`editPositionBrackets`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#editpositionbrackets [`executionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#executionupdate [`limitPrice`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PreOrder#limitprice [`orderUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#orderupdate [`parentId`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BracketOrder#parentid [`parentType`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BracketOrder#parenttype [`placeOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#placeorder [`PlacedOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PlacedOrder [`positionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#positionupdate [`PreOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PreOrder [`stopLoss`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PreOrder#stoploss [`stopPrice`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PreOrder#stopprice [`supportIndividualPositionBrackets`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportindividualpositionbrackets [`supportOnlyPairPositionBrackets`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportindividualpositionbrackets [`supportOrderBrackets`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportorderbrackets [`supportPositionBrackets`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpositionbrackets [`takeProfit`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PreOrder#takeprofit [`Working`]: https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.OrderStatus#working URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders ======================================================================================================= # Orders ## Overview An **order** is a request to buy or sell a financial instrument at a specified price and quantity. In the UI, users can place orders via the [Order Ticket]. When the chart is initially loaded, the library calls the [`orders`] method from the [Broker API] implementation. As a result, your implementation should return either a [`PlacedOrder`] or [`BracketOrder`] object. The object should contain data about orders that a user already had before the chart was created. You can refer to the [step-by-step example] and the [Bracket orders] article to learn how these objects should be used. All user's orders are displayed in the *[Account Manager] → Orders* page. The Orders page in the Account Manager ## Order types Order types allow users to place orders according to their specific strategies and risk tolerance. The library supports four order types: - **Market order** is an order to buy or sell a financial instrument at the current market price. This order type guarantees immediate execution but does not guarantee a specific price. - **Limit order** is an order to buy or sell a financial instrument when a given or better price is reached. This order type guarantees a specific price but does not guarantee immediate execution. - **Stop order** is an order to buy or sell a financial instrument at the market price as soon as it reaches a certain level. - **Stop-limit order** is an order that combines a stop price and a limit price. You can configure which types you want to support. Refer to [Configure order types] for more information. ## Bracket orders Trading Platform supports creating bracket orders for positions. A **bracket order** is an order that helps users limit their losses and secure their profits by bracketing positions with two opposing stop-loss and take-profit orders. - **Stop-loss order** is a type of order designed to limit losses by automatically closing a position at a given price when it moves unfavorably. - **Take-profit order** is a type of limit order that closes a position at a specific price to secure a profit. Refer to [Bracket orders] for more information. ## Order statuses When an order is placed, it enters the execution process. In this process, orders have statuses that can be divided into two groups: - **Transitional** - Placing: an order is registered by the broker, but the exchange has not confirmed the status yet. - Working: an order is created and approved by the exchange but not executed yet. - Inactive: an order is in the system, but not at work. Applied to bracket orders. - **Final** - Filled: an order is executed. - Canceled: an order is canceled by a user. - Rejected: an order is rejected for some reason, for example, the exchange rejected the order. Note that the order status can only change from transitional to final, not vice versa. Refer to a [step-by-step example] to see the whole order process: from placement to execution. [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [Bracket orders]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/brackets [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [Configure order types]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket#configure-order-types [Order Ticket]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket [step-by-step example]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#how-components-work-together [`BracketOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BracketOrder [`orders`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#orders [`PlacedOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PlacedOrder URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions ========================================================================================================== # Positions ## Overview A **position** is the amount of a financial instrument held by an investor. A position is always a result of the executed [order]. In the library, positions can be categorized into two types: - **Regular positions**. These are positions that are aggregated regardless of the position side, whether [long] or [short]. With regular positions, each symbol can have only one position. All user actions, such as buying or selling, result in either an increase or decrease in the position's quantity. For example, if a user buys 100 shares of a stock and later sells 50 shares, their position would be 50 shares. - **Individual positions**. These positions are displayed based on the position side, meaning that long and short positions are treated separately. Individual positions are used in the context of [position netting](#position-netting), where all individual positions are aggregated to calculate a single net position for a particular symbol. For example, a user might have two individual positions for the same symbol: a long position of 100 shares and a short position of 50 shares. In this case, the net position would be 50 shares long. :::tip Before continuing with this article, we recommend reading [Core concepts] and [Trading features configuration] articles for a better understanding. ::: ## Handle and display regular positions When the chart is initially loaded, the library calls the [`positions`] method from your [Broker API] implementation. Your implementation should return an array of [`Position`] objects, containing data about the positions a user already held before the chart was created. To update the library with any added or changed positions, your Broker API implementation should call the [`positionUpdate`] method on the Trading Host. :::caution You may encounter a [timeout issue] if the library fails to receive timely updates through `positionUpdate`. ::: User positions are displayed as follows: - On the chart, as a line based on the [`avgPrice`] value of the [`Position`] object. - On the *Account Manager → Positions* page. For more information, refer to the [Orders and Positions] section. ## Handle multiple positions for one symbol The library supports two options for handling multiple positions for the same symbol: [position netting](#position-netting) and [multiposition](#multiposition). Each option offers a different way of managing and displaying positions in the interface. ### Position netting **Position netting** aggregates multiple individual positions for one symbol into a single net position. For example, a user might have two individual positions for the same symbol: a long position of 100 shares and a short position of 50 shares. In this case, the net position would be 50 shares long. To enable position netting, use the [`supportPositionNetting`] flag. Once activated, this flag adds two new pages to the [Account Manager] within *Positions*: *Individual Positions* and *Net Positions*. Note that the number on the *Positions* tab represents only the total count of net positions. Individual Positions and Net Positions pages in the Account Manager Additionally, the library starts to operate with the following methods in the [Broker API]: - [`individualPositions`] for handling individual positions - [`positions`] for handling net positions Your implementation should return arrays of [`IndividualPosition`] and [`Position`] objects, depending on the method the library calls. These objects should contain data about the positions a user already held before the chart was created. To update the library with any added or changed individual/net positions, your Broker API implementation should call the [`individualPositionUpdate`]/[`positionUpdate`] methods on the Trading Host. :::caution You may encounter a [timeout issue] if the library fails to receive timely updates through `individualPositionUpdate`/`positionUpdate`. ::: ### Multiposition Alternatively, the **multiposition** option allows displaying multiple positions for the same symbol without aggregating them into a net position. To enable multiposition, set the [`supportMultiposition`] flag to `true`. Unlike [position netting](#position-netting), this flag does not affect how positions are calculated but affects how they are displayed in the interface. The library operates with the [Broker API] methods the same way as described in the [Handle and display regular positions](#handle-and-display-regular-positions) section. ## Close positions The library supports two ways to close positions based on the value of the [`supportClosePosition`]/[`supportCloseIndividualPosition`] flag. - Default behavior (`false`) — positions are closed using [market orders] of the opposite side. The library calls the [`placeOrder`] method, passing the [`isClose`] property set to `true` in the [`PreOrder`] object. - Custom logic (`true`) — you can implement custom logic for closing positions. In this case, the library calls the [`closePosition`]/[`closeIndividualPosition`] method from the Broker API. :::info The library expects you to call the [`positionUpdate`] method whenever there is a new position added or existing one changed. This call is confirmation to the library that your backend server received and handled the request. Otherwise, the library will return a [timeout issue]. ::: ### Partial closing Partial position closing allows users to close part of a position while keeping the remainder open. When a user clicks the close button for a position, a dialog appears, allowing the user to specify the number of shares to close. For example, if the position size is 10, the user can choose any value between 1 and 10. The position is then updated to reflect the remaining number of shares. To enable partial position closing, set the [`supportPartialClosePosition`]/[`supportPartialCloseIndividualPosition`] flag to `true`. The library then handles the closing based on the value of the [`supportClosePosition`]/[`supportCloseIndividualPosition`] flag: - If `false`, the library calls the [`placeOrder`] method, passing the specified quantity in the [`PreOrder`] object. - If `true`, the library calls the [`closePosition`]/[`closeIndividualPosition`] method, passing the `amount` parameter. ## Reverse positions The library supports the reverse option that allows users to quickly switch a position from long to short and vice versa. To enable this option in the UI, set the [`supportReversePosition`] flag to `true`. Consider an example. A user has a long position in AAPL for 100 shares. When the user clicks *Reverse*, the position turns into a short one, while other position parameters remain the same. Users can reverse positions in three ways: - Click the *Reverse Position* button on the chart. ![Reverse button on the chart](reverse-button-chart.png) - Click the *Reverse* button in the [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) widget. - Right-click the position in the [Account Manager] and select *Reverse Position*. A reverse request can be handled in the following ways: - [Default reversal](#default-reversal) — the library handles reversing. - [Native reversal](#native-reversal) — you handle reversing on your backend side. ### Default reversal The library includes a built-in mechanism for processing reversal. This mechanism is used by default when the [`supportReversePosition`] flag is `true`, unless you explicitly enable the [native reversal](#native-reversal). When a user requests to reverse a position, the library calls the [`placeOrder`] method to close the original position and place a new market order with the following parameters: - [`isClose`] — `true`, meaning that the original position should be closed. - [`side`] — the opposite side to the original position. - [`qty`] — the number of units in the original position multiplied by 2. For example, a user requests to reverse a long position in AAPL for 100 shares. In this case, the library places an order to sell 200 shares of AAPL. As a result, the user will have a short position in AAPL for 100 shares. :::caution Note that the library cannot handle reversing of [multiple positions](#multiposition). In this case, you need to implement the [native reversal](#native-reversal) on your backend side. Otherwise, the following issue occurs: *Cannot reverse position on multiposition account*. ::: ### Native reversal Native reversal allows you to implement a custom reversing mechanism, depending on your specific requirements. For example, you can handle different scenarios, such as the reversal of [multiple positions](#multiposition). To enable the native reversal, set the [`supportReversePosition`] and [`supportNativeReversePosition`] flags to `true`. On your backend side, you should implement the [`reversePosition`] method that is called when a user requests to reverse a position. ## Add brackets **Bracket orders** (brackets) are orders that protect positions. In other words, brackets help users limit their losses and secure their profits by bracketing positions with either one or two opposing stop-loss and take-profit orders. Refer to [Bracket orders] for more information. [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [Bracket orders]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/brackets [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [Core concepts]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts [long]: https://www.investopedia.com/terms/l/long.asp [market orders]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders#order-types [order]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders [Orders and Positions]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager#orders-and-positions [short]: https://www.investopedia.com/terms/s/short.asp [timeout issue]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue [Trading features configuration]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-features-configuration [`avgPrice`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Position#avgprice [`closeIndividualPosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#closeindividualposition [`closePosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#closeposition [`IndividualPosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IndividualPosition [`individualPositions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#individualpositions [`individualPositionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#individualpositionupdate [`isClose`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PreOrder#isclose [`qty`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PreOrder#qty [`placeOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#placeorder [`Position`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Position [`positions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#positions [`positionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#positionupdate [`PreOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PreOrder [`side`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PreOrder#side [`supportCloseIndividualPosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportcloseindividualposition [`supportClosePosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportcloseposition [`supportMultiposition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportmultiposition [`supportNativeReversePosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportnativereverseposition [`supportPartialCloseIndividualPosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpartialcloseindividualposition [`supportPartialClosePosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpartialcloseposition [`supportPositionNetting`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpositionnetting [`supportReversePosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportreverseposition [`reversePosition`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#reverseposition URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/profit-and-loss ================================================================================================================ # Profit and loss ## Overview **Profit and loss** (P&L) values indicate the current profit or loss status of an account or a [position]. P&L values are displayed in the [Account Manager] and on the chart for the related position. You can control how P&L values are calculated using the [`supportPLUpdate`] flag. The default value is `true`. This means you should calculate the P&L value for a position on your backend server and [provide](#provide-pl-values) it to the library. If [`supportPLUpdate`] is set to `false`, the library automatically calculates P&L values as the difference between the current trade and the average position price. However, we recommend using **your own P&L calculations**. This helps avoid any discrepancies between the P&L values of the account and positions due to potential delays. ## Provide P&L values You can provide P&L data to the library using two distinct methods. The method you choose determines which parts of the user interface are updated. :::warning For both methods, the P&L value must be a number representing the **monetary** profit or loss. Do not provide it as ticks or a percentage. This is because the library only uses your value for the *Money* [display mode](#display-modes-and-calculation-logic) and calculates P&L internally for *Ticks* and *Percentage* modes. ::: ### Through position object This approach updates the P&L value on both the chart's position line and in the [Account Manager]. Since the [`Position`] interface extends the [`CustomFields`] interface, you can include a `pl` property as a custom field within the `Position` object. - When first loading positions, call the [`positions`] method. - When a position's data changes, call the [`positionUpdate`] method. ### Through plUpdate method This approach is designed specifically for pushing frequent P&L updates without resending the entire position object. Once calculated P&L, call the [`plUpdate`] method, providing the `pl` parameter. This method updates the P&L value in the [Account Manager] only. It does not affect the P&L displayed on the chart. ## Handling position netting If [position netting] is enabled, the approaches for providing P&L are the same as [described above](#provide-pl-values). Additionally, you need to implement methods related to individual positions: [`individualPositions`], [`individualPositionUpdate`], and [`individualPositionPLUpdate`]. :::info When position netting is enabled, the chart displays P&L for individual positions only. P&L values for net positions are not shown. ::: ## Display modes and calculation logic The library allows users to switch between different P&L display modes: *Money*, *Ticks*, and *Percentage* through *Settings → Positions → Profit & loss*. The library's behavior depends on the user's selected mode. - **Money mode**. The library displays the exact `pl` value that you provide through either of the [methods above](#provide-pl-values). - **Ticks mode**. The library ignores your provided `pl` value. Instead, it automatically calculates the P&L values using its own internal formula: ```js ((currentPrice - avgPrice) / avgPrice) * 100 * sign ``` where: - `currentPrice` is the current bid/ask/last price of the symbol. - `avgPrice` is the [`avgPrice`] value. - `sign` is the [`side`] value. `1` for long (Buy) positions, `-1` for short (Sell) positions. - **Percentage mode**. The library ignores your provided `pl` value. Instead, it automatically calculates the P&L values using its own internal formula: ```js ((currentPrice - avgPrice) * sign) / tickSize ``` where: - `currentPrice` is the current bid/ask/last price of the symbol. - `avgPrice` is the [`avgPrice`] value. - `sign` is the [`side`] value. 1 for long (Buy) positions, -1 for short (Sell) positions. - `tickSize` is the [`pipSize`] property provided in [`symbolInfo`] if available; [`minTick`] otherwise. [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [position]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions [position netting]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions#position-netting [`avgPrice`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Position#avgprice [`CustomFields`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CustomFields [`individualPositions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#individualpositions [`individualPositionPLUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#individualpositionplupdate [`individualPositionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#individualpositionupdate [`minTick`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.InstrumentInfo#mintick [`pipSize`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.InstrumentInfo#pipsize [`plUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#plupdate [`Position`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Position [`positions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#positions [`positionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#positionupdate [`side`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Position#side [`supportPLUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportplupdate [`symbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#symbolinfo URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/quotes ======================================================================================================= # Quotes ## Overview **Quotes** represent real-time price information for financial instruments, including the most recent bid and ask prices, opening and closing prices, price changes, and other market data. In [Trading Platform], quotes are essential for most trading features, including placing and modifying [orders] or managing [positions]. Quotes ensure that users see the most current data in key UI components such as the [Order Ticket] (for accurate order entry), [Watchlist] (for tracking price movements), and [Depth of Market] (for real-time market depth). ## Provide quotes To provide quotes, the [Datafeed API] includes three quote-related methods that must be implemented before the [Broker API]: - [`getQuotes`] — retrieves the latest price information for specified symbols. - [`subscribeQuotes`] — subscribes to real-time price updates for specified symbols. - [`unsubscribeQuotes`] — stops receiving real-time price updates for specified symbols. :::warning Without these methods, the library cannot receive or process quotes, causing issues such as UI [loading delays] or [missing data]. ::: [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api [Depth of Market]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market [missing data]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues#quotes-are-not-displayed-or-refreshed [orders]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders [Order Ticket]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket [positions]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [loading delays]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues#delays-in-trading-platform-ui-elements [Watchlist]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List [`getQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes [`subscribeQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribequotes [`unsubscribeQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#unsubscribequotes URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts ================================================================================================ # Core trading concepts Trading Platform provides the ability to trade right from the chart. Users can manage orders, track positions, monitor their potential profits and losses, and more. In this article, you will learn about the trading components, how they integrate into the chart widget, and how they work together. ## Trading components Trading in Trading Platform is based on three key components: the [Broker API](#broker-api), [Trading Host](#trading-host), and [Datafeed API](#datafeed-api). The diagram below illustrates how these components should be integrated with the library and your backend server. import ThemedImage from '@theme/ThemedImage'; import useBaseUrl from '@docusaurus/useBaseUrl'; ### Broker API The Broker API enables trading functionality in the library by connecting the chart interface to your backend trading logic. This API is used when the library actively requests information or performs actions, for example, placing an order or fetching account details. The Broker API is an object that bridges the library and your backend trading server, handling the exchange of data, such as account information, orders, executions, and positions. You can implement the Broker API through the [`IBrokerTerminal`] interface. ### Trading Host The Trading Host is an API that facilitates communication between the Broker API and the trading-related parts of the library. The Trading Host is used to send updates from your backend to the library that the library didn’t explicitly request but still needs to keep trading information accurate and up to date (for example, order status changes or profit and loss updates). The Trading Host is defined by the [`IBrokerConnectionAdapterHost`] interface and consists of callback-like methods. You should call these methods from your [Broker API](#broker-api) implementation whenever updates occur on your backend. ### Datafeed API The [Datafeed API] provides market data to the library and plays two distinct roles. On the one hand, it is used directly by the library to retrieve standard market data — such as historical bars, symbol information, and resolutions. On the other hand, for trading functionality, its role is to provide **real-time quotes** (bid/ask prices, last price, etc.). [Quotes] are used in most Trading Platform features including the [Order Ticket], [Legend], and widgets, such as [Watchlist], [Details], [News], and [Depth of Market]. In the trading context, the library does not access the Datafeed API directly. Instead, you should call the methods of the [`IDatafeedQuotesApi`] interface within your [Broker API](#broker-api) implementation. ## How to enable trading ### Implement quote methods To use Trading Platform, in addition to the [required] Datafeed API methods, implement the quote-related methods. - [`getQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes) - [`subscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribequotes) - [`unsubscribeQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#unsubscribequotes) ### Connect Broker API To enable trading, you should pass the function that returns a new object of the Broker API implementation to the library. To do this, use the [`broker_factory`] property of the [Widget Constructor]. Note that this function should accept the Trading Host instance as a parameter. In the code sample below, the function assigned to `broker_factory` accepts `tradingHost` parameter, which is an instance of [`IBrokerConnectionAdapterHost`]. This function returns an instance of `BrokerSample` that implements [`IBrokerTerminal`]. ```javascript const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-next-line broker_factory: function(tradingHost: IBrokerConnectionAdapterHost) { return new Brokers.BrokerDemo(tradingHost, datafeed); }, }) ``` ### Implement Broker API methods Implement the methods required for your trading setup through the [`IBrokerTerminal`] interface. Check out our [step-by-step tutorial] on implementing the required methods for basic trading functionality. It’s the fastest way to get started with the Broker API. ## How library gets user's data When the chart is initially loaded, the library requests data from your Broker API implementation through the following methods: - [`orders`] - [`positions`] - [`executions`] - [`individualPositions`] (optional, required if the [`supportPositionNetting`] flag is set to `true`). Using these methods, the library retrieves data about the orders, positions, and executions the user already had before the chart creation. Then, the library gets updates for these orders and positions through the Trading Host methods. Refer to the [next section](#how-components-work-together) for a step-by-step example. ## How components work together To understand how the library, [Broker API](#broker-api), [Trading Host](#trading-host), and your implemented trading logic should work together, consider the following step-by-step example. Suppose a user wants to buy 10 AAPL shares. This user action initiates three consecutive steps: In the subsequent sections, you will delve into each of these steps, finding detailed explanations and sequence diagrams: 1. [Order creation](#1-order-creation) 2. [Execution update](#2-execution-update) 3. [Equity update](#3-equity-update) You can also refer to the diagram that illustrates the entire process, starting from creating the order in the UI until the position is established.
Expand to view the diagram of the entire process.
### 1. Order creation The diagram below illustrates the process of creating an order. 1. The user specifies 10 units of AAPL shares in the [Order Ticket] and clicks the *Buy* button. 2. The library interprets this action as a trigger to notify your Broker API implementation that the user wants to create the order. 3. The library calls the [`placeOrder`] method, passing along the order data. The code sample below shows an example of the data object: ```json { "symbol": "NasdaqNM:AAPL", "type": 2, // OrderType.Market "side": 1, // Side.Buy "qty": 10, "currentQuotes": { "ask": 173.68, "bid": 173.68 }, "customFields": {} } ``` Note that your Broker API implementation should interpret this call as a notification of the user's intent to create the order. 4. Your Broker API implementation responds with [`PlaceOrderResult`]. 5. The library waits for your backend server to create the order within 10 seconds and provide the updated information. Note that the library will return a [timeout issue] if it fails to receive a timely order update. 6. Your Broker API implementation requests your backend server to create the order. 7. Your backend server creates the order and prepares the updated information. 8. Your backend server provides a response to your Broker API implementation with updated information. 9. Your Broker API implementation calls the [`orderUpdate`] method. As a parameter, it sends the [`PlacedOrder`] object to the library. Note that the `qty`, `id`, `symbol`, and `side` properties must be identical to the data provided in step 3 within the `placeOrder` method.
The code sample below shows an example of the `PlacedOrder` object: ```json { "id": "1", "qty": 10, "side": 1, // Side.Buy "status": 6, // OrderStatus.Working "symbol": "NasdaqNM:AAPL", "type": 2 // OrderType.Market } ``` :::info Here, the object has a `status` property that indicates the order's current [status]. Initially, when the order is created but has not been executed, it is assigned the *working* status. Once the order is executed, its status should be updated to *filled*. This will be done [further](#2-execution-update). ::: 10. The Trading Host receives updates and informs the library and the UI that the order has been created. 11. The user sees the new working order in the [Account Manager]. After this, the backend server should [execute the working order](#2-execution-update) and add a new position. ### 2. Execution update At this point, the user can see the new working order in the Account Manager. Following this, your backend server is responsible for executing the order and creating a position. The diagram below illustrates this process. 1. Your backend server executes the order and prepares the updated information. Note that the order execution and update might be processed on external sources, such as exchanges. However, your server is expected to manage this information and provide it in the format required by the library. 2. Your backend server provides a response to your Broker API implementation with updated information. 3. Your Broker API implementation calls the [`executionUpdate`] method. As a parameter, it sends the [`Execution`] object. The code sample below shows an example of this object: ```json { "price": 173.68, "qty": 10, "side": 1, // Side.Buy "symbol": "NasdaqNM:AAPL", "time": 1697032262341 } ``` 4. Your Broker API implementation calls the [`orderUpdate`] method to update the order status to *filled*. As a parameter, your Broker API implementation sends the [`PlacedOrder`] object. The code sample below shows an example of this object: ```json { "id": "1", "qty": 10, "side": 1, // Side.Buy "status": 2, // OrderStatus.Filled "symbol": "NasdaqNM:AAPL", "type": 2, // OrderType.Market } ``` 5. Your Broker API implementation calls the [`positionUpdate`] method to notify the Trading Host that the position is added. As a parameter, it sends the [`Position`] object. The code sample below shows an example of this object: ```json { "id": "NasdaqNM:AAPL", "qty": 10, "side": 1, // Side.Buy "symbol": "NasdaqNM:AAPL", "avgPrice": 173.68 } ``` 6. The Trading Host receives updates and informs the library and the UI that the order has been executed and the position has been added. 7. The user sees a new position of 10 AAPL shares in the Account Manager. After this, your backend server should [update user's equity](#3-equity-update). ### 3. Equity update At this stage, the user sees that the order has been executed and the position has been created. Next, your backend server should update the user's equity and the Profit & Loss (P&L) values for all active positions whenever there is a price change. :::info To keep the UI data up-to-date, you should constantly provide updates of users' entity and P&L values whenever changes occur. ::: The diagram below illustrates the process of updating the equity and P&L values. 1. Your backend server calculates the user's equity and P&L and prepares the updated information. Note that the calculations might be processed on external sources, such as exchanges. However, your server is expected to manage this information and provide it in the format required by the library. 2. Your backend server provides a response to your Broker API implementation with updated information. 3. Your Broker API implementation calls the [`equityUpdate`] method to notify the Trading Host about equity updates. As a parameter, it sends the accurate equity amount, for example, `[10000000]`. 4. Your Broker API implementation calls the [`plUpdate`] method to notify the Trading Host about P&L updates. 5. The Trading Host notifies the library and the UI about updates. 6. The user sees updated equity and P&L values in the Account Manager. At this stage, the user owns the position of 10 AAPL shares. ## Implementation example :::tip If you're new to the Broker API, we recommend beginning with our [step-by-step tutorial]. It walks you through implementing the required methods to get trading components working. ::: You can also reference a more advanced example of the Broker API implementation on GitHub. However, the repository is private and requires you to [get access] first. The [Broker API example][broker-sample] 🔐 includes TypeScript source code, which can serve as a template for your implementation. Note that this example does not establish a connection with an actual broker but simulates order and position management as a mock setup. This implementation is also used on the [Trading Platform demo page] where you can experiment with various trading features. [`broker_factory`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#broker_factory [`equityUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#equityupdate [`Execution`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Execution [`executions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#executions [`executionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#executionupdate [`IBrokerConnectionAdapterHost`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost [`IBrokerTerminal`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal [`IDatafeedQuotesApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedQuotesApi [`individualPositions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#individualpositions [`orders`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#orders [`orderUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#orderupdate [`placeOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#placeorder [`PlacedOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PlacedOrder [`PlaceOrderResult`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PlaceOrderResult [`plUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#plupdate [`Position`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.Position [`positions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#positions [`positionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#positionupdate [`supportPositionNetting`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportpositionnetting [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [broker-sample]: https://github.com/tradingview/trading_platform/tree/master/broker-sample "The repository is private." [Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api [Details]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal#details [Depth of Market]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market [get access]: https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-start#getting-access [legend]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend [News]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news [Order Ticket]: https://www.tradingview.com/charting-library-docs/trading_terminal/order-ticket [quotes]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/quotes [required]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods [status]: https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.OrderStatus [step-by-step tutorial]: https://www.tradingview.com/charting-library-docs/latest/api/implement-broker-api [timeout issue]: https://www.tradingview.com/charting-library-docs/trading_terminal/common-issues#timeout-issue [Trading Platform demo page]: https://trading-terminal.tradingview-widget.com/ [Watchlist]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor#trading-platform-parameters URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-features-configuration =============================================================================================================================== # Trading features configuration You can configure trading features using the [`broker_config`] property of the [Widget Constructor]. This property is primarily used to specify the `configFlags` object, which contains a list of [configuration flags]. Some flags only enable or disable trading elements in the UI, while others activate more advanced features that require corresponding methods to be implemented in the [Broker API]. Consider the [Widget Constructor] with the following properties. ```javascript const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", broker_factory: function(host) { return new Brokers.BrokerDemo(host, datafeed); }, // highlight-start broker_config: { configFlags: { supportEditAmount: false, supportOrdersHistory: true, }, }, // highlight-end }) ``` In the code sample, the [`supportEditAmount`] flag disables the order quantity control in the [Order Ticket] when users modify orders. This flag only affects the UI. The [`supportOrdersHistory`] flag enables the [*History*] page in the Account Manager. On this page, users can see details about all their orders with final [statuses]. However, in addition to enabling `supportOrdersHistory`, you should also do the following: - Implement the [`ordersHistory`] method to provide the library with the user's order history. - Add the [`historyColumns`] property to the [`AccountManagerInfo`] object to define and display data columns. [`accountManagerInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#accountmanagerinfo [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [`broker_config`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#broker_config [configuration flags]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags [*History*]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager#history [`historyColumns`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo#historycolumns [`ordersHistory`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#ordershistory [Order Ticket]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket [statuses]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders#order-statuses [`supportEditAmount`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supporteditamount [`supportOrdersHistory`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.BrokerConfigFlags#supportordershistory [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor#trading-platform-parameters URL: https://www.tradingview.com/charting-library-docs/latest/trading_terminal =============================================================================== # Trading Platform ## Overview [Trading Platform](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )) is a standalone client-side solution that provides trading capabilities. Trading Platform is based on [Advanced Charts](https://www.tradingview.com/charting-library-docs/latest/getting_startedwhat-is-advanced-charts) and contains all its [features](https://www.tradingview.com/charting-library-docs/latest/getting_started/Key-Featuresadvanced-charts-features). If you already use Advanced Charts and want to get started with Trading Platform, refer to the [How to migrate from Advanced Charts](#how-to-migrate-from-advanced-charts) guide. Otherwise, you should refer to [Quick start](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-start) to start the implementation from scratch. import CTAButton from "@site/src/components/landing-page/CTAButton"; ## Trading Platform features ### Multiple-chart layout Users can display up to 8 charts on one layout using the *Select Layout* button on the top toolbar. Charts can be synchronized by a symbol, [interval (resolution)](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution), crosshair, time, and [date range](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossarydate-range). Multiple-chart layout Selecting multiple-chart layouts is enabled by default. If you want to disable this option, add the [`header_layouttoggle`] and [`support_multicharts`] featuresets to the [`disabled_features`] array of the [Widget Constructor]. ### Chart trading Orders, positions, potential income and loss are displayed on the chart in Trading Platform. Users can place orders right from the chart. To enable chart trading, implement the [Broker API]. Then use the [`broker_factory`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#broker_factory) method in [Widget Constructor] to pass the implementation to the library. Chart trading feature ### Depth of Market The Depth of Market (DOM) widget supports frequent data updates and shows the volume for each price. Data is displayed in static mode. This means that the price series is fixed, while the current price moves within, above, or below the designated range. Users can also place orders right from the widget. Refer to [Depth of Market](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/depth-of-market) for more information. DOM widget ### Watchlist The Watchlist widget allows users to track their favorite symbols and switch quickly between the corresponding charts. Users can create multiple lists and sort symbols by their names, price changes, and volumes. Refer to [Watchlist](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/Watch-List) for more information. ![Watchlist widget](https://www.tradingview.com/charting-library-docs/img/watchlist-widget.png) ### Details The Details widget displays a certain symbol's information such as bid/ask prices, trading hours, and a price range during the day. To display the widget, you should enable the [`details`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.WidgetBarParams#details) property in the [`widgetbar`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#widgetbar) settings. The widget requires quote data that you should send using the corresponding methods in the [Datafeed API](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes) or [UDF](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDFquotes). ![Details widget](https://www.tradingview.com/charting-library-docs/img/details-widget.png) ### News The News widget displays news on a certain symbol. You can fetch news using RSS or the library's API. Refer to [News](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/news) for more information. ![News widget](https://www.tradingview.com/charting-library-docs/img/news-widget.png) ### Account Manager The Account Manager (Trading Panel) widget displays information from your broker account, such as orders, positions, an account balance, and more. Users can manage their orders and positions from the widget. You can add custom tabs and tables to the widget. Refer to [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager) for more information. Account Manager ### Advanced Order Ticket The Advanced Order Ticket dialog allows users to place different types of orders, including trailing stop, stop-loss, bracket orders, and more. To open this dialog, users should click the _Trade_ button in [_Account Manager_](#account-manager). Order Ticket You can add custom fields, enable an order preview, or implement your own custom Order Ticket. Refer to [Order Ticket](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket) for more information. ### Buy/Sell buttons and lines The Buy/Sell buttons are displayed next to the [legend](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend). Click the buttons to open [Order Ticket](#advanced-order-ticket) and place orders instantly. Trading Platform also supports bid/ask price lines on the chart. Buy/Sell Buttons :::tip The buttons can be customized with [CSS](https://www.tradingview.com/charting-library-docs/latest/customization/styles/CSS-Color-Themesbuysell-buttons-properties). ::: ### Japanese chart types Trading Platform includes all [chart types](https://www.tradingview.com/charting-library-docs/latest/getting_started/Key-Featureschart-types) available in Advanced Charts and additional types listed below: - Renko - Point-and-Figure - Line Break - Kagi ### Drawing templates Trading Platform allows users to create drawing templates. For more information, refer to the [Drawings](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawingstemplates) article. ### Building seconds bars from ticks Trading Platform can build seconds bars from ticks. For more information, refer to [`build_seconds_from_ticks`]. ## How to migrate from Advanced Charts If you want to migrate from Advanced Charts to Trading Platform, you should replace the `charting_library` folder in your project with the same folder from the [trading_platform](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )) repository. At this point, you will have additional chart types (Renko, Point-and-Figure, Line Break, and Kagi), the synchronized multiple-chart layout, and an empty [Account Manager](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager). ![Default Trading Platform features](https://www.tradingview.com/charting-library-docs/img/tt_default_features.png) To enable the [Watchlist](#watchlist), [Details](#details), [Order Ticket](#advanced-order-ticket), [News](#news), and [Depth of Market](#depth-of-market) widgets, you need to implement the Datafeed API methods related to [trading](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods). You should also enable the corresponding [featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetstrading-platform) or the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructortrading-platform-parameters) parameters. If you want to add [trading capabilities](#chart-trading), you should implement the [Broker API]. The part of the Trading Platform implementation is shown in the [`trading.html`](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )) file. Pay attention that data for the legend is requested in the [`getQuotes`](https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes) method on the **[mobile version](https://www.tradingview.com/charting-library-docs/latest/mobile_specifics) of Trading Platform**. If this method is not implemented, you may see the `N/A` values instead of prices. ## See also For more information on how to integrate Trading Platform, refer to the following articles: - [Core trading concepts]: learn about the trading components, how they integrate into the chart widget, and how they work together. - [Implement Broker API]: follow the step-by-step tutorial that walks you through implementing the required methods to enable basic trading functionality. - [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions): check the Widget Constructor parameters specific to Trading Platform. [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [Core trading concepts]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts [`disabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features [`header_layouttoggle`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#header_layouttoggle [Implement Broker API]: https://www.tradingview.com/charting-library-docs/latest/api/implement-broker-api [`support_multicharts`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#support_multicharts [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor [`build_seconds_from_ticks`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#build_seconds_from_ticks URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/First-Run-Tutorial =========================================================================================== # How to run the library This tutorial describes how to run the library on your machine. You can also watch the video below that demonstrates running the library step-by-step. import YouTubeVideo from '@site/src/components/youtube-embed'; ## Prepare the project 1. Download the library ZIP file from the [Advanced Charts](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )) / [Trading Platform](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )) repository. 2. Create a new folder (`example` in this tutorial). Copy the `charting_library` and `datafeed` folders from the archive to `example`. 3. Create the following `index.html` file in the `example` folder: ```html title="/example/index.html" ``` 4. Add two script references into the `` section: ```html ``` - `charting_library/charting_library.standalone.js` contains the code that creates the chart widget. - `datafeeds/udf/dist/bundle.js` contains a sample datafeed implementation that loads data to the chart. 5. Define the container for the chart in the `` section: ```html
``` 6. To create a chart, you should initialize the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetConstructor) in ``. To do this, configure some basic Widget Constructor parameters: ```html ``` - [`container`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#container) is set to the container ID from the previous step. - [`library_path`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#library_path) specifies a path to additional HTML, JavaScript, and CSS files that allow you to render the chart. In this tutorial, the `charting_library` folder stores these files. - [`datafeed`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#datafeed) is set to the [`UDFCompatibleDatafeed`](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDFconstructor) sample that TradingView provides. ## Run the library 1. Execute the following command in the `example` folder to run the library locally. ```bash # Python 2.x python -m SimpleHTTPServer 9090 # Python 3.x python -m http.server 9090 ``` In this tutorial, the Python [`http.server`](https) module is used. You can use any server/port that you prefer. The tips below explain how to run the most common HTTP servers.
Node.js 1. Install `http-server`. ```shell npm install http-server -g ``` 2. Start `http-server` using the following command in the library folder. ```shell http-server -p 9090 ```
NGINX 1. [Install](https) NGINX. 2. Open the `nginx.conf` file and insert the following code into the `http` section of the file: ```javascript server { listen 9090; server_name localhost; location / { root ABSOLUTE_PATH_TO_THE_TUTORIAL_FOLDER; } } ``` 3. Replace `ABSOLUTE_PATH_TO_THE_TUTORIAL_FOLDER` with the absolute path to the tutorial folder (`example` in this tutorial). 4. Run NGINX.
2. Open `http://localhost:9090/` in your web browser to see the result. ![Running Library](https://www.tradingview.com/charting-library-docs/img/first-run-result.png) ## Complete code ```html title="/example/index.html" TradingView - Advanced Charts
``` ## What's next? In this tutorial, you have set up Widget Constructor and a static chart. To further enhance your implementation, consider following the [How to connect data via Datafeed API] tutorial to learn more about real-time data streaming. Additionally, check out a guide on [enabling debug modes] to help identify potential issues and ensure your application is running smoothly. [How to connect data via Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial [enabling debug modes]: https://www.tradingview.com/charting-library-docs/latest/tutorials/enable-debug-mode URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/add-custom-button-to-top-toolbar ========================================================================================================= # How to add custom button to top toolbar This guide shows how to add buttons to the [top toolbar] using the following methods: - `createDropdown` — creates a [dropdown menu](#add-a-dropdown-button). - `createButton` — creates a [customizable button](#add-a-custom-button). ## Before you start Consider taking the following steps before proceeding with the guide: 1. Set up the Widget Constructor and run the library. Refer to the [First run] tutorial for more information. 2. Connect data to the library. Refer to the [Connecting data] tutorial for more information. ## Add a dropdown button 1. Call the widget's [`headerReady`] method that ensures the toolbar is fully loaded before adding custom elements. The method returns a promise that will be resolved once the chart’s top toolbar is available for customization. ```js widget.headerReady().then(function () {}); ``` 2. Use the widget's [`createDropdown`] method to add a dropdown button to the top toolbar. This button will [set a symbol] with a specific resolution to the chart. ```js widget.headerReady().then(function () { var dropdown = widget.createDropdown({ title: "Select symbol", tooltip: "Select one of the symbols to load the chart with", items: [ { title: "MSFT (1M)", onSelect: () => { widget.setSymbol("MSFT", "1M"); } }, { title: "IBM (1D)", onSelect: () => { widget.setSymbol("IBM", "1D"); } } ] }); }); ``` ## Add a custom button 1. Call the widget's [`headerReady`] method that ensures the toolbar is fully loaded before adding custom elements. The method returns a promise that will be resolved once the chart’s top toolbar is available for customization. ```js widget.headerReady().then(function () {}); ``` 2. Use the widget's [`createButton`] method to add a button that triggers a confirmation dialog when clicked. The widget's [`showConfirmDialog`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#showconfirmdialog) method displays a dialog box with a title, body text, and two buttons: *Yes* and *No*. ```js widget.headerReady().then(function () { var button = widget.createButton(); button.textContent = "Show dialog"; button.addEventListener("click", function () { widget.showConfirmDialog({ title: "Accept Terms and Conditions", body: "By selecting Yes, you agree to the terms of use. Otherwise, select No to cancel.", callback(result) { result ? console.log("The terms are accepted.") : console.log("The terms are not accepted."); } }); }); }); ``` 3. **(Optional)** If you're a [Trading Platform] user, you can alternatively use the [`showConfirmDialog`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#showconfirmdialog) method within the [`IBrokerConnectionAdapterHost`] interface. 1. Use the widget's [`createButton`] method to add a button that triggers a confirmation dialog when clicked. ```js widget.headerReady().then(function () { var buttonTwo = widget.createButton(); // Create a button buttonTwo.textContent = "Show dialog 2"; // Add the button title buttonTwo.addEventListener("click", function () { window.broker.showDialog(); // Trigger a custom dialog on click }); }); ``` 2. Define the `showDialog` method in the constructor of your [Broker API] class. ```js async showDialog() { const actionConfirmed = await this.host.showConfirmDialog( "Confirm action", // Dialog title [ "This action cannot be undone. Please confirm to continue.", "Otherwise, you may close this dialog to retain the current settings." ], // Dialog content "Confirm", // Text for the button that returns true "Dismiss" // Text for the button that returns false ); if (actionConfirmed) { console.log("Action was confirmed."); } else { console.log("Action was not confirmed."); } } ``` ## What's next? If you want to dive deeper into how to customize the chart, we recommend checking the following documentation articles: - [Customization overview](https://www.tradingview.com/charting-library-docs/latest/customization) - [UI elements overview](https://www.tradingview.com/charting-library-docs/latest/ui_elements) [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [Connecting data]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial [First run]: https://www.tradingview.com/charting-library-docs/latest/tutorials/First-Run-Tutorial [set a symbol]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#setsymbol [top toolbar]: https://www.tradingview.com/charting-library-docs/latest/ui_elements#top-toolbar [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [`createButton`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#createbutton [`createDropdown`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#createdropdown [`headerReady`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#headerready [`IBrokerConnectionAdapterHost`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator/constructor-implementation =========================================================================================================================== # Implement constructor :::tip This article is part of a tutorial about creating a custom indicator. We recommend that you follow the guide from the [start](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator). ::: `CustomIndicator` has the required `constructor` field that you will specify at this part of the tutorial. To do this, assign an ES5 constructor function to `constructor`. The function should contain the `main` method that calculates indicator data. To implement the method, follow the steps below. For a thorough understanding of the constructor implementation, consider the [Constructor](https://www.tradingview.com/charting-library-docs/latest/custom_studies/custom-indicator-constructor) article. ## 1. Handle method arguments The `main` method accepts the following parameters: - [`ctx`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IContext) — context that stores an indicator state. It includes information about the current symbol, resolution, OHLC values of the current bar, and more. - `inputs` — an array of the input parameters' values. Elements in the array are arranged in the same order as [`inputs`](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator/metainfo-implementationinputs) in `metainfo`. Handle the method arguments as follows: ```javascript constructor: function () { this.main = function (ctx, inputs) { this._context = ctx; this._input = inputs; var length = this._input(0); var offset = this._input(2); var smoothingLine = this._input(3); var smoothingLength = this._input(4); // If this._input(1) returns 'close', PineJS.Std.close(this._context) will be called var source = PineJS.Std[this._input(1)](this._context); } } ``` One of the indicator's [input parameters](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator/metainfo-implementationinputs) is _Source_. The parameter specifies certain bar values, such as close or open price, that will be used in the indicator calculations. To get the required values, you should call the corresponding method from [`PineJSStd`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PineJSStd). For example, if the close price is specified as source, call the [`close`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PineJSStd#close) method. ## 2. Call setMinimumAdditionalDepth Calculating any Moving Averages requires extra historical bars. Usually the library can calculate the number of extra bars to request from datafeed. However, in this tutorial, you implement a Smoothing Line which is a Moving Average calculated based on another Moving Average. In this exceptional case, you should manually specify the number of extra bars by calling the [`setMinimumAdditionalDepth`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IContext#setminimumadditionaldepth) method. Call `setMinimumAdditionalDepth` and pass the sum of the _Length_ and _Smoothing Length_ values as a parameter: ```javascript this._context.setMinimumAdditionalDepth(length + smoothingLength); ``` ## 3. Call new_var The library calls the `main` method for each bar of the [main series](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryseries). To access values you get on the previous iterations, you should call the [`new_var`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IContext#new_var) method that creates a special variable. In this tutorial, you need to store the main series to use it as the input to another calculation. To do this, create the `series` variable as follows: ```javascript var series = this._context.new_var(source); ``` ## 4. Calculate data ### For SMA To calculate the SMA values, use the [`sma`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PineJSStd#sma) method. The method returns a number — the SMA value for the current bar. ```javascript var sma = PineJS.Std.sma(series, length, this._context); ``` Additionally, you should store all SMA values to use them in the Smoothing Line calculations. To do this, create the `sma_series` variable with `new_var`: ```javascript var sma_series = this._context.new_var(sma); ``` ### For Smoothing Line The Smoothing Line is a Moving Average calculated based on the [SMA](#for-sma) data. Depending on the type specified in the _Smoothing Line_ input parameter, you should call either `sma`, [`ema`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PineJSStd#ema), or [`wma`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PineJSStd#wma) method to calculate the values: ```javascript var smoothedMA; if (smoothingLine === "EMA") { smoothedMA = PineJS.Std.ema( sma_series, smoothingLength, this._context ); } else if (smoothingLine === "WMA") { smoothedMA = PineJS.Std.wma( sma_series, smoothingLength, this._context ); } else { // if (smoothingLine === "SMA") { smoothedMA = PineJS.Std.sma( sma_series, smoothingLength, this._context ); } ``` ## 5. Return values Return the calculated values for the SMA and Smoothing Line as follows: ```javascript return [ { value: sma, offset: offset }, { value: smoothedMA, offset: offset }, ]; ``` ## Complete code At this stage, you have implemented the constructor function and assigned it to the `constructor` field.
Expand to view the complete code for the constructor. ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... custom_indicators_getter: function(PineJS) { return Promise.resolve([ // Indicator object { constructor: function () { this.main = function (ctx, inputs) { this._context = ctx; this._input = inputs; var length = this._input(0); var offset = this._input(2); var smoothingLine = this._input(3); var smoothingLength = this._input(4); var source = PineJS.Std[this._input(1)](this._context); this._context.setMinimumAdditionalDepth(length + smoothingLength); var series = this._context.new_var(source); var sma = PineJS.Std.sma(series, length, this._context); var sma_series = this._context.new_var(sma); var smoothedMA; if (smoothingLine === "EMA") { smoothedMA = PineJS.Std.ema( sma_series, smoothingLength, this._context ); } else if (smoothingLine === "WMA") { smoothedMA = PineJS.Std.wma( sma_series, smoothingLength, this._context ); } else { // if (smoothingLine === "SMA") { smoothedMA = PineJS.Std.sma( sma_series, smoothingLength, this._context ); } return [ { value: sma, offset: offset }, { value: smoothedMA, offset: offset }, ]; }; }, } ]); }, }); ```
## Tutorial results This was the final step of the custom indicator implementation. You have created a custom indicator and specified its appearance and data.
Expand to view the complete code for the custom indicator. ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... custom_indicators_getter: function(PineJS) { return Promise.resolve([ // Indicator object { name: 'Custom Moving Average', metainfo: { _metainfoVersion: 53, id: "Custom Moving Average@tv-basicstudies-1", description: "Custom Moving Average", shortDescription: "Custom MA", format: { type: "inherit" }, linkedToSeries: true, is_price_study: true, plots: [ { id: "plot_0", type: "line" }, { id: "smoothedMA", type: "line" }, ], defaults: { styles: { plot_0: { linestyle: 0, linewidth: 1, plottype: 0, trackPrice: false, transparency: 0, visible: true, color: "#2196F3", }, smoothedMA: { linestyle: 0, linewidth: 1, plottype: 0, trackPrice: false, transparency: 0, visible: true, color: "#9621F3", }, }, inputs: { length: 9, source: "close", offset: 0, smoothingLine: "SMA", smoothingLength: 9, }, }, styles: { plot_0: { title: "Plot", histogramBase: 0, joinPoints: true }, smoothedMA: { title: "Smoothed MA", histogramBase: 0, joinPoints: false, }, }, inputs: [ { id: "length", name: "Length", defval: 9, type: "integer", min: 1, max: 10000, }, { id: "source", name: "Source", defval: "close", type: "source", options: [ "open", "high", "low", "close", "hl2", "hlc3", "ohlc4", ], }, { id: "offset", name: "Offset", defval: 0, type: "integer", min: -10000, max: 10000, }, { id: "smoothingLine", name: "Smoothing Line", defval: "SMA", type: "text", options: ["SMA", "EMA", "WMA"], }, { id: "smoothingLength", name: "Smoothing Length", defval: 9, type: "integer", min: 1, max: 10000, }, ], }, constructor: function () { this.main = function (ctx, inputs) { this._context = ctx; this._input = inputs; var length = this._input(0); var offset = this._input(2); var smoothingLine = this._input(3); var smoothingLength = this._input(4); var source = PineJS.Std[this._input(1)](this._context); this._context.setMinimumAdditionalDepth(length + smoothingLength); var series = this._context.new_var(source); var sma = PineJS.Std.sma(series, length, this._context); var sma_series = this._context.new_var(sma); var smoothedMA; if (smoothingLine === "EMA") { smoothedMA = PineJS.Std.ema( sma_series, smoothingLength, this._context ); } else if (smoothingLine === "WMA") { smoothedMA = PineJS.Std.wma( sma_series, smoothingLength, this._context ); } else { // if (smoothingLine === "SMA") { smoothedMA = PineJS.Std.sma( sma_series, smoothingLength, this._context ); } return [ { value: sma, offset: offset }, { value: smoothedMA, offset: offset }, ]; }; }, } ]); }, }); ```
If you want to dive deeper into the custom indicators, we recommend checking out the following documentation sections: - [Custom indicators](https://www.tradingview.com/charting-library-docs/latest/custom_studies) - [Custom indicators examples](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Custom-Studies-Examples) URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator ================================================================================================ # How to create a custom indicator In this tutorial we will create a [custom indicator](https://www.tradingview.com/charting-library-docs/latest/custom_studies) that displays a [Simple Moving Average (SMA)] and a Smoothing Line. The line represents either SMA, [Exponential Moving Average (EMA)], or [Weighted Moving Average (WMA)] calculated based on the existing SMA. After completing the tutorial, you will learn how to add a custom indicator to the library, specify the indicator look and feel, and implement data calculations. ## Before you start Consider taking the following steps before proceeding with the tutorial: 1. Set up the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) and run the library. Refer to the [First run](https://www.tradingview.com/charting-library-docs/latest/tutorials/First-Run-Tutorial) tutorial for more information. 2. Connect data to the library. Refer to the [Connecting data](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial) tutorial for more information. ## Tutorial structure The tutorial is divided into three parts: 1. [Add a custom indicator to the library](#add-a-custom-indicator-to-the-library) 2. [Implement metainfo](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator/metainfo-implementation) 3. [Implement constructor](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator/constructor-implementation) :::tip Tips - At the end of each part, you will find the complete code blocks related to a specific step. - Refer to the CodePen example above to see the complete tutorial code right away. ::: ## Add a custom indicator to the library To add a custom indicator to the library, specify a function that returns a Promise object and assign this function to the [`custom_indicators_getter`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_indicators_getter) property in the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor). The Promise object should be resolved with an array of [`CustomIndicator`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CustomIndicator) instances. In this tutorial, only one custom indicator will be created, therefore, the array contains one element. `CustomIndicator` is an interface that you should implement to provide information on the indicator. The interface contains the following required fields: - `name`: an indicator's internal name that is not visible in the UI. This name should be unique. - `metainfo`: the field that describes how the indicator looks like. - `constructor`: the field that contains data calculations. At this stage of the tutorial, you should adjust the `name` filed only. ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... custom_indicators_getter: function(PineJS) { return Promise.resolve([ // Indicator object { name: 'Custom Moving Average', metainfo: { // ... }, constructor: function() { // ... } } ]); }, }); ``` In the next steps, you will specify the `metainfo` and `constructor` fields. [Simple Moving Average (SMA)]: https://www.tradingview.com/support/solutions/43000696841-simple-moving-average/ [Exponential Moving Average (EMA)]: https://www.tradingview.com/support/solutions/43000592270-exponential-moving-average/ [Weighted Moving Average (WMA)]: https://www.tradingview.com/support/solutions/43000594680-weighted-moving-average/ URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator/metainfo-implementation ======================================================================================================================== # Implement metainfo :::tip This article is part of a tutorial about creating a custom indicator. We recommend that you follow the guide from the [start](https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-indicator). ::: [`CustomIndicator`] has the required `metainfo` field that you will specify at this part of the tutorial. To do this, create a [`StudyMetaInfo`] object that contains indicator metadata and assign this object to `metainfo`. For a thorough understanding of the `StudyMetaInfo` implementation, consider the [Metainfo](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo) article. ## 1. Specify service information Add [service information](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfoservice-information) required for any custom indicator. The code sample below specifies the [`_metainfoVersion`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfo_metainfoversion) and [`id`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfoid) properties. ```javascript metainfo: { _metainfoVersion: 53, id: "Custom Moving Average@tv-basicstudies-1", // ... } ``` ## 2. Specify indicator name Specify the indicator name that will be displayed in the _Indicators_ dialog and the [_Legend_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend). To do this, use the [`description`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfodescription) and [`shortDescription`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfoshortdescription) properties, respectively. ```javascript metainfo: { // ... description: "Custom Moving Average", // Name in the Indicators dialog shortDescription: "Custom MA", // Name in the Legend } ``` ## 3. Position on the chart _Custom Moving Average_ should be displayed on the same pane with the [source symbol] and remain attached to this symbol. Therefore, you should configure the [`is_price_study`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfois_price_study) and [`linkedToSeries`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfolinkedtoseries) properties as follows: ```javascript metainfo: { // ... is_price_study: true, // Display on the same pane with symbol linkedToSeries: true, // Attach indicator to the symbol } ``` :::tip If an indicator is attached to the symbol, users cannot move the symbol to another pane without the indicator. ::: ## 4. Specify visual representation Each indicator is represented with visual elements such as [plots](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryplot), [bands](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfobands) (horizontal lines), and filled (color) [areas](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfofilledareas). In this tutorial, the _Custom Moving Average_ indicator will be represented with two plots. To implement the plots and specify their appearance, adjust the properties below. ### plots Define two plots in [`plots`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfoplots) as follows: ```javascript metainfo: { // ... plots: [ { id: "plot_0", type: "line" }, // Simple Moving Average { id: "smoothedMA", type: "line" }, // Smoothing Line ], } ``` The `plots` property contains two [`StudyLinePlotInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyLinePlotInfo) objects with the following parameters: - `id` that is used to refer to the plot - `type` that specifies the plot form ### styles Next, use the [`styles`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfostyles) property to specify appearance settings for each plot defined in [`plots`](#plots). The `styles` property should contain a [`MappedObject`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.MappedObject). In this object, `key` is a certain plot's `id`, and `TValue` is a [`StudyStylesInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyStylesInfo) object. In `StudyStylesInfo`, specify basic appearance settings that are initialized once and cannot be changed by users, for example, the plot's name in the _Styles_ tab. Note that users can change a line type in the UI, for example, from `Line` to `Histogram`. Therefore, you should specify `StudyStylesInfo` properties related to other line types if necessary. ```javascript metainfo: { // ... styles: { plot_0: { title: "Plot", // Name in the Styles tab histogramBase: 0, // Histogram base level joinPoints: false // Whether join points when the plot type is `Circles` or `Cross` }, smoothedMA: { title: "Smoothed MA", histogramBase: 0, joinPoints: false, }, }, } ``` Styles tab ### Style defaults All default indicator settings should be stored in a [`StudyDefaults`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyDefaults) object. You should assign this object to [`defaults`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfodefaults). To provide default appearance settings for each plot defined in [`plots`](#plots), use the `styles` property within `StudyDefaults`. This property should contain a [`MappedObject`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.MappedObject). In this object, `key` is a certain plot's `id`, and `TValue` is a [`StudyLinePlotPreferences`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyLinePlotPreferences) object. In `StudyLinePlotPreferences`, specify default appearance settings, for example, a line color and width. ```javascript metainfo: { // ... defaults: { styles: { plot_0: { linestyle: 0, // LineStyle.Solid linewidth: 1, plottype: 0, // LineStudyPlotStyle.Line trackPrice: false, // Hide the price line transparency: 0, visible: true, color: "#2196F3", }, smoothedMA: { linestyle: 0, linewidth: 1, plottype: 0, trackPrice: false, transparency: 0, visible: true, color: "#9621F3", }, }, }, } ``` Users can change these appearance settings in the _Styles_ tab. Styles tab ## 5. Specify data Next, you should specify data that the indicator uses. ### Data format Depending on the indicator data, the [_Price Scale_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale) displays price, volume, or percent values. You can specify the indicator's data type using the [`format`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfoformat) property. In this tutorial, _Custom Moving Average_ has the same format as the [source symbol]. Therefore, `format` is set to `inherit`. ```javascript metainfo: { // ... format: { type: "inherit" }, } ``` ### inputs You can allow users to adjust some indicator parameters such as a [source symbol] or time period. To do this, specify input parameters that users can change in the _Inputs_ tab. The parameter values are used in the indicator calculations. To specify input parameters, assign an array of objects to the [`inputs`](https://www.tradingview.com/charting-library-docs/latest/custom_studies/metainfoinputs) property. Each object should implement a certain interface depending on the parameter type. The table below contains the _Custom Moving Average_ input parameters and the corresponding interfaces. Input parameter | Interface | Description ---------|----------|--------- Length | [`StudyNumericInputInfo`] | A time period that is used in calculating the SMA. Source | [`StudySourceInputInfo`] | Bar values that are used in calculating the SMA. Offset | [`StudyNumericInputInfo`] | A number of bars to shift to the right or left. Smoothing Line | [`StudyTextInputInfo`] | A type of the Smoothing Line. Possible types are: [SMA], [EMA], and [WMA]. Smoothing Length | [`StudyNumericInputInfo`] | A length of the Smoothing Line. All these interfaces have the following properties: - `id` that is used to refer to the input parameter - `name` that specifies the parameter name in the _Inputs_ tab - `type` that specifies the parameter data type - `defval` that specifies the default parameter value Other properties depend on the parameter type. Implement the input parameters as follows: ```javascript metainfo: { // ... inputs: [ { id: "length", name: "Length", // Parameter name in the Inputs tab defval: 9, // 9 bars type: "integer", min: 1, max: 10000, }, { id: "source", name: "Source", defval: "close", // Close price type: "source", options: [ // Options in the drop-down menu "open", "high", "low", "close", "hl2", "hlc3", "ohlc4", ], }, { id: "offset", name: "Offset", defval: 0, type: "integer", min: -10000, max: 10000, }, { id: "smoothingLine", name: "Smoothing Line", defval: "SMA", type: "text", options: ["SMA", "EMA", "WMA"], }, { id: "smoothingLength", name: "Smoothing Length", defval: 9, type: "integer", min: 1, max: 10000, }, ], } ``` Inputs tab ### Input defaults [In Style defaults](#style-defaults), you have created the `StudyDefaults` object and assigned it to `defaults`. To provide default values for each input parameter defined in [`inputs`](#inputs), use the `inputs` property within `StudyDefaults`. This property should contain the `id` properties of all input parameters and the corresponding default values. ```javascript metainfo: { // ... defaults: { styles: { // ... }, // highlight-start inputs: { length: 9, source: "close", offset: 0, smoothingLine: "SMA", smoothingLength: 9, }, // highlight-end }, } ``` ## Complete code At this stage, you have implemented the [`StudyMetaInfo`] object and assigned it to the `metainfo` field.
Expand to view the complete code for the StudyMetaInfo object. ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... custom_indicators_getter: function(PineJS) { return Promise.resolve([ // Indicator object { name: 'Custom Moving Average', metainfo: { _metainfoVersion: 53, id: "Custom Moving Average@tv-basicstudies-1", description: "Custom Moving Average", shortDescription: "Custom MA", format: { type: "inherit" }, linkedToSeries: true, is_price_study: true, plots: [ { id: "plot_0", type: "line" }, { id: "smoothedMA", type: "line" }, ], defaults: { styles: { plot_0: { linestyle: 0, linewidth: 1, plottype: 0, trackPrice: false, transparency: 0, visible: true, color: "#2196F3", }, smoothedMA: { linestyle: 0, linewidth: 1, plottype: 0, trackPrice: false, transparency: 0, visible: true, color: "#9621F3", }, }, inputs: { length: 9, source: "close", offset: 0, smoothingLine: "SMA", smoothingLength: 9, }, }, styles: { plot_0: { title: "Plot", histogramBase: 0, joinPoints: true }, smoothedMA: { title: "Smoothed MA", histogramBase: 0, joinPoints: false, }, }, inputs: [ { id: "length", name: "Length", defval: 9, type: "integer", min: 1, max: 10000, }, { id: "source", name: "Source", defval: "close", type: "source", options: [ "open", "high", "low", "close", "hl2", "hlc3", "ohlc4", ], }, { id: "offset", name: "Offset", defval: 0, type: "integer", min: -10000, max: 10000, }, { id: "smoothingLine", name: "Smoothing Line", defval: "SMA", type: "text", options: ["SMA", "EMA", "WMA"], }, { id: "smoothingLength", name: "Smoothing Length", defval: 9, type: "integer", min: 1, max: 10000, }, ], }, constructor: function() { // ... } } ]); }, }); ```
Next, you will specify the `constructor` field. [`StudyMetaInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#studymetainfo [source symbol]: https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#source-symbol [SMA]: https://www.tradingview.com/support/solutions/43000696841-simple-moving-average/ [EMA]: https://www.tradingview.com/support/solutions/43000592270-exponential-moving-average/ [WMA]: https://www.tradingview.com/support/solutions/43000594680-weighted-moving-average/ [`StudyNumericInputInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyNumericInputInfo [`StudySourceInputInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudySourceInputInfo [`StudyTextInputInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StudyTextInputInfo [`CustomIndicator`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CustomIndicator URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/create-custom-page-in-account-manager ============================================================================================================== # How to create custom page in Account Manager The [Account Manager] (AM) is an interactive widget that displays trading information, such as orders, positions, and account balance. This guide describes how to create a custom page in the AM, populate it with data, and provide dynamic updates. ## Before you start 1. This guide assumes that you are familiar with the [core trading concepts] and have implemented the required methods of the [Broker API]. 2. The example below extends the TradingView's [Broker API implementation] and overrides the default AM implementation. We recommend reviewing the implementation as a prerequisite to following this guide. Since the AM is supported only on larger viewports, it will not be displayed within the iframe below. We recommend clicking the *Edit on CodePen* button to view the full example, where the AM is visible. ## 1. Set up a delegate in constructor Delegates are functions that subscribe to specific events and get triggered when these events occur. In this example, delegates allow custom pages to automatically refresh when there are data changes, ensuring that the AM displays real-time information. Define a delegate in the constructor of the `CustomBroker` class using the [`createDelegate`] method of the [Trading Host]. ```js constructor(host, quotesProvider) { super(host, quotesProvider); // Create a delegate this._customPageChangeDelegate = host.factory.createDelegate(); } ``` ## 2. Initialize the first item In this example, the custom page will have three columns: symbol name and two dynamic text fields. Initialize the first item to be displayed on the page. ```js constructor(host, quotesProvider) { this._customPageData = [ { id: "1", // Item's unique ID symbol: "AAPL", // First column customTextOne: `1 - Example`, // Second column customTextTwo: Math.round(Math.random() * +100), // Third column }, ]; } ``` ## 3. Create a function for data updates The `triggerCustomPageUpdate` method updates the custom page by adding a new data item every 5 seconds. This function triggers the delegate to notify the UI, allowing users to see changes immediately. ```js triggerCustomPageUpdate() { // Generate a new item with a unique ID const newId = this._customPageData.length + 1; const newItem = { id: newId, symbol: "IBM", customTextOne: `${newId} - Example`, customTextTwo: Math.round(Math.random() * +100), }; // Add new data to custom page this._customPageData.push(newItem); // Notify any listeners that the data has changed this._customPageChangeDelegate.fire(newItem); } ``` Then, simulate custom page updates in the constructor of the `CustomBroker` class. ```js constructor(host, quotesProvider) { // ... setInterval(() => { this.triggerCustomPageUpdate(); }, 5000); } ``` ## 4. Define custom page 1. The [`accountManagerInfo`] method returns an [`AccountManagerInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo) object containing the information that will be displayed in the AM. Since this example overrides the default implementation defined in the [Broker API implementation], we will only add a new page to the existing AM configuration. Define the custom page via the [`pages`] property of `AccountManagerInfo`. ```js pages: [ { id: "custom-page", title: "Custom Page", tables: [ // Custom table definition ], }, ]; ``` 2. Define a custom table within the [`tables`] property. This table will be displayed on the custom page. ```js tables: [ { // Listen for data updates // When data changes, changeDelegate will signal the UI to update the table changeDelegate: this._customPageChangeDelegate, columns: [ // Columns definition ], id: "custom-table", title: "Custom Table", // Request table data getData: () => { console.log("getData"); return Promise.resolve(this._customPageData); }, }, ], ``` 3. Define [columns] within the table. The order of column display aligns with the sequence of objects added to the [`columns`] array. The formatter property manages how the values are displayed in the columns. Refer to [Value formatters] for more information. ```js columns: [ // Display symbol name in the first column { id: "symbol", label: "Symbol", formatter: "rowButton", // Custom formatter dataFields: ["symbol"], }, // Display custom data in the second column { id: "customTextColumnOne", label: "Column One", formatter: "text", // StandardFormatterName.Text dataFields: ["customTextOne"], }, // Display custom data in the third column { id: "customTextColumnTwo", label: "Column Two", formatter: "text", dataFields: ["customTextTwo"], }, ], ``` ## 5. Implement chart loading on click To allow users to load a selected symbol onto the chart by clicking its name, you need to make the symbol name clickable. This can be achieved by creating a [custom formatter] using the [`customFormatters`] property. The `rowButton` formatter transforms the symbol name into a button that, when clicked, updates the chart with the selected symbol. ```js customFormatters: [ { name: "rowButton", formatText: () => "", formatElement: ({ values }) => { const [symbol, id] = values; const row = document.createElement("button"); row.innerText = symbol; row.style.borderRadius = "6px"; row.style.padding = "2px 8px"; row.style.border = "none"; row.addEventListener("mouseenter", () => { row.style.backgroundColor = "#2962ff"; row.style.color = "#fff"; }); row.addEventListener("mouseleave", () => { row.style.backgroundColor = "#f0f0f0"; row.style.color = "#000"; }); row.addEventListener("click", (event) => { event.stopPropagation(); window.tvWidget.activeChart().setSymbol(symbol); }); return row; }, }, ], ``` At this point, the AM includes a custom page with a dynamic table. The table displays three columns: one showing symbols and two displaying custom data that update in real time. ## What's next? If you want to dive deeper on how to customize the Account Manager, we recommend checking the following documentation articles: - [Account Manager] - [Multiple accounts] [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [Broker API]: https://www.tradingview.com/charting-library-docs/trading_terminal/trading-concepts/trading-concepts#broker-api [Broker API implementation]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#implementation-example [columns]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager#columns [core trading concepts]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts [custom formatter]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters#custom-formatters [Multiple accounts]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/multiple-accounts [Trading Host]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#trading-host [Value formatters]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/value-formatters [`accountManagerInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#accountmanagerinfo [`columns`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerTable#columns [`createDelegate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterFactory#createdelegate [`customFormatters`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo#customformatters [`pages`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerInfo#pages [`tables`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.AccountManagerPage#tables URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/enable-debug-mode ========================================================================================== # How to enable debug mode This article will guide you through enabling debug mode in the library. This feature provides detailed logs and error messages in the browser's Developer Tools, helping you identify issues and ensure your application runs smoothly. The library offers two debug options: - Logging messages related to [connecting data](#enable-debug-mode-for-data-connection) using the Datafeed API. - Logging messages related to [trading features](#enable-debug-mode-for-trading) in the Trading Platform. ## Enable debug mode for data connection The [Datafeed API] is a set of methods that allow you to connect market data to the library. The debug mode in the Datafeed API is useful for identifying how the library loads, processes, and resolves data. You can also check the number of bars requested versus the number of bars received. You can enable the debug mode in two ways: - Set the [`debug`] property to `true` in the [Widget Constructor]. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-next-line debug: true, }) ``` - Call the [`setDebugMode`] method after the chart is initialized. ```js var widget = window.tvWidget = new TradingView.widget({ /* Widget Constructor properties */}); widget.onChartReady(() => { // highlight-next-line widget.setDebugMode(true); }); ``` Once the debug mode is enabled and you [run your app], you can access the console logs in the Developer Tools of your browser. Below is an example of the generated logs. ``` 2024-08-20T13:36:56.244Z Symbol resolve requested: `AAPL` 2024-08-20T13:36:56.504Z FEED [AAPL|1D]: Processing pending subscribers, count=2 2024-08-20T13:36:56.504Z FEED [AAPL|1D]: Leftmost subscriber requires 329 bars prior 2024-08-20T00:00:00.000Z 2024-08-20T13:36:56.505Z FEED [AAPL|1D]: Requesting data: [2023-05-18T00:00:00.000Z ... 2024-08-21T00:00:00.000Z, 330 bars] 2024-08-20T13:36:56.735Z FEED [AAPL|1D]: Receiving bars: total 330 bars in [2016-11-30T00:00:00.000Z ... 2018-03-27T00:00:00.000Z], requested range: [2023-05-18T00:00:00.000Z ... 2024-08-21T00:00:00.000Z, 330 bars] ``` ## Enable debug mode for trading If you are working with [Trading Platform], you can also enable the debug mode for the trading part of your implementation. This mode allows you to check which methods are triggered based on user actions, what data the library sends, and what it expects to receive. Trading is based on two key components: the [Broker API] and the [Trading Host]. The Broker API acts as a bridge between the library and your backend trading server, transmitting data between them. The Trading Host provides the library with updates that it did not request, but these updates are necessary to display up-to-date information. Therefore, the debug mode in trading offers several options, allowing you to choose which logs you want to see. To enable debug mode, use the [`debug_broker`] property in the [Widget Constructor]. You can set this property to one of the debug levels defined by the [`BrokerDebugMode`] type: - `all`: logs all possible debug messages. - `broker-only`: logs only messages related to the Broker API. - `host-only`: logs only messages related to the Trading Host. - `normal`: logs messages for the Broker API and Trading Host but excludes frequently called methods, such as `connectionStatus`. In the example below, the debug mode enables messages related to the Broker API. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-next-line debug_broker: "broker-only", }) ``` Once the debug mode is enabled and you [run your app], you can access the console logs in the Developer Tools of your browser. Below is an example of the generated logs. ``` 2024-08-22T09:18:12.344Z Broker API | id: 1 | method: placeOrder | CALLED with arguments: [{"symbol":"AAPL","type":2,"qty":100,"side":1,"seenPrice":173.68,"currentQuotes":{"ask":173.68,"bid":173.68},"stopType":0,"customFields":{}},null] 2024-08-22T09:18:12.344Z Broker API | id: 1 | method: placeOrder | RETURNED (async): {} ``` ## What's next? If you plan to connect data, we recommend reading the following articles: - [How to connect data via Datafeed API](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial). Learn how to implement datafeed, display historical data, and stream real-time data via WebSocket. - [Datafeed: common issues](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues). Explore detailed explanations and solutions for the most common issues that you may encounter when implementing the Datafeed API. If you plan to implement trading features in Trading Platform, we recommend reading the following articles: - [Core trading concepts](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts). Learn about the trading components, how they integrate into the chart widget, and how they work together. - [Common Broker API issues](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues). Explore detailed explanations and solutions for the most common issues that you may encounter when implementing the Broker API. [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [`BrokerDebugMode`]: https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#brokerdebugmode [Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api [`debug`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#debug [`debug_broker`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#debug_broker [run your app]: https://www.tradingview.com/charting-library-docs/latest/tutorials/First-Run-Tutorial [`setDebugMode`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#setdebugmode [Trading Host]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#trading-host [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement-broker-api/enable-ui ======================================================================================================= # Enable trading UI ## Overview This is the first part of a two-part tutorial on integrating trading into your platform using the [Broker API]. In this part, you'll focus on enabling the trading UI: implementing the Order Ticket, Account Manager, and *Buy/Sell* buttons. Trading in the Trading Platform relies on two key components: the **Broker API** and the **Trading Host**. The Broker API acts as a bridge between the library and the backend trading server, receiving and transmitting data between them. The Trading Host provides the library with updates that the library didn't request, but which are necessary to display up-to-date information. Your job is to implement: - The Broker API methods, which connect the frontend to your backend logic. - The Trading Host notifications, which keep the library in sync with backend changes. You can learn more about how these components work together in [Core trading concepts]. ## 1. Set up broker in Widget Constructor To enable trading, pass a function to the [`broker_factory`] property of the [Widget Constructor]. This function must return a new instance of your Broker API implementation and accept the [Trading Host] as a parameter. ```ts function initOnReady() { var myDatafeed = new UDFCompatibleDatafeed('https://demo-feed-data.tradingview.com'); (window as any).tvWidget = new widget({ symbol: 'AAPL', interval: '1D' as ResolutionString, container: 'tv_chart_container', // BEWARE: no trailing slash is expected in feed URL datafeed: myDatafeed, library_path: 'trading_platform/charting_library/', locale: 'en', broker_factory: function(host: IBrokerConnectionAdapterHost) { return new BrokerMinimal(host, myDatafeed); }, }); } ``` ## 2. Define broker connection status The library uses the [`connectionStatus`] method to determine if the broker is active. ```ts connectionStatus(): ConnectionStatus { return ConnectionStatus.Connected; } ``` Return [`ConnectionStatus.Connected`] to let users start trading. Without it, the [Account Manager] will keep spinning indefinitely. ![The Account Manager is spinning](https://www.tradingview.com/charting-library-docs/img/spinning-account-manager.png)
Want to support other broker statuses? Manage disconnected or error states on your backend and provide connection updates using [`connectionStatusUpdate`].
## 3. Provide user account metadata Implement [`accountsMetainfo`] to return an array of account objects. You can start with a single hardcoded test account. ```ts async accountsMetainfo(): Promise { return [ { id: '1' as AccountId, name: 'Test account', }, ]; } ```
Want to support multiple accounts? Check out our [Multiple Accounts] guide for implementation tips.
## 4. Set current account Specify which account should be used in the current session using [`currentAccount`]. ```ts currentAccount(): AccountId { return '1' as AccountId; } ``` ## 5. Display Account Manager details The [Account Manager] (AM) is an interactive widget that displays trading information, such as orders and positions. To populate the AM, implement [`accountManagerInfo`]. Otherwise, the AM will be empty and only the *Trade* button will appear. ![Empty Account Manager](https://www.tradingview.com/charting-library-docs/img/empty-account-manager.png) Each AM page is a table where you define columns and the data to be displayed. The columns and values shown below are just examples. You can fully customize the AM structure and data fields to match your product's needs. Refer to [Account Manager] for more information. ```ts accountManagerInfo(): AccountManagerInfo { return { accountTitle: 'Trading Sample', summary: [], orderColumns: [ { label: 'Symbol', formatter: StandardFormatterName.Symbol, id: CommonAccountManagerColumnId.Symbol, dataFields: ['symbol', 'symbol', 'message'], }, { label: 'Side', id: 'side', dataFields: ['side'], formatter: StandardFormatterName.Side, }, { label: 'Type', id: 'type', dataFields: ['type', 'parentId', 'stopType'], formatter: StandardFormatterName.Type, }, { label: 'Qty', alignment: 'right', id: 'qty', dataFields: ['qty'], formatter: StandardFormatterName.FormatQuantity, }, { label: 'Status', id: 'status', dataFields: ['status'], formatter: StandardFormatterName.Status, }, { label: 'Order ID', id: 'id', dataFields: ['id'], }, ], positionColumns: [ { label: 'Symbol', formatter: StandardFormatterName.Symbol, id: CommonAccountManagerColumnId.Symbol, dataFields: ['symbol', 'symbol', 'message'], }, { label: 'Side', id: 'side', dataFields: ['side'], formatter: StandardFormatterName.Side, }, { label: 'Qty', alignment: 'right', id: 'qty', dataFields: ['qty'], formatter: StandardFormatterName.FormatQuantity, }, ], pages: [], }; } ``` The method above implements the [*Positions* and *Orders*] pages. The [*Notifications log*] page appears by default. import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; The Positions page in the Account Manager The Orders page in the Account Manager The Notifications log page in the Account Manager ## 6. Add actions to chart context menu actions The library allows users to interact with the chart via a [context menu] — including placing trades directly from it. To support this, implement the [`chartContextMenuActions`] method. This method renders the *Trade* button in the context menu and populates available actions by calling the [`defaultContextMenuActions`] method of the [Trading Host]. ```ts chartContextMenuActions( context: TradeContext, options?: DefaultContextMenuActionsParams | undefined ): Promise { return this._host.defaultContextMenuActions(context); } ``` ## 7. Enable trading buttons Let the library know that symbols are tradable using the [`isTradable`] method. Returning `true` enables the *Buy/Sell* buttons on the chart. Without this method, trading buttons appear disabled and the [Order Ticket] displays a message saying the symbol is not tradable. ```ts async isTradable(symbol: string): Promise { return Promise.resolve(true); } ``` Note that the buttons still won't show bid/ask prices and the Order Ticket won't open until [`symbolInfo`](#8-return-symbol-information) is implemented. ![Buy/Sell buttons don't display bid/ask prices](https://www.tradingview.com/charting-library-docs/img/buy-sell-buttons-without-price.png) ## 8. Return symbol information Implement the [`symbolInfo`] method to provide detailed instrument data needed for the *Buy/Sell* buttons and [Order Ticket]. :::info This symbol information is different from the [`LibrarySymbolInfo`] used in the [Datafeed API]. ::: The example below returns mock symbol information for demonstration only. You should replace it with real instrument details from your backend. ```ts async symbolInfo(symbol: string): Promise { const mintick = await this._host.getSymbolMinTick(symbol); const pipSize = mintick; // Pip size can differ from minTick const accountCurrencyRate = 1; // Account currency rate const pointValue = 1; // USD value of 1 point of price return { qty: { min: 1, max: 1e12, step: 1, }, pipValue: pipSize * pointValue * accountCurrencyRate || 1, pipSize: pipSize, minTick: mintick, description: '', }; } ``` Once this method is implemented, the *Buy/Sell* buttons show bid/ask prices. ![Buy/Sell buttons display bid/ask prices](https://www.tradingview.com/charting-library-docs/img/buy-sell-buttons-with-price.png) Also, the Order Ticket becomes active — but clicking the *Buy/Sell* buttons still won’t do anything. The library will display a toast message stating that the order is rejected. ![Toast message stating that the order is rejected](https://www.tradingview.com/charting-library-docs/img/broker-api-order-rejected.png) To support placing orders, you’ll also need to implement `placeOrder` and work on [order management] logic. [`accountManagerInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#accountmanagerinfo [`accountsMetainfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#accountsmetainfo [`broker_factory`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TradingTerminalWidgetOptions#broker_factory [`chartContextMenuActions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#chartcontextmenuactions [`connectionStatus`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#connectionstatus [`ConnectionStatus.Connected`]: https://www.tradingview.com/charting-library-docs/latest/api/enums/Charting_Library.ConnectionStatus#connected [`connectionStatusUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#connectionstatusupdate [`currentAccount`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#currentaccount [`defaultContextMenuActions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#defaultcontextmenuactions [`isTradable`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#istradable [`LibrarySymbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo [`symbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#symbolinfo [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [context menu]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu [Core trading concepts]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts [Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api [Multiple Accounts]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager/multiple-accounts [*Notifications log*]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager#notifications-log [order management]: https://www.tradingview.com/charting-library-docs/latest/api/manage-orders [Order Ticket]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket [*Positions* and *Orders*]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager#orders-and-positions [Trading Host]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#trading-host [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement-broker-api ============================================================================================= # Implement Broker API ## Overview This step-by-step tutorial walks you through implementing the **required** methods to enable basic trading functionality using the [Broker API]. By the end of this guide, you'll know how to: - Set up the widget and connect it to your broker implementation. - Make symbols tradable and provide detailed instrument data. - Enable trading buttons, Account Manager, and Order Ticket. - Load and manage orders. This tutorial is split into two parts: 1. [Enable trading UI] — focuses on setting up the UI and activating key trading components like the Order Ticket and Account Manager. 2. [Manage orders] — covers how to store, return, and update orders to make the trading flow functional. :::info This guide focuses on the **bare minimum** needed to get trading components working. Once complete, you’ll have a functional mocked Broker API implementation — ideal for testing UI and workflows before connecting to a real backend. ::: ## Before you start Consider taking the following steps before proceeding with the tutorial: 1. Set up the [Widget Constructor] and run the library. Refer to the [First run] tutorial for more information. 2. Connect data to the library. Refer to the [Connecting data] tutorial for more information. 3. (Optional) Enable [debug logs] for troubleshooting. ## Class scaffold The class used in `broker.ts` provides a skeleton implementation of the [Broker API]. Initially, all methods simply throw error messages — this helps highlight which methods are missing when the library tries to use them. As you follow the tutorial, we’ll gradually replace these errors with basic mock implementations. This allows you to: - Get a functional mock setup. - See which UI components depend on which methods. - Understand how the Broker API interacts with the library step by step.
Click to reveal broker.ts ```ts import { AccountId, AccountManagerInfo, AccountMetainfo, ActionMetaInfo, ConnectionStatus, DefaultContextMenuActionsParams, Execution, IBrokerConnectionAdapterHost, IBrokerTerminal, InstrumentInfo, IsTradableResult, Order, OrderStatus, OrderType, PlacedOrder, PlaceOrderResult, Position, PreOrder, TradeContext, } from '../node_modules/trading_platform/charting_library/charting_library';; import { IDatafeedQuotesApi } from 'trading_platform'; export const enum CommonAccountManagerColumnId { // You should use this column ID if you want to fix the column in the positions and orders tables. Symbol = 'symbol', } export abstract class AbstractBrokerMinimal implements IBrokerTerminal { protected readonly _host: IBrokerConnectionAdapterHost; protected readonly _quotesProvider: IDatafeedQuotesApi; constructor(host: IBrokerConnectionAdapterHost, quotesProvider: IDatafeedQuotesApi) { this._host = host; this._quotesProvider = quotesProvider; } abstract orders(): Promise; abstract positions(): Promise; abstract modifyOrder(order: Order, confirmId?: string): Promise; abstract cancelOrder(orderId: string): Promise; abstract chartContextMenuActions( context: TradeContext, options?: DefaultContextMenuActionsParams ): Promise; abstract isTradable(symbol: string): Promise; abstract connectionStatus(): ConnectionStatus; abstract executions(symbol: string): Promise; abstract symbolInfo(symbol: string): Promise; abstract accountManagerInfo(): AccountManagerInfo; abstract accountsMetainfo(): Promise; abstract currentAccount(): AccountId; abstract placeOrder(order: PreOrder): Promise; } export class BrokerMinimal extends AbstractBrokerMinimal { orders(): Promise { throw new Error('Method `orders` not implemented.'); } positions(): Promise { throw new Error('Method `positions` not implemented.'); } modifyOrder(order: Order, confirmId?: string | undefined): Promise { throw new Error('Method `modifyOrder` not implemented.'); } cancelOrder(orderId: string): Promise { throw new Error('Method `cancelOrder` not implemented.'); } chartContextMenuActions( context: TradeContext, options?: DefaultContextMenuActionsParams | undefined ): Promise { throw new Error('Method `chartContextMenuActions` not implemented.'); } // If not implemented this method will render the Buy/Sell buttons with // a white background + tooltip indicating that the symbol cannot be traded. async isTradable(symbol: string): Promise { throw new Error('Method `isTradable` not implemented.'); } // If this method is not returning a Connected state, Account Manager will present a continuous loading spinner. connectionStatus(): ConnectionStatus { return ConnectionStatus.Connected; } executions(symbol: string): Promise { throw new Error('Method `executions` not implemented.'); } // If this method is not implemented the Buy/Sell buttons in the Legend // will display "..." (3 dots) instead of values returned by quotes. async symbolInfo(symbol: string): Promise { throw new Error('Method `symbolInfo` not implemented.'); } // If this method is not implemented the Account Manager will be empty with just the "Trade" button displayed. accountManagerInfo(): AccountManagerInfo { throw new Error('Method `accountManagerInfo` not implemented.'); } async accountsMetainfo(): Promise { throw new Error('Method `accountsMetainfo` not implemented.'); } currentAccount(): AccountId { throw new Error('Method `currentAccount` not implemented.'); } async placeOrder(order: PreOrder): Promise { throw new Error('Method `placeOrder` not implemented.'); } } ```
[Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [Connecting data]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial [debug logs]: https://www.tradingview.com/charting-library-docs/latest/tutorials/enable-debug-mode#enable-debug-mode-for-trading [Enable trading UI]: https://www.tradingview.com/charting-library-docs/latest/api/enable-ui [First run]: https://www.tradingview.com/charting-library-docs/latest/tutorials/First-Run-Tutorial [Manage orders]: https://www.tradingview.com/charting-library-docs/latest/api/manage-orders [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement-broker-api/manage-orders =========================================================================================================== # Manage orders ## Overview This is the second part of a two-part tutorial on integrating trading into your platform using the [Broker API]. At this point, the trading UI is set up. Users can view Account Manager, open Order Ticket, and click the *Buy/Sell* buttons. But while the interface is ready, no trading logic is in place yet. This section introduces the core of order management: how to handle placing, modifying, and canceling orders. To make that possible, you need to store orders in your implementation and return them when requested. The library itself doesn’t keep any trading state. It expects your code to manage and update order data, then notify the UI through the appropriate methods. ## 1. Store and return orders To allow the library to display [orders][order] — both when the chart loads and during user interaction — you need to store this data locally in your Broker API implementation. The library expects your implementation to return existing orders via the [`orders`] method. This method returns initial data about the user’s trading history, before any new actions are taken. Even in a mock setup, you’ll need to store orders locally and provide access to them when the library asks for it. ```ts // Stores orders indexed by ID private readonly _orderById: SimpleMap = {}; // Returns all existing orders private _orders(): Order[] { return Object.values(this._orderById); } orders(): Promise { return Promise.resolve(this._orders()); } ``` ## 2. Return positions and executions The library also calls [`positions`] and [`executions`] on startup. While this tutorial doesn’t use them, you should define these methods to avoid errors. ```ts positions(): Promise { return Promise.resolve([]); } executions(symbol: string): Promise { return Promise.resolve([]); } ``` You can later extend this logic using the same approach — store items in memory, and return them when needed.
Want to support positions? Check out our [Positions] guide for implementation tips.
## 3. Place orders To support [order] placement from the UI, implement the [`placeOrder`] method. The library calls this method when the user submits a new order, for example, by clicking the *Buy/Sell* button in the [Order Ticket]. ```ts // A counter to generate unique IDs for new orders private _orderIdCounter: number = 1; async placeOrder(order: PreOrder): Promise { const newOrder: PlacedOrder = { id: `${this._orderIdCounter++}`, // ID must be unique limitPrice: order.limitPrice, qty: order.qty, side: order.side || Side.Buy, status: OrderStatus.Working, stopPrice: order.stopPrice, symbol: order.symbol, type: order.type || OrderType.Market, takeProfit: order.takeProfit, stopLoss: order.stopLoss, } // Save the new order in local storage this._orderById[newOrder.id] = newOrder; // Notify the library about the new order so it appears in the UI this._host.orderUpdate(newOrder); return {} } ``` When this method is triggered: 1. Create an order on your backend using the [`PreOrder`] data provided by the library. 2. Assign a **unique ID** and store the order. - Each order must have a unique ID so the library can track, update, and manage it properly. - In this sample, we use a simple counter `_orderIdCounter` that increments with every new order. This approach is subjective. You're free to use any ID generation strategy that fits your backend. However, **uniqueness is mandatory**: the same ID may later be reused to reference the corresponding position once the order is filled. 3. Notify the library by calling [`orderUpdate`] to reflect the new order in the UI. - The library waits up to 10 seconds for updates through the [Trading Host]. If no update is received, the library will return a [timeout issue]. - All trading updates — including orders, positions, or executions — must be delivered via the [Trading Host] methods such as [`orderUpdate`], [`executionUpdate`], and [`positionUpdate`]. The library does not manage internal state. It only reflects what your implementation sends. Once this is done, users will be able to place orders from the UI and see them immediately appear on the chart and in the Account Manager. ![New order appears in the Account Manager](https://www.tradingview.com/charting-library-docs/img/new-order-in-account-manager.png)
Want the breakdown for the order flow? For a step-by-step explanation of the entire order flow, from creating an order to creating a position, see the dedicated article [How components work together].
## 4. Modify orders Implement [`modifyOrder`] to let users modify active orders. Without it, the library will display a toast message stating that it failed to modify the order. ![Toast message stating that the order failed to be modified](https://www.tradingview.com/charting-library-docs/img/broker-api-order-modification-failed.png) Once the method is implemented, order modification becomes enabled in the UI. However, [market orders] cannot be modified by design. ```ts async modifyOrder(order: Order, confirmId?: string | undefined): Promise { // Look up the original order using its ID const originalOrder = this._orderById[order.id]; // If no such order exists, do nothing if (originalOrder === undefined) { return; } const handler = () => { // Apply the modification, for example, updating the quantity originalOrder.qty = order.qty; // Notify the library about the order update so it appears in the UI this._host.orderUpdate(originalOrder); return Promise.resolve(); } return handler(); } ``` When this method is triggered: 1. Update the order details on your backend. 2. After the update is complete, call [`orderUpdate`] to reflect the changes in the UI. The library waits up to 10 seconds for updates through the [Trading Host]. If no update is received, the library will return a [timeout issue]. ## 5. Cancel orders To support canceling orders from the [Account Manager], implement the [`cancelOrder`] method. ```ts cancelOrder(orderId: string): Promise { // Look up the original order using its ID const originalOrder = this._orderById[orderId]; const handler = () => { // Change order status to canceled originalOrder.status = OrderStatus.Canceled; // Notify the library about the order update so it appears in the UI this._host.orderUpdate(originalOrder); return Promise.resolve(); } return handler(); } ``` When this method is triggered: 1. Cancel the order and update its [status] to canceled on your backend. 2. After the update is complete, call [`orderUpdate`] to reflect the changes in the UI. The library waits up to 10 seconds for updates through the [Trading Host]. If no update is received, the library will return a [timeout issue].
Want to understand how order statuses work? [Orders][order] move through different statuses after placement. These can be grouped into: - Transitional statuses: placing, working, inactive. - Final statuses: filled, canceled, rejected. Understanding these is key to accurate order status management. For a step-by-step explanation of the entire order flow, including status changes, see the dedicated article [How components work together].
## Full implementation example You’ve now implemented all required methods the library expects from the Broker API implementation. This covers placing, modifying, and canceling orders.
Click to reveal broker.ts ```ts import { AccountId, AccountManagerInfo, AccountMetainfo, ActionMetaInfo, ConnectionStatus, DefaultContextMenuActionsParams, Execution, IBrokerConnectionAdapterHost, IBrokerTerminal, InstrumentInfo, IsTradableResult, Order, OrderStatus, OrderType, PlacedOrder, PlaceOrderResult, Position, PreOrder, Side, StandardFormatterName, TradeContext, } from '../node_modules/trading_platform/charting_library/charting_library';; interface SimpleMap { [key: string]: TValue; } import { IDatafeedQuotesApi } from 'trading_platform'; export const enum CommonAccountManagerColumnId { /** You should use this column ID if you want to fix the column in the positions and orders tables. */ Symbol = 'symbol', } export abstract class AbstractBrokerMinimal implements IBrokerTerminal { protected readonly _host: IBrokerConnectionAdapterHost; protected readonly _quotesProvider: IDatafeedQuotesApi; constructor(host: IBrokerConnectionAdapterHost, quotesProvider: IDatafeedQuotesApi) { this._host = host; this._quotesProvider = quotesProvider; } abstract orders(): Promise; abstract positions(): Promise; abstract modifyOrder(order: Order, confirmId?: string): Promise; abstract cancelOrder(orderId: string): Promise; abstract chartContextMenuActions( context: TradeContext, options?: DefaultContextMenuActionsParams ): Promise; abstract isTradable(symbol: string): Promise; abstract connectionStatus(): ConnectionStatus; abstract executions(symbol: string): Promise; abstract symbolInfo(symbol: string): Promise; abstract accountManagerInfo(): AccountManagerInfo; abstract accountsMetainfo(): Promise; abstract currentAccount(): AccountId; abstract placeOrder(order: PreOrder): Promise; } export class BrokerMinimal extends AbstractBrokerMinimal { /** Initializes an empty map to store orders indexed by their IDs */ private readonly _orderById: SimpleMap = {}; /** A counter to generate unique IDs for new orders */ private _orderIdCounter: number = 1; /** Retrieves all orders stored in the `_orderById` map and returns an array containing all orders */ private _orders(): Order[] { return Object.values(this._orderById); } orders(): Promise { return Promise.resolve(this._orders()); } positions(): Promise { return Promise.resolve([]); } async modifyOrder(order: Order, confirmId?: string | undefined): Promise { // Look up the original order using its ID const originalOrder = this._orderById[order.id]; // If no such order exists, do nothing if (originalOrder === undefined) { return; } const handler = () => { // Apply the modification, for example, updating the quantity originalOrder.qty = order.qty; // Notify the library about the order update so it appears in the UI this._host.orderUpdate(originalOrder); return Promise.resolve(); } return handler(); } cancelOrder(orderId: string): Promise { // Look up the original order using its ID const order = this._orderById[orderId]; const handler = () => { // Change order status to canceled order.status = OrderStatus.Canceled; // Notify the library about the order update so it appears in the UI this._host.orderUpdate(order); return Promise.resolve(); } return handler(); } chartContextMenuActions( context: TradeContext, options?: DefaultContextMenuActionsParams | undefined ): Promise { return this._host.defaultContextMenuActions(context); } async isTradable(symbol: string): Promise { return Promise.resolve(true); } connectionStatus(): ConnectionStatus { return ConnectionStatus.Connected; } executions(symbol: string): Promise { return Promise.resolve([]); } async symbolInfo(symbol: string): Promise { const mintick = await this._host.getSymbolMinTick(symbol); const pipSize = mintick; // Pip size can differ from minTick const accountCurrencyRate = 1; // Account currency rate const pointValue = 1; // USD value of 1 point of price return { qty: { min: 1, max: 1e12, step: 1, }, pipValue: pipSize * pointValue * accountCurrencyRate || 1, pipSize: pipSize, minTick: mintick, description: '', }; } accountManagerInfo(): AccountManagerInfo { return { accountTitle: 'Trading Sample', summary: [], orderColumns: [ { label: 'Symbol', formatter: StandardFormatterName.Symbol, id: CommonAccountManagerColumnId.Symbol, dataFields: ['symbol', 'symbol', 'message'], }, { label: 'Side', id: 'side', dataFields: ['side'], formatter: StandardFormatterName.Side, }, { label: 'Type', id: 'type', dataFields: ['type', 'parentId', 'stopType'], formatter: StandardFormatterName.Type, }, { label: 'Qty', alignment: 'right', id: 'qty', dataFields: ['qty'], help: 'Size in lots', formatter: StandardFormatterName.FormatQuantity, }, { label: 'Status', id: 'status', dataFields: ['status'], formatter: StandardFormatterName.Status, }, { label: 'Order ID', id: 'id', dataFields: ['id'], }, ], positionColumns: [ { label: 'Symbol', formatter: StandardFormatterName.Symbol, id: CommonAccountManagerColumnId.Symbol, dataFields: ['symbol', 'symbol', 'message'], }, { label: 'Side', id: 'side', dataFields: ['side'], formatter: StandardFormatterName.Side, }, { label: 'Qty', alignment: 'right', id: 'qty', dataFields: ['qty'], help: 'Size in lots', formatter: StandardFormatterName.FormatQuantity, }, ], pages: [], }; } async accountsMetainfo(): Promise { return [ { id: '1' as AccountId, name: 'Test account', }, ]; } currentAccount(): AccountId { return '1' as AccountId; } async placeOrder(order: PreOrder): Promise { const newOrder: PlacedOrder = { id: `${this._orderIdCounter++}`, // ID must be unique limitPrice: order.limitPrice, qty: order.qty, side: order.side || Side.Buy, status: OrderStatus.Working, stopPrice: order.stopPrice, symbol: order.symbol, type: order.type || OrderType.Market, takeProfit: order.takeProfit, stopLoss: order.stopLoss, } // Save the new order in local storage this._orderById[newOrder.id] = newOrder; // Notify the library about the new order so it appears in the UI this._host.orderUpdate(newOrder); return {} } } ```
Similarly, you can extend this logic to support [positions] and executions: track their uniqueness, update their state in real time, and send timely updates to the library when anything changes. Let’s explore what you can do next. [`cancelOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#cancelorder [`executions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#executions [`executionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#executionupdate [`orders`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#orders [`orderUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#orderupdate [`modifyOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#modifyorder [`placeOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#placeorder [`positions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerTerminal#positions [`positionUpdate`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IBrokerConnectionAdapterHost#positionupdate [`PreOrder`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PreOrder [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [How components work together]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#how-components-work-together [market orders]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders#order-types [order]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders [Order Ticket]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/order-ticket [positions]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/positions [status]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/orders#order-statuses [timeout issue]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/common-issues#timeout-issue [Trading Host]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#trading-host URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement-broker-api/next-steps ======================================================================================================== # Next steps import CardLinkList from "@site/src/components/CardLinkList"; You’ve just built a minimal, working [Broker API] implementation using mock data. Here's what you've done: - Connected a broker implementation to the Widget Constructor. - Enabled trading buttons in the UI. - Populated the Account Manager and Order Ticket. - Implemented basic logic for placing, modifying, and canceling mock orders. This setup is enough to see the trading UI in action — but below is what you can explore next. ## Ready to go further? [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement-snapshots-server =================================================================================================== # How to implement a server to host snapshots The library allows users to take chart [snapshots] via buttons located on the top toolbar. Take snapshot menu Snapshots taken through *Copy link*, *Open in new tab*, and *Tweet image* options are stored on your servers. This guide shows how to implement a Node.js server to host [snapshots] generated by the library. By the end of this guide, you'll have a server that: - Sends a POST request with a snapshot. - Saves the snapshot to a local folder. - Returns a URL you can use to access the snapshot later. You can use tools like curl, Postman, or a frontend form to upload the snapshot. ## Before you start Consider taking the following steps before proceeding with the guide: 1. Set up the [Widget Constructor] and run the library. For more information, refer to the [First run] tutorial. 2. Make sure you have installed Node.js and npm (comes with Node.js). 3. Create a new folder and run the following commands. ```bash npm init -y npm install express multer cors ``` 4. Create a JavaScript file that will contain the server code. In this example, assume it's `snapshotserver.js`. ## Create a server ### 1. Import required modules ```js title="snapshotserver.js" // Import Express framework for creating the server const express = require('express'); // Enable Cross-Origin Resource Sharing (CORS) // It allows your server to accept requests from the library const cors = require('cors'); // Middleware for handling file uploads const multer = require('multer'); // Modules for working with the file system const path = require('path'); const fs = require('fs'); ``` ### 2. Initialize app and create uploads folder ```js title="snapshotserver.js" const app = express(); const port = 3001; // `cors()` allows your app to accept requests from anywhere app.use(cors()); // Check if `uploads/` exists // If not, it creates the folder const uploadDir = path.join(__dirname, 'uploads'); if (!fs.existsSync(uploadDir)) { fs.mkdirSync(uploadDir); } ``` ### 3. Configure Multer ```js title="snapshotserver.js" // Configure Multer storage: set destination folder and filename format const storage = multer.diskStorage({ // Set the destination directory for uploaded files destination: (req, file, cb) => cb(null, uploadDir), // Add a timestamp to the original filename to prevent name collisions filename: (req, file, cb) => { const timestamp = Date.now(); cb(null, `${timestamp}-${file.originalname}.png`); }, }); // Accept only image files based on the MIME type const fileFilter = (req, file, cb) => { if (file.mimetype.startsWith('image/')) cb(null, true); else cb(new Error('Only image files are allowed'), false); }; // Create the upload middleware with custom storage and file filter const upload = multer({ storage, fileFilter }); ``` ### 4. Serve uploaded files ```js title="snapshotserver.js" // Serve static files from the uploads directory at the `/uploads` URL path app.use('/uploads', express.static(uploadDir)); ``` This allows users to access uploaded snapshots via a URL like `http://localhost:3001/uploads/`. ### 5. Handle upload endpoint ```js title="snapshotserver.js" // Handle image upload at the `/snapshot` endpoint app.post('/snapshot', upload.single('preparedImage'), (req, res) => { // Return an error if no file was uploaded if (!req.file) { return res.status(400).send('No image uploaded.'); } // Create the public URL for the uploaded snapshot const imageUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`; console.log(`Received image: ${req.file.originalname}`); // Respond with the snapshot URL where snapshot can be accessed res.status(200).send(imageUrl); }); ``` ### 6. Start the server ```js title="snapshotserver.js" app.listen(port, () => { console.log(`Listening at http://localhost:${port}`); }); ``` ## How to use the server Use the following `node` command: ```bash node snapshotserver.js ``` This command outputs the following: ```bash Listening at http://localhost:3001 ``` ## How to test the server Use `curl` to test the server: ```bash curl -i -X POST http://localhost:3001/snapshot \ -F preparedImage=@/path/to/your/image.png ``` Generated output should be: ```bash http://localhost:3001/uploads/1716379138459-image.png ``` At this point, you can open this link in a browser and see the image. ## How to connect the server to the library Once your server is deployed and accessible from the internet, pass its `/snapshot` endpoint to the [`snapshot_url`] property in your [Widget Constructor]. This allows the library to send chart snapshots to your server and receive public image URLs in return. ```javascript title="main.js" const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-next-line snapshot_url: "https://myserver.com/snapshot", }) ``` ## Complete code At this stage, you have implemented a functional server.
Expand to view the complete code for the snapshot server in snapshotserver.js. ```javascript // Import required modules const express = require('express'); const cors = require('cors'); const multer = require('multer'); const path = require('path'); const fs = require('fs'); const app = express(); const port = 3001; // Use CORS to allow requests from the frontend app.use(cors()); // Ensure the uploads directory exists const uploadDir = path.join(__dirname, 'uploads'); if (!fs.existsSync(uploadDir)) { fs.mkdirSync(uploadDir); } // Multer storage config const storage = multer.diskStorage({ destination: (req, file, cb) => cb(null, uploadDir), filename: (req, file, cb) => { const timestamp = Date.now(); cb(null, `${timestamp}-${file.originalname}.png`); }, }); // Accept only image files const fileFilter = (req, file, cb) => { if (file.mimetype.startsWith('image/')) cb(null, true); else cb(new Error('Only image files are allowed'), false); }; const upload = multer({ storage, fileFilter }); // Serve static files from the uploads directory app.use('/uploads', express.static(uploadDir)); // Endpoint to receive `preparedImage` app.post('/snapshot', upload.single('preparedImage'), (req, res) => { if (!req.file) { return res.status(400).send('No image uploaded.'); } const imageUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`; console.log(`Received image: ${req.file.originalname}`); res.status(200).send(imageUrl); // Respond with the image URL }); // Endpoint to receive `image` app.listen(port, () => { console.log(`Listening at http://localhost:${port}`); }); ```
[First run]: https://www.tradingview.com/charting-library-docs/latest/tutorials/First-Run-Tutorial [snapshots]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Snapshots [`snapshot_url`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#snapshot_url [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial/Datafeed-Implementation ============================================================================================================================ # Implement datafeed :::tip This article is part of a tutorial about implementing Datafeed API. We recommend that you follow the guide from the [start]. ::: At this stage, you will know how the Datafeed API works and implement your own datafeed and methods. ## How the datafeed works Datafeed API is a set of methods that you should implement and assign to the [datafeed object] in [Widget Constructor]. The library calls these methods to access and process data and fill the current chart with it. The datafeed returns results using callback functions. Refer to the [Datafeed API] topic for more information. ## Step 1. Create a datafeed mock Create a `datafeed.js` file in `src` and add the following code: ```javascript title="/chart‑project/src/datafeed.js" export default { onReady: (callback) => { console.log('[onReady]: Method call'); }, searchSymbols: (userInput, exchange, symbolType, onResultReadyCallback) => { console.log('[searchSymbols]: Method call'); }, resolveSymbol: (symbolName, onSymbolResolvedCallback, onResolveErrorCallback, extension) => { console.log('[resolveSymbol]: Method call', symbolName); }, getBars: (symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) => { console.log('[getBars]: Method call', symbolInfo); }, subscribeBars: (symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) => { console.log('[subscribeBars]: Method call with subscriberUID:', subscriberUID); }, unsubscribeBars: (subscriberUID) => { console.log('[unsubscribeBars]: Method call with subscriberUID:', subscriberUID); }, }; ``` This code sample represents a datafeed that writes a message to the console when any method is called. Now this is only a mock implementation, but you will implement all the methods in the next steps. ## Step 2. Implement methods ### onReady The [`onReady`] method is the first datafeed method that is called when the chart is initialized. The library uses it to get datafeed configuration such as supported resolutions and exchanges. 1. Add the following [`DatafeedConfiguration`] implementation for the datafeed sample: ```javascript title="/chart‑project/src/datafeed.js" const configurationData = { // Represents the resolutions for bars supported by your datafeed supported_resolutions: ['1D', '1W', '1M'], // The `exchanges` arguments are used for the `searchSymbols` method if a user selects the exchange exchanges: [ { value: 'Bitfinex', name: 'Bitfinex', desc: 'Bitfinex'}, { value: 'Kraken', name: 'Kraken', desc: 'Kraken bitcoin exchange'}, ], // The `symbols_types` arguments are used for the `searchSymbols` method if a user selects this symbol type symbols_types: [ { name: 'crypto', value: 'crypto'} ] }; ``` 2. Call the [`OnReadyCallback`] asynchronously and pass a [`DatafeedConfiguration`] object as a parameter: ```javascript title="/chart‑project/src/datafeed.js" onReady: (callback) => { console.log('[onReady]: Method call'); setTimeout(() => callback(configurationData)); }, ``` ### resolveSymbol The [`resolveSymbol`] method is called once the datafeed is configured. The library uses it to retrieve [symbol information] such as exchange, time zone, price scale, and etc. As mentioned [before], the library does not contain or provide any data. For this reason, this tutorial uses the [CryptoCompare API]. 1. Create a `helpers.js` file for the CryptoCompare API functions and add the following code: ```javascript title="/chart‑project/src/helpers.js" // Your CryptoCompare API key export const apiKey = ""; // Makes requests to CryptoCompare API export async function makeApiRequest(path) { try { const url = new URL(`https://min-api.cryptocompare.com/${path}`); url.searchParams.append('api_key',apiKey) const response = await fetch(url.toString()); return response.json(); } catch (error) { throw new Error(`CryptoCompare request error: ${error.status}`); } } // Generates a symbol ID from a pair of the coins export function generateSymbol(exchange, fromSymbol, toSymbol) { const short = `${fromSymbol}/${toSymbol}`; return { short, }; } ``` At this step, you need a CryptoCompare API key (line 2). If you have not got this key yet, consider the [CryptoCompare documentation]. Also, note that the `makeApiRequest` and `generateSymbol` functions are specific to CryptoCompare API and will be used in `resolveSymbol`. You might not need them when implementing your own datafeed. 2. Import the functions from `helpers.js` into `datafeed.js`: ```javascript title="/chart‑project/src/datafeed.js" import { makeApiRequest, generateSymbol } from './helpers.js'; ``` 3. Implement the `getAllSymbols` function to [obtain all symbols for all supported exchanges][load-all-cryptocompare-api]. ```javascript title="/chart‑project/src/datafeed.js" // DatafeedConfiguration implementation // ... // Obtains all symbols for all exchanges supported by CryptoCompare API async function getAllSymbols() { const data = await makeApiRequest('data/v3/all/exchanges'); let allSymbols = []; for (const exchange of configurationData.exchanges) { const pairs = data.Data[exchange.value].pairs; for (const leftPairPart of Object.keys(pairs)) { const symbols = pairs[leftPairPart].map(rightPairPart => { const symbol = generateSymbol(exchange.value, leftPairPart, rightPairPart); return { symbol: symbol.short, ticker: symbol.short, description: symbol.short, exchange: exchange.value, type: 'crypto', }; }); allSymbols = [...allSymbols, ...symbols]; } } return allSymbols; } ``` 4. Implement the [`resolveSymbol`] method and specify [symbol information] in a `symbolInfo` object according to [`LibrarySymbolInfo`]. ```javascript title="/chart‑project/src/datafeed.js" resolveSymbol: async ( symbolName, onSymbolResolvedCallback, onResolveErrorCallback, extension ) => { console.log('[resolveSymbol]: Method call', symbolName); const symbols = await getAllSymbols(); const symbolItem = symbols.find(({ ticker }) => ticker === symbolName); if (!symbolItem) { console.log('[resolveSymbol]: Cannot resolve symbol', symbolName); onResolveErrorCallback('Cannot resolve symbol'); return; } // Symbol information object const symbolInfo = { ticker: symbolItem.ticker, name: symbolItem.symbol, description: symbolItem.description, type: symbolItem.type, session: '24x7', timezone: 'Etc/UTC', exchange: symbolItem.exchange, minmov: 1, pricescale: 100, has_intraday: false, visible_plots_set: 'ohlc', has_weekly_and_monthly: false, supported_resolutions: configurationData.supported_resolutions, volume_precision: 2, data_status: 'streaming', }; console.log('[resolveSymbol]: Symbol resolved', symbolName); onSymbolResolvedCallback(symbolInfo); }, ``` :::info In this tutorial, you specified `supported_resolutions: ['1D', '1W', '1M']` in the [`onReady`](#onready) method. The library can build weekly and monthly resolutions from the daily ones (`1D`). However, you need to directly specify that the datafeed does not have these resolutions by setting [`has_weekly_and_monthly`] to `false`. ::: ### getBars The library uses [`getBars`] to get historical data for a symbol within a certain range. Historical data will be retrieved from the CryptoCompare API. 1. In `helpers.js`, implement a `parseFullSymbol` function that will parse a crypto pair symbol and return all parts of this symbol. Note that the `full` value is returned from [`generateSymbol`](#resolvesymbol). ```javascript title="/chart‑project/src/helpers.js" // makeApiRequest and generateSymbol implementation // ... // Returns all parts of the symbol export function parseFullSymbol(fullSymbol) { const match = fullSymbol.match(/^(\w+):(\w+)\/(\w+)$/); if (!match) { return null; } return { exchange: match[1], fromSymbol: match[2], toSymbol: match[3] }; } ``` 2. Import `parseFullSymbol` into `datafeed.js`. ```javascript title="/chart‑project/src/datafeed.js" import { makeApiRequest, generateSymbol, parseFullSymbol } from './helpers.js'; ``` 3. Implement [`getBars`] using `parseFullSymbol` and CryptoCompare's [Daily Pair OHLCV] to retrieve historic OHLCV data. :::caution The CryptoCompare API does not allow specifying the `from` date, so you have to filter bars on the client side. ::: ```javascript title="/chart‑project/src/datafeed.js" getBars: async (symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) => { const { from, to, firstDataRequest } = periodParams; console.log('[getBars]: Method call', symbolInfo, resolution, from, to); const parsedSymbol = parseFullSymbol(symbolInfo.full_name); const urlParameters = { e: parsedSymbol.exchange, fsym: parsedSymbol.fromSymbol, tsym: parsedSymbol.toSymbol, toTs: to, limit: 2000, }; const query = Object.keys(urlParameters) .map(name => `${name}=${encodeURIComponent(urlParameters[name])}`) .join('&'); try { const data = await makeApiRequest(`data/histoday?${query}`); if (data.Response && data.Response === 'Error' || data.Data.length === 0) { // "noData" should be set if there is no data in the requested period onHistoryCallback([], { noData: true }); return; } let bars = []; data.Data.forEach(bar => { if (bar.time >= from && bar.time < to) { bars = [...bars, { time: bar.time * 1000, low: bar.low, high: bar.high, open: bar.open, close: bar.close, }]; } }); console.log(`[getBars]: returned ${bars.length} bar(s)`); onHistoryCallback(bars, { noData: false }); } catch (error) { console.log('[getBars]: Get error', error); onErrorCallback(error); } }, ``` ### searchSymbols The library uses the [`searchSymbols`] method to request symbols that match some user input. ```javascript title="/chart‑project/src/datafeed.js" searchSymbols: async ( userInput, exchange, symbolType, onResultReadyCallback ) => { console.log('[searchSymbols]: Method call'); const symbols = await getAllSymbols(); const newSymbols = symbols.filter(symbol => { const isExchangeValid = exchange === '' || symbol.exchange === exchange; const fullName = `${symbol.exchange}:${symbol.ticker}`; const isFullSymbolContainsInput = fullName .toLowerCase() .indexOf(userInput.toLowerCase()) !== -1; return isExchangeValid && isFullSymbolContainsInput; }); onResultReadyCallback(newSymbols); }, ``` In this case, you will request all available symbols from the API and filter them in `datafeed.js`. If a user has not selected an exchange, the `exchange` argument will be equal to an empty string. ## Result At this point, you have implemented datafeed. Save all your changes and run the following command from your project directory (`chart‑project` in this tutorial): ```bash npx serve ``` Open the library locally in your web browser to see the results. You should see a chart plotted and be able to search symbols and display historical data. ## Next steps In the next stage, you will implement real-time data streaming via WebSocket. ## Complete code Click the following sections to reveal the complete code for the examples at this stage of the tutorial.
datafeed.js ```javascript import { makeApiRequest, generateSymbol, parseFullSymbol } from './helpers.js'; // DatafeedConfiguration implementation const configurationData = { // Represents the resolutions for bars supported by your datafeed supported_resolutions: ['1D', '1W', '1M'], // The `exchanges` arguments are used for the `searchSymbols` method if a user selects the exchange exchanges: [ { value: 'Bitfinex', name: 'Bitfinex', desc: 'Bitfinex'}, { value: 'Kraken', name: 'Kraken', desc: 'Kraken bitcoin exchange'}, ], // The `symbols_types` arguments are used for the `searchSymbols` method if a user selects this symbol type symbols_types: [ { name: 'crypto', value: 'crypto'} ] }; // Obtains all symbols for all exchanges supported by CryptoCompare API async function getAllSymbols() { const data = await makeApiRequest('data/v3/all/exchanges'); let allSymbols = []; for (const exchange of configurationData.exchanges) { const pairs = data.Data[exchange.value].pairs; for (const leftPairPart of Object.keys(pairs)) { const symbols = pairs[leftPairPart].map(rightPairPart => { const symbol = generateSymbol(exchange.value, leftPairPart, rightPairPart); return { symbol: symbol.short, ticker: symbol.short, description: symbol.short, exchange: exchange.value, type: 'crypto', }; }); allSymbols = [...allSymbols, ...symbols]; } } return allSymbols; } export default { onReady: (callback) => { console.log('[onReady]: Method call'); setTimeout(() => callback(configurationData)); }, searchSymbols: async ( userInput, exchange, symbolType, onResultReadyCallback ) => { console.log('[searchSymbols]: Method call'); const symbols = await getAllSymbols(); const newSymbols = symbols.filter(symbol => { const isExchangeValid = exchange === '' || symbol.exchange === exchange; const fullName = `${symbol.exchange}:${symbol.ticker}`; const isFullSymbolContainsInput = fullName .toLowerCase() .indexOf(userInput.toLowerCase()) !== -1; return isExchangeValid && isFullSymbolContainsInput; }); onResultReadyCallback(newSymbols); }, resolveSymbol: async ( symbolName, onSymbolResolvedCallback, onResolveErrorCallback, extension ) => { console.log('[resolveSymbol]: Method call', symbolName); const symbols = await getAllSymbols(); const symbolItem = symbols.find(({ ticker }) => ticker === symbolName); if (!symbolItem) { console.log('[resolveSymbol]: Cannot resolve symbol', symbolName); onResolveErrorCallback('Cannot resolve symbol'); return; } // Symbol information object const symbolInfo = { ticker: symbolItem.ticker, name: symbolItem.symbol, description: symbolItem.description, type: symbolItem.type, session: '24x7', timezone: 'Etc/UTC', exchange: symbolItem.exchange, minmov: 1, pricescale: 100, has_intraday: false, visible_plots_set: 'ohlc', has_weekly_and_monthly: false, supported_resolutions: configurationData.supported_resolutions, volume_precision: 2, data_status: 'streaming', }; console.log('[resolveSymbol]: Symbol resolved', symbolName); onSymbolResolvedCallback(symbolInfo); }, getBars: async (symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) => { const { from, to, firstDataRequest } = periodParams; console.log('[getBars]: Method call', symbolInfo, resolution, from, to); const parsedSymbol = parseFullSymbol(symbolInfo.full_name); const urlParameters = { e: parsedSymbol.exchange, fsym: parsedSymbol.fromSymbol, tsym: parsedSymbol.toSymbol, toTs: to, limit: 2000, }; const query = Object.keys(urlParameters) .map(name => `${name}=${encodeURIComponent(urlParameters[name])}`) .join('&'); try { const data = await makeApiRequest(`data/histoday?${query}`); if (data.Response && data.Response === 'Error' || data.Data.length === 0) { // "noData" should be set if there is no data in the requested period onHistoryCallback([], { noData: true }); return; } let bars = []; data.Data.forEach(bar => { if (bar.time >= from && bar.time < to) { bars = [...bars, { time: bar.time * 1000, low: bar.low, high: bar.high, open: bar.open, close: bar.close, }]; } }); console.log(`[getBars]: returned ${bars.length} bar(s)`); onHistoryCallback(bars, { noData: false }); } catch (error) { console.log('[getBars]: Get error', error); onErrorCallback(error); } }, subscribeBars: (symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) => { console.log('[subscribeBars]: Method call with subscriberUID:', subscriberUID); }, unsubscribeBars: (subscriberUID) => { console.log('[unsubscribeBars]: Method call with subscriberUID:', subscriberUID); }, }; ```
helpers.js ```javascript // Your CryptoCompare API key export const apiKey = ""; // Makes requests to CryptoCompare API export async function makeApiRequest(path) { try { const url = new URL(`https://min-api.cryptocompare.com/${path}`); url.searchParams.append('api_key',apiKey) const response = await fetch(url.toString()); return response.json(); } catch (error) { throw new Error(`CryptoCompare request error: ${error.status}`); } } // Generates a symbol ID from a pair of the coins export function generateSymbol(exchange, fromSymbol, toSymbol) { const short = `${fromSymbol}/${toSymbol}`; return { short, }; } // Returns all parts of the symbol export function parseFullSymbol(fullSymbol) { const match = fullSymbol.match(/^(\w+):(\w+)\/(\w+)$/); if (!match) { return null; } return { exchange: match[1], fromSymbol: match[2], toSymbol: match[3] }; } ```
[before]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial#use-external-data-source [CryptoCompare API]: https://min-api.cryptocompare.com/ [Daily Pair OHLCV]: https://min-api.cryptocompare.com/documentation?key=Historical&cat=dataHistoday [Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api [`DatafeedConfiguration`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration [datafeed object]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#datafeed [`getBars`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#getbars [`has_weekly_and_monthly`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Datafeed.LibrarySymbolInfo#has_weekly_and_monthly [`LibrarySymbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo [load-all-cryptocompare-api]: https://min-api.cryptocompare.com/documentation?key=Other&cat=allExchangesV3Endpoint [`onReady`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#onready [`OnReadyCallback`]: https://www.tradingview.com/charting-library-docs/latest/api/modules/Datafeed#onreadycallback [`resolveSymbol`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol [`searchSymbols`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#searchsymbols [start]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial [symbol information]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor [CryptoCompare documentation]: https://www.cryptocompare.com/coins/guides/how-to-use-our-api/ URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial/Streaming-Implementation ============================================================================================================================= # Implement streaming :::tip This article is part of a tutorial about implementing Datafeed API. We recommend that you follow the guide from the [start]. ::: At this stage, you will implement real-time data updates via WebSocket. You will know how to: - Connect to streaming and unsubscribe from it. - Subscribe for data updates and handle them. ## Step 1. Connect to streaming To connect your datafeed to the streaming API: 1. Import `apiKey` from [`helpers.js`] into `streaming.js`. ```javascript title="/chart‑project/src/streaming.js" import { apiKey } from './helpers.js'; ``` 2. Create a new file called `streaming.js`, where you will implement a connection to WebSocket. ```javascript title="/chart‑project/src/streaming.js" const socket = new WebSocket( 'wss://streamer.cryptocompare.com/v2?api_key=' + apiKey ); const channelToSubscription = new Map(); socket.addEventListener('open', () => { console.log('[socket] Connected'); }); socket.addEventListener('close', (reason) => { console.log('[socket] Disconnected:', reason); }); socket.addEventListener('error', (error) => { console.log('[socket] Error:', error); }); export function subscribeOnStream() { // To Do } export function unsubscribeFromStream() { // To Do } ``` 3. Import the functions from `streaming.js` into `datafeed.js`: ```javascript title="/chart‑project/src/datafeed.js" import { subscribeOnStream, unsubscribeFromStream } from './streaming.js'; ``` 4. To subscribe for real-time data updates for a symbol, implement [`subscribeBars`]. the library calls it every time the chart symbol or resolution is changed, or when the chart needs to subscribe to a new symbol. ```javascript title="/chart‑project/src/datafeed.js" // ... // Use it to keep a record of the most recent bar on the chart const lastBarsCache = new Map(); // ... export default { // ... subscribeBars: ( symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback ) => { console.log('[subscribeBars]: Method call with subscriberUID:', subscriberUID); subscribeOnStream( symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback, lastBarsCache.get(symbolInfo.full_name), ); }, }; ``` 5. Implement [`unsubscribeBars`] to stop receiving updates for the symbol when a user selects another symbol on the chart. ```javascript title="/chart‑project/src/datafeed.js" unsubscribeBars: (subscriberUID) => { console.log('[unsubscribeBars]: Method call with subscriberUID:', subscriberUID); unsubscribeFromStream(subscriberUID); }, ``` ## Step 2. Subscribe for updates On the previous step, you connected your datafeed to WebSocket. Now, you need to subscribe to the channels to receive updates: 1. Import `parseFullSymbol` from [`helpers.js`] into `streaming.js`. ```javascript title="/chart‑project/src/streaming.js" import { parseFullSymbol, apiKey } from './helpers.js'; ``` 2. Implement `subscribeOnStream` to subscribe for updates. ```javascript title="/chart‑project/src/streaming.js" // ... const channelToSubscription = new Map(); // ... export function subscribeOnStream( symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback, lastDailyBar ) { const parsedSymbol = parseFullSymbol(symbolInfo.full_name); const channelString = `0~${parsedSymbol.exchange}~${parsedSymbol.fromSymbol}~${parsedSymbol.toSymbol}`; const handler = { id: subscriberUID, callback: onRealtimeCallback, }; let subscriptionItem = channelToSubscription.get(channelString); if (subscriptionItem) { // Already subscribed to the channel, use the existing subscription subscriptionItem.handlers.push(handler); return; } subscriptionItem = { subscriberUID, resolution, lastDailyBar, handlers: [handler], }; channelToSubscription.set(channelString, subscriptionItem); console.log( '[subscribeBars]: Subscribe to streaming. Channel:', channelString ); const subRequest = { action: 'SubAdd', subs: [channelString], }; socket.send(JSON.stringify(subRequest)); } ``` ## Step 3. Unsubscribe from streaming Implement `unsubscribeFromStream` to unsubscribe from streaming: ```javascript title="/chart‑project/src/streaming.js" export function unsubscribeFromStream(subscriberUID) { // Find a subscription with id === subscriberUID for (const channelString of channelToSubscription.keys()) { const subscriptionItem = channelToSubscription.get(channelString); const handlerIndex = subscriptionItem.handlers.findIndex( (handler) => handler.id === subscriberUID ); if (handlerIndex !== -1) { // Remove from handlers subscriptionItem.handlers.splice(handlerIndex, 1); if (subscriptionItem.handlers.length === 0) { // Unsubscribe from the channel if it was the last handler console.log( '[unsubscribeBars]: Unsubscribe from streaming. Channel:', channelString ); const subRequest = { action: 'SubRemove', subs: [channelString], }; socket.send(JSON.stringify(subRequest)); channelToSubscription.delete(channelString); break; } } } } ``` ## Step 4. Handle updates The responses for requests look like this: ```javascript 0~Bitfinex~BTC~USD~2~335394436~1548837377~0.36~3504.1~1261.4759999999999~1f ``` To handle updates coming from the WebSocket: 1. Implement the following function in `streaming.js`: ```javascript title="/chart‑project/src/streaming.js" // ... socket.addEventListener('message', (event) => { const data = JSON.parse(event.data); console.log('[socket] Message:', data); const { TYPE: eventTypeStr, M: exchange, FSYM: fromSymbol, TSYM: toSymbol, TS: tradeTimeStr, P: tradePriceStr, } = data; if (parseInt(eventTypeStr) !== 0) { // Skip all non-trading events return; } const tradePrice = parseFloat(tradePriceStr); const tradeTime = parseInt(tradeTimeStr); const channelString = `0~${exchange}~${fromSymbol}~${toSymbol}`; const subscriptionItem = channelToSubscription.get(channelString); if (subscriptionItem === undefined) { return; } const lastDailyBar = subscriptionItem.lastDailyBar; let bar = { ...lastDailyBar, high: Math.max(lastDailyBar.high, tradePrice), low: Math.min(lastDailyBar.low, tradePrice), close: tradePrice, }; console.log('[socket] Update the latest bar by price', tradePrice); subscriptionItem.lastDailyBar = bar; // Send data to every subscriber of that symbol subscriptionItem.handlers.forEach((handler) => handler.callback(bar)); }); ``` 2. Adjust the [`getBars`] method in `datafeed.js` to save the last bar data for the current symbol. ```javascript title="/chart‑project/src/datafeed.js" //... data.Data.forEach( ... ); // highlight-start if (firstDataRequest) { lastBarsCache.set(symbolInfo.full_name, { ...bars[bars.length - 1], }); } // highlight-end console.log(`[getBars]: returned ${bars.length} bar(s)`); // ... ``` 3. Add `getNextDailyBarTime` function to `streaming.js`. ```javascript title="/chart‑project/src/streaming.js" function getNextDailyBarTime(barTime) { const date = new Date(barTime * 1000); date.setDate(date.getDate() + 1); return date.getTime() / 1000; } ``` CryptoCompare API provides a streaming of ticks, not bars. So, you need to check that the new trade is related to the new daily bar. Note that you might need a more comprehensive check for the production version. 4. Adjust the `socket.on` listener in `streaming.js`. ```javascript socket.on('m', data => { //... const lastDailyBar = subscriptionItem.lastDailyBar; // highlight-start const nextDailyBarTime = getNextDailyBarTime(lastDailyBar.time); let bar; if (tradeTime >= nextDailyBarTime) { bar = { time: nextDailyBarTime, open: tradePrice, high: tradePrice, low: tradePrice, close: tradePrice, }; console.log('[socket] Generate new bar', bar); } else { bar = { ...lastDailyBar, high: Math.max(lastDailyBar.high, tradePrice), low: Math.min(lastDailyBar.low, tradePrice), close: tradePrice, }; console.log('[socket] Update the latest bar by price', tradePrice); } // highlight-end subscriptionItem.lastDailyBar = bar; //... }); ``` ## Result 🎉 Congrats! At this point, you have implemented a datafeed with searching and resolving symbols, loading historical data, and providing real-time data updates via WebSocket. Now you can run `npx serve` from the `chart-project` folder (if you have not already done it before) and check how the implementation works. ## Complete code Click the following sections to reveal the complete code for the examples at this stage of the tutorial.
index.html ```html TradingView Advanced Charts example
```
datafeed.js ```javascript import { makeApiRequest, generateSymbol, parseFullSymbol } from './helpers.js'; import { subscribeOnStream, unsubscribeFromStream } from './streaming.js'; const lastBarsCache = new Map(); // DatafeedConfiguration implementation const configurationData = { // Represents the resolutions for bars supported by your datafeed supported_resolutions: ['1D', '1W', '1M'], // The `exchanges` arguments are used for the `searchSymbols` method if a user selects the exchange exchanges: [{ value: 'Bitfinex', name: 'Bitfinex', desc: 'Bitfinex', }, { value: 'Kraken', // Filter name name: 'Kraken', // Full exchange name displayed in the filter popup desc: 'Kraken bitcoin exchange', }, ], // The `symbols_types` arguments are used for the `searchSymbols` method if a user selects this symbol type symbols_types: [{ name: 'crypto', value: 'crypto', }, ], }; // Obtains all symbols for all exchanges supported by CryptoCompare API async function getAllSymbols() { const data = await makeApiRequest('data/v3/all/exchanges'); let allSymbols = []; for (const exchange of configurationData.exchanges) { const pairs = data.Data[exchange.value].pairs; for (const leftPairPart of Object.keys(pairs)) { const symbols = pairs[leftPairPart].map(rightPairPart => { const symbol = generateSymbol(exchange.value, leftPairPart, rightPairPart); return { symbol: symbol.short, full_name: symbol.full, description: symbol.short, exchange: exchange.value, type: 'crypto', }; }); allSymbols = [...allSymbols, ...symbols]; } } return allSymbols; } export default { onReady: (callback) => { console.log('[onReady]: Method call'); setTimeout(() => callback(configurationData)); }, searchSymbols: async ( userInput, exchange, symbolType, onResultReadyCallback, ) => { console.log('[searchSymbols]: Method call'); const symbols = await getAllSymbols(); const newSymbols = symbols.filter(symbol => { const isExchangeValid = exchange === '' || symbol.exchange === exchange; const isFullSymbolContainsInput = symbol.full_name .toLowerCase() .indexOf(userInput.toLowerCase()) !== -1; return isExchangeValid && isFullSymbolContainsInput; }); onResultReadyCallback(newSymbols); }, resolveSymbol: async ( symbolName, onSymbolResolvedCallback, onResolveErrorCallback, extension ) => { console.log('[resolveSymbol]: Method call', symbolName); const symbols = await getAllSymbols(); const symbolItem = symbols.find(({ full_name, }) => full_name === symbolName); if (!symbolItem) { console.log('[resolveSymbol]: Cannot resolve symbol', symbolName); onResolveErrorCallback('cannot resolve symbol'); return; } // Symbol information object const symbolInfo = { ticker: symbolItem.full_name, name: symbolItem.symbol, description: symbolItem.description, type: symbolItem.type, session: '24x7', timezone: 'Etc/UTC', exchange: symbolItem.exchange, minmov: 1, pricescale: 100, has_intraday: false, has_no_volume: true, has_weekly_and_monthly: false, supported_resolutions: configurationData.supported_resolutions, volume_precision: 2, data_status: 'streaming', }; console.log('[resolveSymbol]: Symbol resolved', symbolName); onSymbolResolvedCallback(symbolInfo); }, getBars: async (symbolInfo, resolution, periodParams, onHistoryCallback, onErrorCallback) => { const { from, to, firstDataRequest } = periodParams; console.log('[getBars]: Method call', symbolInfo, resolution, from, to); const parsedSymbol = parseFullSymbol(symbolInfo.full_name); const urlParameters = { e: parsedSymbol.exchange, fsym: parsedSymbol.fromSymbol, tsym: parsedSymbol.toSymbol, toTs: to, limit: 2000, }; const query = Object.keys(urlParameters) .map(name => `${name}=${encodeURIComponent(urlParameters[name])}`) .join('&'); try { const data = await makeApiRequest(`data/histoday?${query}`); if (data.Response && data.Response === 'Error' || data.Data.length === 0) { // "noData" should be set if there is no data in the requested period onHistoryCallback([], { noData: true, }); return; } let bars = []; data.Data.forEach(bar => { if (bar.time >= from && bar.time < to) { bars = [...bars, { time: bar.time * 1000, low: bar.low, high: bar.high, open: bar.open, close: bar.close, }]; } }); if (firstDataRequest) { lastBarsCache.set(symbolInfo.full_name, { ...bars[bars.length - 1], }); } console.log(`[getBars]: returned ${bars.length} bar(s)`); onHistoryCallback(bars, { noData: false, }); } catch (error) { console.log('[getBars]: Get error', error); onErrorCallback(error); } }, subscribeBars: ( symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback, ) => { console.log('[subscribeBars]: Method call with subscriberUID:', subscriberUID); subscribeOnStream( symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback, lastBarsCache.get(symbolInfo.full_name), ); }, unsubscribeBars: (subscriberUID) => { console.log('[unsubscribeBars]: Method call with subscriberUID:', subscriberUID); unsubscribeFromStream(subscriberUID); }, }; ```
streaming.js ```javascript import { parseFullSymbol, apiKey } from './helpers.js'; const socket = new WebSocket( 'wss://streamer.cryptocompare.com/v2?api_key=' + apiKey ); const channelToSubscription = new Map(); socket.addEventListener('open', () => { console.log('[socket] Connected'); }); socket.addEventListener('close', (reason) => { console.log('[socket] Disconnected:', reason); }); socket.addEventListener('error', (error) => { console.log('[socket] Error:', error); }); socket.addEventListener('message', (event) => { const data = JSON.parse(event.data); console.log('[socket] Message:', data); const { TYPE: eventTypeStr, M: exchange, FSYM: fromSymbol, TSYM: toSymbol, TS: tradeTimeStr, P: tradePriceStr, } = data; if (parseInt(eventTypeStr) !== 0) { // Skip all non-trading events return; } const tradePrice = parseFloat(tradePriceStr); const tradeTime = parseInt(tradeTimeStr); const channelString = `0~${exchange}~${fromSymbol}~${toSymbol}`; const subscriptionItem = channelToSubscription.get(channelString); if (subscriptionItem === undefined) { return; } const lastDailyBar = subscriptionItem.lastDailyBar; const nextDailyBarTime = getNextDailyBarTime(lastDailyBar.time); let bar; if (tradeTime >= nextDailyBarTime) { bar = { time: nextDailyBarTime, open: tradePrice, high: tradePrice, low: tradePrice, close: tradePrice, }; console.log('[socket] Generate new bar', bar); } else { bar = { ...lastDailyBar, high: Math.max(lastDailyBar.high, tradePrice), low: Math.min(lastDailyBar.low, tradePrice), close: tradePrice, }; console.log('[socket] Update the latest bar by price', tradePrice); } subscriptionItem.lastDailyBar = bar; // Send data to every subscriber of that symbol subscriptionItem.handlers.forEach((handler) => handler.callback(bar)); }); function getNextDailyBarTime(barTime) { const date = new Date(barTime * 1000); date.setDate(date.getDate() + 1); return date.getTime() / 1000; } export function subscribeOnStream( symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback, lastDailyBar ) { const parsedSymbol = parseFullSymbol(symbolInfo.full_name); const channelString = `0~${parsedSymbol.exchange}~${parsedSymbol.fromSymbol}~${parsedSymbol.toSymbol}`; const handler = { id: subscriberUID, callback: onRealtimeCallback, }; let subscriptionItem = channelToSubscription.get(channelString); if (subscriptionItem) { // Already subscribed to the channel, use the existing subscription subscriptionItem.handlers.push(handler); return; } subscriptionItem = { subscriberUID, resolution, lastDailyBar, handlers: [handler], }; channelToSubscription.set(channelString, subscriptionItem); console.log( '[subscribeBars]: Subscribe to streaming. Channel:', channelString ); const subRequest = { action: 'SubAdd', subs: [channelString], }; socket.send(JSON.stringify(subRequest)); } export function unsubscribeFromStream(subscriberUID) { // Find a subscription with id === subscriberUID for (const channelString of channelToSubscription.keys()) { const subscriptionItem = channelToSubscription.get(channelString); const handlerIndex = subscriptionItem.handlers.findIndex( (handler) => handler.id === subscriberUID ); if (handlerIndex !== -1) { // Remove from handlers subscriptionItem.handlers.splice(handlerIndex, 1); if (subscriptionItem.handlers.length === 0) { // Unsubscribe from the channel if it was the last handler console.log( '[unsubscribeBars]: Unsubscribe from streaming. Channel:', channelString ); const subRequest = { action: 'SubRemove', subs: [channelString], }; socket.send(JSON.stringify(subRequest)); channelToSubscription.delete(channelString); break; } } } } ```
## What's next? We hope this tutorial helped you understand the essentials of the [Datafeed API] and how to work with it. If you want to dive deeper into the details, we recommend checking out the following articles: - [Widget Constructor]: get a better understanding of the Widget Constructor's capabilities and settings. - [Datafeed Common Issues]: explore common issues that you might face when implementing the Datafeed API. - [Customization Overview]: learn how to customize UI elements and chart behavior. [Customization Overview]: https://www.tradingview.com/charting-library-docs/latest/customization [Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api [Datafeed Common Issues]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Datafeed-Issues [`getBars`]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial/Datafeed-Implementation#getbars [`helpers.js`]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial/Datafeed-Implementation#resolvesymbol [start]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial [`subscribeBars`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#subscribebars [`unsubscribeBars`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#unsubscribebars [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial/Widget-Setup ================================================================================================================= # Set up the widget :::tip This article is part of a tutorial about implementing Datafeed API. We recommend that you follow the guide from the [start]. ::: At this stage of the tutorial, you will initialize the basic elements of the integration and create a chart. ## Step 1. Clone the library 1. Create a directory for your project: ```bash mkdir chart-project cd chart-project ``` 2. Clone the [library repository][library-repo] 🔐 (access is [restricted][get-access]). ```bash git clone https://github.com/tradingview/charting_library charting_library_cloned_data ``` ## Step 2. Add a container To display the chart, you need to add a DOM container. To do this, create an initial `index.html` file in your project directory (`chart‑project` in this tutorial) and add the following code: ```html title="/chart‑project/index.html" TradingView Advanced Charts example
``` At this point, you added a script that is used to load the library and a container that will be used as a placeholder for the chart. ## Step 3. Create Widget Constructor 1. Add the `src` folder to your project directory. 2. Create a `main.js` file in `src` and add the following code that creates [Widget Constructor][widget-constructor]. Widget Constructor is the library entry point that allows embedding the library widget into your web page. ```javascript title="/chart‑project/src/main.js" // Datafeed implementation that you will add later import Datafeed from './datafeed.js'; window.tvWidget = new TradingView.widget({ symbol: 'BTC/EUR', // Default symbol pair interval: '1D', // Default interval fullscreen: true, // Displays the chart in the fullscreen mode container: 'tv_chart_container', // Reference to an attribute of a DOM element datafeed: Datafeed, library_path: '../charting_library_cloned_data/charting_library/', }); ``` :::tip This tutorial uses only the required Widget Constructor parameters that will be enabled when the chart is first loaded. However, Widget Constructor has many different parameters to manage. You can find the full list in the [`ChartingLibraryWidgetOptions`] interface. ::: ## Next steps At this stage, you have set up Widget Constructor. Next, you will implement your own datafeed and methods. ## Complete code Click the following sections to reveal the complete code for the examples at this stage of the tutorial.
index.html ```html TradingView Advanced Charts example
```
main.js ```javascript // Datafeed implementation that you will add later import Datafeed from './datafeed.js'; window.tvWidget = new TradingView.widget({ symbol: 'BTC/EUR', // Default symbol pair interval: '1D', // Default interval fullscreen: true, // Displays the chart in the fullscreen mode container: 'tv_chart_container', // Reference to the attribute of the DOM element datafeed: Datafeed, library_path: '../charting_library_cloned_data/charting_library/', }); ```
[get-access]: https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-start#getting-access "Click to open the 'Getting Access' section." [library-repo]: https://github.com/tradingview/charting_library/ "The repository is private." [`ChartingLibraryWidgetOptions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions [start]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial [widget-constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial ==================================================================================================== # How to connect data via datafeed API This tutorial explains how to implement real-time data streaming to Advanced Charts / [Trading Platform] step-by-step. As an example, the tutorial describes connection via free CryptoCompare API that [provides data](#use-external-data-source) from several crypto exchanges. After completing this tutorial, you will learn how to implement datafeed using Datafeed API, display historical data using ordinary HTTP requests, and stream real-time data via WebSocket. The tutorial is divided into three parts: 1. [Widget Constructor set-up](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial/Widget-Setup) 2. [Datafeed implementation](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial/Datafeed-Implementation) 3. [Streaming implementation](https://www.tradingview.com/charting-library-docs/latest/tutorials/implement_datafeed_tutorial/Streaming-Implementation) :::tip Tips - You can find the final code for this tutorial on the [GitHub repository][tutorial-repo-url]. - At the end of each section, you will find the complete code blocks related to a specific step. - Before proceeding with the tutorial, we recommend checking the [Prerequisites](#prerequisites) section. ::: ## Prerequisites ### Get repository access The [Advanced Charts repository][cl-repo] is private. Refer to the [Getting Access] section for more information. ### Use external data source The library is used to display financial data but it does not contain or provide any data. You need to implement your own data source to display data in the library. It can be a web API, a database, or a CSV file. This tutorial uses the [CryptoCompare API], which has a wide range of market data. Note that CryptoCompare requires an API key to request their stream data. You need to get such key to complete the tutorial. Refer to the [CryptoCompare documentation] for more information. :::caution We cannot guarantee that CryptoCompare works in your region. If you see the `ERR_CONNECTION_REFUSED` error when running the tutorial, try to use a proxy or VPN. ::: ### See results on the fly If you want to see the results of this tutorial right away, take the following steps: 1. Clone the [tutorial repository][tutorial-repo-url]. Note that for the real project, it is better to use this repository as a submodule in yours. ```bash git clone https://github.com/tradingview/charting-library-tutorial.git ``` 2. Go to the repository folder and initialize the Git submodule with the library: ```bash git submodule update --init --recursive ``` Alternatively, you can [download] the library repository from a ZIP file or [clone] it using Git. 3. Run the following command to serve static files: ```bash npx serve ``` [cl-repo]: https://github.com/tradingview/charting_library [clone]: https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository [CryptoCompare API]: https://min-api.cryptocompare.com/ [download]: https://docs.github.com/en/repositories/working-with-files/using-files/downloading-source-code-archives [Getting Access]: https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-start#getting-access [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [tutorial-repo-url]: https://github.com/tradingview/charting-library-tutorial [CryptoCompare documentation]: https://www.cryptocompare.com/coins/guides/how-to-use-our-api/ URL: https://www.tradingview.com/charting-library-docs/latest/tutorials ======================================================================== # Tutorials import CardLinkList from "@site/src/components/CardLinkList"; import DatabaseIcon from "@site/static/img/svg-icons/database-solid.svg"; import TerminalIcon from "@site/static/img/svg-icons/terminal-solid.svg"; import BugIcon from "@site/static/img/svg-icons/bug-solid.svg"; import TableIcon from "@site/static/img/svg-icons/table-columns-solid.svg"; import ChartLineIcon from "@site/static/img/svg-icons/chart-line-solid.svg"; import ButtonIcon from "@site/static/img/svg-icons/square-check-regular.svg"; import MoneyIcon from "@site/static/img/svg-icons/money-trend-up-solid.svg"; import SnapshotIcon from "@site/static/img/svg-icons/snapshot-icon.svg"; import AngularLogo from "@site/static/img/svg-icons/angular.svg"; import AndroidLogo from "@site/static/img/svg-icons/android.svg"; import NextjsLogo from "@site/static/img/svg-icons/nextjs.svg"; import NuxtjsLogo from "@site/static/img/svg-icons/nuxtjs.svg"; import ReactLogo from "@site/static/img/svg-icons/react.svg"; import ReactNativeLogo from "@site/static/img/svg-icons/react-native.svg"; import RubyOnRailsLogo from "@site/static/img/svg-icons/ruby-on-rails.svg"; import SvelteLogo from "@site/static/img/svg-icons/svelte.svg"; import SwiftLogo from "@site/static/img/svg-icons/swift.svg"; import VuejsLogo from "@site/static/img/svg-icons/vuejs.svg"; import SolidjsLogo from "@site/static/img/svg-icons/solidjs.svg"; ## First steps We prepared several tutorials and guides that will walk you through the basics. , description: "Learn how to start using the library and run it locally", }, { href: "/latest/tutorials/enable-debug-mode", title: "Enable debug mode", image: , description: "Learn how to enable logs when connecting data and implementing trading features", }, { href: "/latest/tutorials/implement_datafeed_tutorial/", title: "Connect data", image: , description: "Implement Datafeed API and connect real‑time data streaming", }, { href: "/latest/tutorials/implement-broker-api/", title: "Enable trading", image: , description: "Implement Broker API to enable basic trading functionality", }, ]} /> ## Further steps Once you've mastered the basics, dive into more advanced topics and explore specific features with these tutorials and guides. , description: "Implement an indicator that displays a Simple Moving Average and Smoothing Line", }, { href: "/latest/tutorials/create-custom-page-in-account-manager/", title: "Create custom page", image: , description: "Learn how to create custom page in the Account Manager with dynamic data updates", }, { href: "/latest/tutorials/add-custom-button-to-top-toolbar/", title: "Create custom buttons", image: , description: "Learn how to add a custom button to the top toolbar of the chart", }, { href: "/latest/tutorials/implement-snapshots-server/", title: "Implement snapshots server", image: , description: "Learn how to implement a Node.js server to host snapshots generated by the library", }, ]} /> ## Framework integrations We have a collection of integration examples for frameworks commonly used with Advanced Charts and Trading Platform. The sections below link to GitHub pages where you can learn more about library integrations. , }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/angular", title: "Angular", image: , }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/ios-swift", title: "iOS WKWebView", image: , description: "Swift version" }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/nextjs-javascript", title: "Next.js", image: , description: "Up to version 13" }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/nextjs", title: "Next.js", image: , description: "Starting from version 13" }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/nuxtjs", title: "Nuxt.js", image: , description: "Up to version 2.x" }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/nuxtjs3", title: "Nuxt.js", image: , description: "Starting from version 3.x" }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/react-native", title: "React Native", image: , }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/react-javascript", title: "React and JavaScript", image: , }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/react-typescript", title: "React and TypeScript", image: , }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/ruby-on-rails", title: "Ruby on Rails", image: , }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/sveltekit", title: "SvelteKit", image: , }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/vuejs", title: "Vue.js", image: , description: "Version 2" }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/vuejs3", title: "Vue.js", image: , description: "Version 3" }, { href: "https://github.com/tradingview/charting-library-examples/tree/master/solidjs-typescript", title: "Solid.js", image: }, ]} /> ## Interactive examples Explore our CodePen account that hosts interactive examples to learn and experiment with different features in just a few clicks. The examples can help you elevate your understanding of both Advanced Charts and Trading Platform. import CTAButton from "@site/src/components/landing-page/CTAButton"; URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Chart ================================================================================ # Chart This article contains general information on how to customize and control the chart. For more information about certain chart elements, refer to the rest of the articles in the **UI Elements** section. ## Default chart settings You should use the Widget Constructor to set up default chart settings like symbol, [resolution](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution), [time zone](https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezones), [locale](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Localization), [size](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructorchart-size), and others. Refer to the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructorchart-configuration) article for more information. ## Customization :::tip Refer to the [Customization](https://www.tradingview.com/charting-library-docs/latest/customization) section for detailed information on how to customize the chart and its elements. ::: ### Change colors You can customize the colors of the chart to implement your corporate colors. The articles listed below explain how to change colors in certain cases: - [Chart Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides): specify default color of UI elements on the chart like scales and panes. - [Custom themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes): specify default color of UI elements outside the chart like dialogs and toolbars. ### Show/hide chart elements You can show/hide chart elements using [featuresets](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets). If there is no featureset for an element you want to hide, you can do it by adding your custom [CSS file](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_css_url). ### Show/hide gaps on the chart By default, the library hides periods with no trading activity to keep the chart continuous. In certain cases, such as analyzing low-liquidity instruments, it might be useful to represent these periods with whitespace gaps on the chart. To do this, use the [`inactivity_gaps`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsinactivity_gaps) featureset. Note that inactivity gaps are displayed **only within the trading session** of the instrument. For example, for a U.S. stock with a trading session from 09:00 to 16:00, inactivity outside of the session will not be displayed. import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; Chart without inactivity gaps Chart with inactivity gaps When [`inactivity_gaps`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsinactivity_gaps) is enabled, the corresponding checkbox appears in the *Chart settings* dialog, allowing users to toggle inactivity gaps on or off. The checkbox is disabled by default. Inactivity gaps toggle in Chart settings You can also use the [`inactivityGaps`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#inactivitygaps) method to control the gaps visibility through the API. ```javascript // Access the watched value for inactivity gaps visibility const inactivityGaps = widget.chart().inactivityGaps(); // Enable inactivity gaps display inactivityGaps.set(true); // Listen for changes inactivityGaps.subscribe((isVisible) => { console.log('Inactivity gaps visibility changed by the user:', isVisible); }); ``` ## Chart methods You can use the Chart API to interact with the chart after it is initialized. For example, you can subscribe to chart events, manage drawings and indicators, get information about a current configuration, perform Z-order operations, and more. All methods are listed in [IChartWidgetApi](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi). ### Subscribe to events You can subscribe to the chart events using methods like [`onDataLoaded`], [`onSymbolChanged`], [`onChartTypeChanged`], and others. For example, the code sample below specifies a time frame when an interval is changed using the [`onIntervalChanged`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#onintervalchanged) method. ```javascript widget.activeChart().onIntervalChanged().subscribe(null, (interval, timeframeObj) => timeframeObj.timeframe = { value: '12M', type: 'period-back' }); ``` ### Manage chart You can manage chart settings using methods like [`setSymbol`], [`setResolution`], [`resetData`], [`clearMarks`], and others. For example, the code sample below specifies a new [range](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossarydate-range) using the [`setVisibleRange`] method. ```javascript widget.activeChart().setVisibleRange( { from: Date.UTC(2023, 6, 12, 13, 30) / 1000 }, { applyDefaultRightMargin: true } ) ``` ### Execute action by ID The [`executeActionById`] method allows you to trigger specific actions programmatically through the API. This is useful for customizing UI or replicating built-in functionality with custom components. For example, you can replace built-in [top toolbar] buttons with custom ones or trigger actions for hidden UI elements. ```js widget.activeChart().executeActionById("chartReset"); ```
Click to reveal the list of the ChartActionId types. | Action ID | Purpose | |-|-| | `"chartProperties"` | Opens the *Chart settings* dialog. | | `"compareOrAdd"` | Opens or hides the [*Compare symbol*] dialog. | | `"scalesProperties"` | Opens or hides the *Chart settings* dialog. | | `"paneObjectTree"` | Opens the Object tree on the [widget bar]. | | `"insertIndicator"` | Opens or hides a dialog for adding [indicators][indicator-link]. | | `"symbolSearch"` | Opens the [*Symbol Search*] dialog. | | `"changeInterval"` | Opens a dialog for changing [resolution]. | | `"timeScaleReset"` | Resets the [time scale] to its default state. | | `"chartReset"` | Resets the [chart] view to its default state. | | `"seriesHide"` | Hides the selected series on the chart. | | `"studyHide"` | Hides the selected [indicator][indicator-link] on the chart. | | `"lineToggleLock"` | Enables or disables the *Lock/Unlock* button in the floating toolbar of the selected [drawing][drawing-link]. | | `"lineHide"` | Hides the selected [drawing][drawing-link] on the chart. | | `"scaleSeriesOnly"` | Enables or disables the *Scale price chart only* option for the [price scale]. | | `"drawingToolbarAction"` | Opens or hides the [drawing toolbar]. | | `"stayInDrawingModeAction"` | Enables or disables the *Stay in drawing* mode. | | `"hideAllMarks"` | Shows or hides all [marks] on the chart. | | `"showCountdown"` | Enables or disables *Countdown to bar close* option for the [price scale]. | | `"showSeriesLastValue"` | Shows or hides the series's last value on the [price scale]. | | `"showSymbolLabelsAction"` | Shows or hides the symbol's label on the [price scale]. | | `"showStudyLastValue"` | Shows or hides the indicator's last value on the [price scale]. | | `"showStudyPlotNamesAction"` | Shows or hides the indicator's label on the [price scale]. | | `"undo"` | Undoes the last applied action. | | `"redo"` | Redoes the last undone action. | | `"paneRemoveAllStudiesDrawingTools"` | Removes all [indicators][indicator-link] and [drawings][drawing-link] from the chart. | | `"showSymbolInfoDialog"` | Opens the *Security info* dialog. |
### Manage drawings and indicators You can create and manage drawings/indicators using methods like [`createStudy`], [`getAllShapes`], [`getShapeById`], [`removeAllStudies`], and others. For example, the code sample below adds the _Vertical line_ drawing on the chart using the [`createShape`] method. ```javascript widget.activeChart().createShape( { time: 1514764800 }, { shape: 'vertical_line' } ); ``` ### Getters You can get information about the current chart settings using methods like [`symbol`], [`chartType`], [`getVisibleRange`], and others. For example, the code sample below gets the current resolution using the [`resolution`] method. ```javascript console.log(widget.activeChart().resolution()); ``` You can also use chart methods to get objects that provide API to perform certain operations. For example: - [`getSeries`] returns [`ISeriesApi`] that allows you to interact with a [series](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryseries). - [`selection`] returns [`ISelectionApi`] that allows you to select drawings and indicators. - [`getTimezoneApi`] returns [`ITimezoneApi`] that allows you to manage the chart's time zone. [`onDataLoaded`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#ondataloaded [`onSymbolChanged`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#onsymbolchanged [`onChartTypeChanged`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#oncharttypechanged [`setSymbol`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#setsymbol [`setResolution`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#setresolution [`resetData`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#resetdata [`clearMarks`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#clearmarks [`setVisibleRange`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#setvisiblerange [`createStudy`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createstudy [`getAllShapes`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#getallshapes [`getShapeById`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#getshapebyid [`removeAllStudies`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#removeallstudies [`createShape`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createshape [`symbol`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#symbol [`chartType`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#charttype [`resolution`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#resolution [`getVisibleRange`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#getvisiblerange [`getSeries`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#getseries [`ISeriesApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISeriesApi [`selection`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#selection [`ISelectionApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISelectionApi [`getTimezoneApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#gettimezoneapi [`ITimezoneApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ITimezoneApi [`executeActionById`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#executeactionbyid [top toolbar]: https://www.tradingview.com/charting-library-docs/latest/ui_elements#top-toolbar [chart]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Chart [*Compare symbol*]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators#add-and-compare-new-series [drawing-link]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings [drawing toolbar]: https://www.tradingview.com/charting-library-docs/latest/ui_elements#drawing-toolbar [indicator-link]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators [marks]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Marks [price scale]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale [resolution]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution [*Symbol Search*]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search [time scale]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale [widget bar]: https://www.tradingview.com/charting-library-docs/latest/ui_elements#widget-bar URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend ================================================================================= # Legend Legend is a list of series and indicators at the top-left corner of any chart. Note that the legend position cannot be changed. Legend ## Configure legend In the *Chart settings → Status line* dialog, users can configure the legend. Chart settings ### Symbol logos If you want to display logos for symbols within the legend, follow the steps below: 1. Enable the [`show_symbol_logos`] and [`show_symbol_logo_in_legend`] featuresets. The *Logo* option appears in the settings dialog. 2. Provide URLs for symbols in the [`logo_urls`] property of the [`LibrarySymbolInfo`] object. Pass the object as a parameter to the callback of the [`resolveSymbol`] method. ### Open market status By default, the library displays the current [market status] as an icon within the legend for the main series of the chart. You can hide the market status by adding the [`display_market_status`] featureset to the [`disabled_features`] array. ### Title In the *Title* drop-down, users can select what title to display in the legend: - Description - Ticker - Ticker and description You can also set the title using the [Overrides API]. For example, the code sample below sets ticker as the legend title. ```js chartApi.applyOverrides({ "mainSeriesProperties.statusViewStyle.symbolTextSource": "ticker" }) ``` ### Last day change values :::info Last day change can be displayed in Trading Platform only as it requires quote data. ::: Last day change is a parameter represented by two values: daily change and percentage daily change. You should specify these values in the [`ch`] and [`chp`] properties of `DatafeedQuoteValues` and pass them to the library when it calls [`getQuotes`]. Last day change is displayed in *Data Window* on the right toolbar. You can also add this parameter to the chart legend using the [overrides]: ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... overrides: { "paneProperties.legendProperties.showLastDayChange": true, } }); ``` Users can toggle the *Last day change values* option in the *Chart settings* dialog to change the last day change visibility in the legend. This option is hidden by default. To display it, you should enable one of the following featuresets: - [`legend_last_day_change`] — adds the extra *Last day change values* option to the *Chart settings* dialog. - [`show_last_price_and_change_only_in_series_legend`] — adds the last day change to the legend and hides the OHLC values. Also, the extra *Last day change values* option appears in the *Chart settings* dialog. ### Resolution To disable resolution changing in the Legend, use the [`legend_inplace_edit`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetslegend_inplace_edit) featureset. If you want to completely remove the *Resolution* button from the *Legend*, use the [`hide_resolution_in_legend`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetshide_resolution_in_legend) featureset. ![Remove resolution from Legend](https://www.tradingview.com/charting-library-docs/img/no-resolution-legend.png) ## Visibility customization You can use [featuresets][featureset] or [overrides] to customize the legend's visibility such as hiding or displaying particular legend elements. The sections below describe customization via featuresets. For more information about override properties that affect the legend, refer to [Legend]. ### Hide legend You can hide the legend widget from the chart. To do this, include the `legend_widget` [featureset] in the [`disabled_features`] array. Disable legend ### Hide legend buttons You can hide all legend buttons by including the `edit_buttons_in_legend` in [`disabled_features`]. Besides, disabling `show_hide_button_in_legend`, `format_button_in_legend`, or `delete_button_in_legend` allows customizing particular legend buttons. For example, the *Settings* button is hidden in the image below. Hide settings button ### Hide context menu When right-clicking the legend, you can access the context menu. To disable this feature, include `legend_context_menu` in [`disabled_features`]. Hide context menu ## Price formatting Prices are formatted according to the `pricescale`, `minmov`, `minmove2`, `fractional`, and `variable_tick_size` properties specified in the [`LibrarySymbolInfo`] object. For more information, refer to the [Price format] section. You can also apply custom formatting using the [`numeric_formatting`] property of [Widget Constructor]. ```javascript new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"), symbol: "AAPL", interval: "1D", // highlight-next-line numeric_formatting: { decimal_sign: "," }, }) ``` In the code sample above, the comma separates the decimal/fractional part of the price. ![Numeric formatting](https://www.tradingview.com/charting-library-docs/img/legend-numeric-formatting.png) ## NaN values in legend If `NaN` values appear in the legend instead of the expected data, ensure that you have implemented the [`getQuotes`] and [`subscribeQuotes`] methods of the [Datafeed API]. This issue appears in [mobile applications] when running outside of tracking mode. Outside this mode, the legend shows only three values: the closing price, price change, and price change percentage. The library retrieves these values from the [`getQuotes`] request, otherwise, it displays `NaN`. Note that open, high, and low prices and indicator values are displayed in the tracking mode only. To activate this mode, users should long tap on the chart. A single tap on the chart exits this mode. ## Display delayed data information Follow the steps below to enable the *Data is delayed* section in the legend: 1. Add the [`display_data_mode`] featureset to the [`enabled_features`] array of the [Widget Constructor] object. 2. Provide the following properties in the [`LibrarySymbolInfo`] object. Pass this object as a parameter to the callback of the [`resolveSymbol`] method. - [`data_status`] – specify `"delayed_streaming"`. - [`delay`] – specify delay in seconds. The image below shows the *Data is delayed* section and the *D* icon in the legend. Data is delayed [`ch`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedQuoteValues#ch [`chp`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedQuoteValues#chp [Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api [`data_status`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#data_status [`delay`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#delay [`disabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features [`display_market_status`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#display_market_status [`enabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#enabled_features [featureset]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets [`display_data_mode`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#display_data_mode [`getQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#getquotes [Legend]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides#legend [`legend_last_day_change`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#legend_last_day_change [`LibrarySymbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo [`logo_urls`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#logo_urls [market status]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Status [mobile applications]: https://www.tradingview.com/charting-library-docs/latest/mobile_specifics [`numeric_formatting`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#numeric_formatting [overrides]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides [Overrides API]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides [Price format]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#price-format [`resolveSymbol`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol [`show_last_price_and_change_only_in_series_legend`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#show_last_price_and_change_only_in_series_legend [`show_symbol_logo_in_legend`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#show_symbol_logo_in_legend [`show_symbol_logos`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#show_symbol_logos [`subscribeQuotes`]: https://www.tradingview.com/charting-library-docs/latest/api/trading-platform-methods#subscribequotes [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Marks ================================================================================ # Marks Marks allow you to display some extra information like news, bar patterns, splits/dividends, and more [on the chart](#marks-on-the-chart) or [time scale](#marks-on-the-time-scale). Use the [`subscribe`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#subscribe) method to handle events raised when users interact with marks. You can also [refresh](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#refreshmarks) and [clear](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#clearmarks) marks using the chart methods. ## Marks on the chart Marks on the chart are circles that are attached to bars and contain a character inside. You can customize the circle size and color. If you want to display two characters (like 'ED', 'AB', 'CD', etc.), you should enable the [`two_character_bar_marks_labels`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets) featureset. One bar can have several marks. When a user clicks on the mark, the tooltip appears. The tooltip can only contain plain text. HTML code is not supported. ![Marks](https://www.tradingview.com/charting-library-docs/img/marks.png) Marks are requested from your datafeed if you set [`supports_marks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#supports_marks) to `true`. The library calls [`getMarks`](https://www.tradingview.com/charting-library-docs/latest/api/additional-methods#getmarks) or requests [/marks](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDFmarks) to get mark data for the visible data range. ## Marks on the time scale Marks on the time scale are figures above the time scale. Each mark has a character inside and a pop-up tooltip with information strings. The tooltip does not support HTML code. You can specify a time scale mark shape using the [`shape`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TimescaleMark#shape) property. Images can be displayed within time scale marks by providing an image URL in the [`imageUrl`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TimescaleMark#imageurl) property. ![Timescale marks](https://www.tradingview.com/charting-library-docs/img/timescale_marks.png) Time scale marks are requested from your datafeed if you set [`supports_timescale_marks`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#supports_timescale_marks) to `true`. The library calls [`getTimescaleMarks`](https://www.tradingview.com/charting-library-docs/latest/api/additional-methods#gettimescalemarks) or requests [/timescale_marks](https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDFtimescale-marks) to get mark data for the visible data range. URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Panes-And-Scales-Behavior ==================================================================================================== # Panes and Scales Behavior ## Panes and scales behavior Here is the detailed description of how panes and scales work when creating a study. First of all, all studies are divided into 2 groups: "price" studies and "non-price" studies. Examples of price studies are "moving average" and "bollinger bands". The result of such studies has the same dimension as their input source. Price studies are placed by default on the same pane as their source and pinned to the same price scale. By contrast, the result of non-price studies has a different dimension. For example, Stochastic always returns values from 0 to 100. Non-price studies are placed by default to a separate pane. * You can change the default pane of the study using `forceOverlay`. If it's set to true, the study is placed on the main pane (pane with the main series). This option doesn't affect the default price scale. This flag is applied to non-price studies only. There is no way to place a price study on a separate pane by default at this time. * You can change the default price scale using `priceScale`. If it is not set, then the chart behaves as described above. `no-scale` sets "No scale" (full-screen) mode for the study. `new-left` and `new-right` always places the study on a new price scale, even while placing a price study. `as-series` option always places the study on the same price scale that the main series are attached to. The following table illustrates this | Value | Price Study or Non-Price Study with force_overlay=true | Non-Price Study with force_overlay=false | |---|---|---| |new-left|place on a new left scale of the main pane|place on a new left scale of a new pane |new-right|place on a new right scale of the main pane|place on a new right scale of a new pane |no-scale|place as "no scale" on the main pane|place as "no scale" on a new pane |as-series|place on the same price scale as the main series|place on a separate pane on the right price scale URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale ====================================================================================== # Price scale **Price scale** (or price axis) is a vertical scale on the right or left side of the chart that maps prices to coordinates and vice versa. ![Price scale](https://www.tradingview.com/charting-library-docs/img/price-scale.png) ## UI interactions This section describes how users can interact with the price scale. ### Adding price scale Users can add new price scales via the [*Compare symbol*] dialog by selecting *New price scale*. ![Add new price scale](https://www.tradingview.com/charting-library-docs/img/add-new-price-scale.gif) :::info The library allows users to have up to eight price scales on the chart. However, only one price scale can be displayed on [mobile applications]. ::: ### Changing position Users can place the price scale on the left or right side of the chart. To do this, they should select the *Move scale to left/right* button in the context menu of the price scale. ![Change price scale position](https://www.tradingview.com/charting-library-docs/img/move-scale-to-left.gif) You can also programmatically [change a price scale position](#change-price-scale-position). ### Pinning to scale Users can select *Pin to scale* in the symbol/indicator settings to attach symbols/indicators to the price scale. ![Pin to scale](https://www.tradingview.com/charting-library-docs/img/pin-to-scale.gif) You can also programmatically add a new indicator and [attach it to a new price scale](#attach-indicators-to-price-scale). ### Inverting price scale Users can invert the scale via *Invert scale* in the context menu of the price scale. When the option is enabled, the price increase is shown from top to bottom. ![Invert price scale](https://www.tradingview.com/charting-library-docs/img/invert-price-scale.gif) ### Resetting price scale Users can reset the price scale when it is in a non-default state. Note that the *Reset price scale* option will not appear in the context menu with adjustments such as moving the scale to the left or switching to logarithmic mode. ![Reset price scale](https://www.tradingview.com/charting-library-docs/img/reset-price-scale.gif) ### Quick trading :::info This feature is only available in [Trading Platform]. ::: By default, the price scale includes a *Plus* button. When users click this button, a context menu opens, allowing them to quickly access trading options. Note that this menu will be empty unless you implement the [Broker API]. ![Plus button on the price scale](https://www.tradingview.com/charting-library-docs/img/plus-button-price-scale.gif) To detect when the user clicks the *Plus* button, you can listen for the [`onPlusClick`] event. You can disable this button by adding the [`chart_crosshair_menu`] featureset to the [`disabled_features`] array. ## Style and default settings ### Customize price scale appearance You can customize the appearance of the price scale using the [Overrides API]. For example, the code sample below changes the text color and font size of the price and [time] scales. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-start overrides: { "scalesProperties.textColor": "#FF0000", "scalesProperties.fontSize": 14, } // highlight-end }) ``` Refer to the [Scale colors and fonts] section to see the full list of the overrides properties. ### Change price scale position You can change the position of the price scale attached to the main series. When creating a chart, use the [`priceScaleSelectionStrategyName`] property of the [Overrides API]. For example, the code sample below changes the price scale position to the left. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-start overrides: { "priceScaleSelectionStrategyName": "left", } // highlight-end }) ``` If the chart is already created, use the [`changePriceScale`] method of the [`ISeriesApi`] interface. For example, the code sample below also changes the price scale position of the main series to the left. ```js widget.onChartReady(() => { widget.activeChart().getSeries().changePriceScale("new-left"); }); ``` ### Attach indicators to price scale You can attach [indicators] to the price scale. To do this, specify the [`priceScale`] property in the `options` parameter of the [`createStudy`] method. For example, the code sample below creates a _Volume_ indicator and attaches it to a new price scale on the left. ```js widget.onChartReady(() => { widget.activeChart().createStudy('Volume', false, false, undefined, undefined, { "priceScale": "new-left" }); }); ``` ### Hide price scale If you want to hide the price scale when all series or indicators attached to it are hidden, enable the [`hide_price_scale_if_all_sources_hidden`] featureset. ### Hide settings button The scale settings button is available directly below the price scale. If users have more than one price scale on the chart, a letter will be displayed in place of the settings button. Users should click the letter that indicates the scale to open the corresponding scale settings. If you want to hide the settings button, disable the [`main_series_scale_menu`] featureset. ### Add labels You can add labels to the price scale to display additional information like a symbol name, bid/ask prices, indicators, and more. For example, the code sample below adds a symbol name label on the price scale. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-start overrides: { "scalesProperties.showSymbolLabels": true, } // highlight-end }) ``` Refer to the [Labels on the scale] section to see the full list of the overrides properties. ### Enable auto scaling You can enable auto scaling using the [`setAutoScale`] method of the [Price Scale API]. ```js widget.onChartReady(() => { const priceScale = widget.activeChart().getPanes()[0].getMainSourcePriceScale(); // highlight-next-line priceScale.setAutoScale(true) }); ``` ### Set mode You can set the price scale mode using the [Overrides API] or [Price Scale API]. However, you cannot change the price scale mode using the [`applyOverrides`] method. When creating a chart, use [`overrides`] to change the price scale mode. For example, the code sample below enables the percentage mode. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-start overrides: { "mainSeriesProperties.priceAxisProperties.percentage": true, } // highlight-end }) ``` Refer to the [Price scale mode] section to see the full list of the overrides properties. If the chart is already created, you can change the price scale mode only using the [`setMode`] method of the [Price Scale API]. For example, the code sample below also enables the percentage mode. ```js widget.onChartReady(() => { const priceScale = widget.activeChart().getPanes()[0].getRightPriceScales()[0]; // highlight-next-line priceScale.setMode(2); }); ``` ### Set visible price range If you want to set a visible price range of the price scale, you can use the [`setVisiblePriceRange`] method of the [Price Scale API]. For example, the code sample below sets the visible price range between 140 and 170. ```js widget.onChartReady(() => { const priceScale = widget.activeChart().getPanes()[0].getRightPriceScales()[0]; // highlight-next-line priceScale.setVisiblePriceRange({ "from": 140, "to": 170 }); }); ``` ## Price formatting The [`format`][format] property in the [`LibrarySymbolInfo`] object determines how prices appear on the scale. Specifying the `volume` format displays prices as decimals in thousands, millions, billions, or trillions. If you specify the `price` format, the prices will be formatted in decimal or fractional format according to the `minmov`, `pricescale`, `minmove2`, `fractional`, `variablemintick` properties. Refer to the [Price Format] section for more information. You can also [change the decimal sign](#change-decimal-sign) for the prices or [implement your custom logic](#use-custom-formatting) of the price formatting. ### Change decimal sign You can apply custom formatting using the [`numeric_formatting`] property of the [Widget Constructor]. For example, the code sample below sets a comma to separate the decimal/fractional part of the prices. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-next-line numeric_formatting: { decimal_sign: "," }, }) ``` The image below shows that the decimal parts of the prices on the price scale and the legend are separated with a comma. ![Numeric formatting](https://www.tradingview.com/charting-library-docs/img/price-scale-numeric-formatting.png) ### Use custom formatting You can adjust the display format of price values using the [`custom_formatters`] property of the [Widget Constructor]. For example, the code sample below defines a custom price formatting function for the `volume` [format type][format]. This function replaces numerical zeros with letter representations like billions (B), millions (M), and thousands (K). ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-start custom_formatters: { priceFormatterFactory: (symbolInfo, minTick) => { if (symbolInfo === null) { return null; } if (symbolInfo.format === 'volume') { return { format: (price, signPositive) => { if (price >= 1000000000) { return `${(price / 1000000000).toFixed(3)}B`; } if (price >= 1000000) { return `${(price / 1000000).toFixed(3)}M`; } if (price >= 1000) { return `${(price / 1000).toFixed(3)}K`; } return price.toFixed(2); }, }; } return null; // The default formatter will be used. }, } // highlight-end }) ``` ## Symbol currency ### Display symbol currency To display symbol currency on the price scale, follow the steps below. 1. Enable the [`pricescale_currency`] featureset to show the *Currency* menu in *Chart Settings → Scales*. 2. Assign a currency code to the [`currency_code`] property of the [`LibrarySymbolInfo`] object. Note that the currency code must be a three-letter string in the [ISO 4217] format. ### Enable currency conversion The library provides a drop-down menu for selecting the currency in which the symbol is displayed. To switch between currencies, you should implement the currency conversion. Follow the steps below to enable the currency conversion. 1. Enable the [`pricescale_currency`] featureset to show the *Currency* menu in *Chart Settings → Scales*. 2. Add the [`currency_code`] and [`original_currency_code`] properties to the [`LibrarySymbolInfo`] object. Note that the currency code must be a three-letter string in the [ISO 4217] format. 3. Provide a list of available currencies in the [`currency_codes`] property of the [`DatafeedConfiguration`] object. 4. Pass [`currencyCode`] to the [`resolveSymbol`] method. 5. Implement the conversion algorithm. The conversion algorithms can vary, but you can choose one from the following two: - **Constant currency rate algorithm**. With this approach, you retrieve the current currency exchange rate and multiply each bar by this value. However, this approach may yield inaccurate results for historical bars if the exchange rate has fluctuated significantly over time. - **Corresponding currency rate algorithm**. With this approach, you request historical currency exchange rates from the server and then multiply each bar by its corresponding currency rate. :::info Implementing either of these algorithms is straightforward when all symbols and Forex rates share the same time zone. However, if time zones differ, you need to find an appropriate way to accurately match the corresponding rate to each bar. ::: After this, users can view symbol prices in their preferred currency. To switch to a different currency, users can click the currency drop‑down menu and choose another option. When a new currency is selected, the `resolveSymbol` method is called with the same `symbolInfo` but with an added `currency_code` property indicating the chosen currency. Hide context menu [`applyOverrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#applyoverrides [`changePriceScale`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISeriesApi#changepricescale [`chart_crosshair_menu`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#chart_crosshair_menu [`createStudy`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createstudy [`currencyCode`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SymbolResolveExtension#currencycode [`currency_code`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#currency_code [`currency_codes`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#currency_codes [`custom_formatters`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_formatters [`DatafeedConfiguration`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration [`disabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features [`hide_price_scale_if_all_sources_hidden`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#hide_price_scale_if_all_sources_hidden [`ISeriesApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ISeriesApi [`LibrarySymbolInfo`]: https://www.tradingview.com/charting-library-docs/api/interfaces/Charting_Library.LibrarySymbolInfo [`main_series_scale_menu`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#main_series_scale_menu [`numeric_formatting`]: https://www.tradingview.com/charting-library-docs/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#numeric_formatting [`onPlusClick`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap#onplusclick [`original_currency_code`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#original_currency_code [`overrides`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#overrides [`priceScale`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CreateStudyOptions#pricescale [`pricescale_currency`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#pricescale_currency [`priceScaleSelectionStrategyName`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartPropertiesOverrides#pricescaleselectionstrategyname [`resolveSymbol`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol [`setAutoScale`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IPriceScaleApi#setautoscale [`setMode`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IPriceScaleApi#setmode [`setVisiblePriceRange`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IPriceScaleApi#setvisiblepricerange [Broker API]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts#broker-api [*Compare symbol*]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators#add-and-compare-new-series [format]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#format [indicators]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators [ISO 4217]: https://www.iso.org/iso-4217-currency-codes.html [Labels on the scale]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides#labels-on-the-scale [mobile applications]: https://www.tradingview.com/charting-library-docs/latest/mobile_specifics [Overrides API]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides [Price Format]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbology#price-format [Price Scale API]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IPriceScaleApi [Price scale mode]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides#price-scale-mode [Scale colors and fonts]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides#scale-colors-and-fonts [time]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Snapshots ==================================================================================== # Snapshots ## Overview The library allows users to take chart snapshots via buttons located on the top toolbar. By default, the menu contains two options: *Download image* and *Copy image*. You can [extend this menu](#enable-additional-menu-options) to also include the *Copy link*, *Open in new tab*, and *Tweet image* options. Take snapshot menu ### Snapshot storage Snapshots taken through *Copy link*, *Open in new tab*, and *Tweet image* options are stored **on your servers**. The server URL used on the [TradingView demo website] only works on TradingView domains. For details on how to set up your own server, see our guide to [implementing a snapshot server][snapshot-server-guide]. ## Enable additional menu options You can extend the default snapshots menu with the *Copy link*, *Open in new tab*, and *Tweet image* options. To enable them, follow the steps below. 1. Implement your own server for storing snapshots. For more information, refer to the [Implement snapshots server][snapshot-server-guide] guide. - Your server should have an endpoint that accepts `POST` requests and returns saved image URLs to the library. - The data storage period is not limited in time. You have to implement a policy on your end. 2. Specify the [`snapshot_url`] property in your [Widget Constructor]. ```javascript const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-next-line snapshot_url: "https://myserver.com/snapshot", }) ``` Note that you cannot add custom options to this menu. Only the five predefined ones are available. However, you can [remove any of these options](#remove-button-options) if you don’t need them. ## Remove button options Depending on what you are interested in showing to your end users, you may want to hide some options. To do this, use custom CSS defined within the [`custom_css_url`] property of the [Widget Constructor]. The example below shows how to remove the *Tweet image* option from the menu. ```js // highlight-start // Custom CSS properties var customCSS = `div[data-name="open-image-in-new-tab"],div[data-name="tweet-chart-image"],div[data-name="copy-link-to-the-chart-image"] { display: none; } `; function initOnReady() { const cssBlob = new Blob([customCSS], { type: "text/css", }); const cssBlobUrl = URL.createObjectURL(cssBlob); // highlight-end const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", snapshot_url: "https://myserver.com/snapshot", // highlight-start custom_css_url: cssBlobUrl, // highlight-end }) } ``` ## Hide button Disable the [`header_screenshot`] featureset to hide the snapshot button. ```javascript const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", snapshot_url: "https://myserver.com/snapshot", // highlight-next-line disabled_features: ["header_screenshot"], }) ``` ## Display trading lines If you want snapshots to include orders, positions, and executions, enable the [`snapshot_trading_drawings`] featureset. ```javascript const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", snapshot_url: "https://myserver.com/snapshot", // highlight-next-line enabled_features: ["snapshot_trading_drawings"], }) ``` ## Implement your logic If you want to implement your logic for taking snapshots, use the [`takeClientScreenshot`] method. This method creates a snapshot of the chart and returns it as a canvas. You can then take the canvas element and create an image from it. The code sample below saves a snapshot as a PNG. ```js async function saveChartToPNG() { const screenshotCanvas = await widget.takeClientScreenshot(); const linkElement = document.createElement('a'); linkElement.download = 'screenshot'; linkElement.href = screenshotCanvas.toDataURL(); // Alternatively, use `toBlob` which is a better API linkElement.dataset.downloadurl = ['image/png', linkElement.download, linkElement.href].join(':'); document.body.appendChild(linkElement); linkElement.click(); document.body.removeChild(linkElement); } saveChartToPNG(); // Call the screenshot function ``` Additionally, you can configure snapshot parameters listed in [`ClientSnapshotOptions`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ClientSnapshotOptions). To do this, specify the desired parameters and pass them to [`takeClientScreenshot`]. For example, you can hide indicators from the legend with `hideStudiesFromLegend`: ```javascript const screenshotCanvas = await widget.takeClientScreenshot({ hideStudiesFromLegend: true }); ``` [`custom_css_url`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_css_url [`header_screenshot`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#header_screenshot [snapshot-server-guide]: https://www.tradingview.com/charting-library-docs/latest/tutorials/implement-snapshots-server [`takeClientScreenshot`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#takeclientscreenshot [TradingView demo website]: https://charting-library.tradingview-widget.com/ [`snapshot_trading_drawings`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#snapshot_trading_drawings [`snapshot_url`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#snapshot_url [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Search ======================================================================================== # Symbol Search The *Symbol Search* is a button on the top toolbar that opens a dialog containing a search box. *Symbol Search* is used to search and display instruments that match the entered full or partial instrument name. Symbol Search ## Display symbols The way symbols appear in the *Symbol Search* depends on how you provide the data. - If you use the built-in [UDF adapter], you can either implement a symbol [group request] or a [single request]. The first method is suitable when you have a short list of symbols. - If you implement a custom datafeed via [Datafeed API], use the [`searchSymbols`] method. ## Hide Symbol Search If you do not want users to change the displayed instrument, you can hide the *Symbol Search*. To do this, include the `header_symbol_search` [featureset] in the [`disabled_features`] array. ## Open/close Symbol Search To programmatically open the Symbol Search, call the [`executeActionById`] method with the `symbolSearch` action ID. ```js widget.activeChart().executeActionById("symbolSearch"); ``` To programmatically close the Symbol Search, call the [`closePopupsAndDialogs`] method. This method closes any active dialog on the chart. ```js widget.closePopupsAndDialogs(); ``` ## Set request delay If you want to reduce the number of search requests when users enter symbol names in the search box, you can set a request delay in milliseconds. To do this, use the [`symbol_search_request_delay`] property of the [Widget Constructor]. You can check out the [Widget Constructor tutorial][tutorial-request-delay] on YouTube for an implementation example. ## Override symbol names Sometimes symbol names can be too long/short or implicitly reflect the meaning of the symbol name. In these cases, you can use the [`symbol_search_complete`] property of the [Widget Constructor]. This property overrides the entered symbol name with whatever human-friendly form you want. The overridden symbol name will then be requested by your server and plotted. You can check out the [Widget Constructor tutorial][tutorial-symbol-search-complete] on YouTube for an implementation example. ## Case-insensitive search By default, all letters that users type are displayed in uppercase. To allow case-insensitive search, disable the [`uppercase_instrument_names`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsuppercase_instrument_names) featureset. ## Filters When users click *Symbol Search*, the search dialog appears. The widget has predefined optional filters by symbol type and exchange. To use them, pass a [`DatafeedConfiguration`] object with the [`symbols_types`] and [`exchanges`] properties as a parameter to the callback of the [`onReady`] method. ## Symbol grouping The search dialog can display symbols grouped by a root name. For example, to group futures `ABC2023`, `ABC2024`, and `ABC2025` by the root name `ABC`, provide a regular expression to the library. The expression should consist of two capture groups, where the first is the root name and the second is the expiration date. To enable grouping, provide an object with regular expressions to parse symbol names in the [`symbols_grouping`] property of the [`DatafeedConfiguration`] interface. Then pass the `DatafeedConfiguration` object as a parameter to the callback of the [`onReady`] method. ## Display logos If you want to display logos for symbols and exchanges within the search results, follow the steps below: 1. Enable the corresponding [featuresets][featureset]: `show_symbol_logos` and `show_exchange_logos`. 2. Provide URLs for symbols and exchanges in the [`logo_urls`] and [`exchange_logo`] properties of the [`SearchSymbolResultItem`] object. Pass the object as a parameter to the callback of the [`searchSymbols`] method. ## Enable spread operators **Spread operators** are operators that allow comparison between a financial instrument, such as a stock, and an additional variable, such as another financial instrument or a numerical value. import SpreadOperatorsWarning from './_spread-operators-warning.mdx'; To display spread operators in the *Symbol Search*, include the [`show_spread_operators`] featureset in the [`enabled_features`] array. ![Spread operators in the Search Symbol](https://www.tradingview.com/charting-library-docs/img/spread-operators-in-symbol-search.png) [`closePopupsAndDialogs`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#closepopupsanddialogs [Datafeed API]: https://www.tradingview.com/charting-library-docs/latest/api/datafeed-api [`DatafeedConfiguration`]: https://www.tradingview.com/charting-library-docs/api/interfaces/Charting_Library.DatafeedConfiguration [`disabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features [`enabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#enabled_features [`exchange_logo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SearchSymbolResultItem#exchange_logo [`exchanges`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#exchanges [`executeActionById`]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Chart#execute-action-by-id [featureset]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets [`logo_urls`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SearchSymbolResultItem#logo_urls [`onReady`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#onready [`searchSymbols`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#searchsymbols [`SearchSymbolResultItem`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SearchSymbolResultItem [`show_spread_operators`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#show_spread_operators [group request]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF#symbol-group-request [single request]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF#symbol-search [`symbol_search_complete`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#symbol_search_complete [`symbol_search_request_delay`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#symbol_search_request_delay [`symbols_grouping`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#symbols_grouping [`symbols_types`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.DatafeedConfiguration#symbols_types [tutorial-request-delay]: https://www.youtube.com/watch?v=bdvmM3FNnSY&t=727s [tutorial-symbol-search-complete]: https://www.youtube.com/watch?v=bdvmM3FNnSY&t=3606s [UDF adapter]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Symbol-Status ======================================================================================== # Symbol Status :::caution This page has moved here: [Market Status](https://www.tradingview.com/charting-library-docs/latest/ui_elements/market-status) ::: URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale ===================================================================================== # Time scale **Time scale** (or time axis) is a horizontal scale at the bottom of the chart that displays the time of bars. Time scale ## Time range Time (date) range is a period of time that is currently visible on the chart canvas. This range changes when users scale or scroll the chart. You can specify a certain range using the [`setVisibleRange`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#setvisiblerange) method. ```javascript widget.activeChart().setVisibleRange( { from: 1420156800, to: 1451433600 } ) ``` If the library cannot fit the specified range within the canvas, which may happen on small screens, it will render as much data as possible. In this case, the `to` parameter is considered more prior than `from`. To ensure the full range is displayed, consider decreasing the [bar spacing](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossarybar-spacing) to a smaller number, which allows more data to fit within the available space. You can adjust bar spacing using the [`min_bar_spacing`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TimeScaleOptions#min_bar_spacing) option or the [`setBarSpacing`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ITimeScaleApi#setbarspacing) method. ```javascript time_scale: { min_bar_spacing: 0.01 }, ``` :::caution Using [`min_bar_spacing`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TimeScaleOptions#min_bar_spacing) forces the library to perform more calculations. This may lead to the following issues: - The chart UI may update slowly because the browser thread is blocked. - The browser may use excessive memory or even run out of memory due to the large number of bars on the screen. Use this option carefully and only when necessary. ::: ## Time scale API You can manage the time scale using the Time scale API. For example, you can set a specific right margin or detect when the chart has been zoomed in/out. Refer to [`ITimeScaleApi`] for more information. ## Customize scale appearance You can customize the appearance of the time scale using the [Overrides API]. For example, the code sample below changes the text color and font size of the time and [price] scales. ```js const datafeed = new Datafeeds.UDFCompatibleDatafeed("https://demo-feed-data.tradingview.com"); new TradingView.widget({ container: "chartContainer", locale: "en", library_path: "charting_library/", datafeed: datafeed, symbol: "AAPL", interval: "1D", // highlight-start overrides: { "scalesProperties.textColor": "#FF0000", "scalesProperties.fontSize": 14, } // highlight-end }) ``` Refer to the [Scale colors and fonts] section to see the full list of the overrides properties. ## Date and time formatting You can adjust the display format of date and time values using the [`custom_formatters`] property of the [Widget Constructor]. Check out the [Widget Constructor tutorial][tutorial-custom-formatters] on YouTube for an implementation example. ## Time frame toolbar Time frames are time period buttons displayed at the bottom-left corner of the chart. When users switch a time frame, it causes the following changes to satisfy the selected time frame: 1. The chart [resolution] changes. 2. The bars scale horizontally to cover the entire requested date/time range. For example, clicking `1Y` makes the chart switch the resolution to `1W` and scale it accordingly to display weekly bars for the entire year. Each time frame has its default chart resolution: | Time frame | Chart resolution | |:-:|:-:| | 5Y | W | | 1Y | W | | 6M | 120 | | 3M | 60 | | 1M | 30 | | 5D | 5 | | 1D | 1 | ### Time frame customization You can customize displayed time frames using the [`time_frames`] property of the [Widget Constructor]. Note that time frames that require resolutions that are unavailable for a particular symbol will be hidden. You can also check out the [Widget Constructor tutorial][tutorial-time-frames] on YouTube for an implementation example. ### Programmatic time frame setting If you want to programmatically set the time frame for the active chart, use the [`setTimeFrame`] method of the [`IChartWidgetApi`]. For example, the following code snippet applies the `1Y` time frame, which is the same as when users click `1Y` at the bottom of the chart: ```js const widget = new TradingView.widget(/* Widget properties */); widget.onChartReady(() => { const chart = widget.chart(); chart.setTimeFrame({val: {type: 'period-back', value: '12M'}, res: '1W'}); }); ``` ## Extended time scale You can enable indicators to extend the time scale. This allows you to create custom indicators that show bars at a higher resolution than the main series. Refer to [Extending the time scale] for more information. ## Extended sessions If you want to display extended sessions for some symbols, refer to the [Extended sessions] article for more information. [`custom_formatters`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_formatters [Extended sessions]: https://www.tradingview.com/charting-library-docs/latest/connecting_data/Extended-Sessions [Extending the time scale]: https://www.tradingview.com/charting-library-docs/custom_studies/Studies-Extending-The-Time-Scale [`IChartWidgetApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi [`ITimeScaleApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ITimeScaleApi [Overrides API]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Overrides [price]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Price-Scale [resolution]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Resolution [Scale colors and fonts]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides#scale-colors-and-fonts [`setTimeFrame`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#settimeframe [`time_frames`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#time_frames [tutorial-custom-formatters]: https://www.youtube.com/watch?v=bdvmM3FNnSY&t=1466s [tutorial-time-frames]: https://www.youtube.com/watch?v=bdvmM3FNnSY&t=2328s [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Toolbars =================================================================================== # Toolbars ## Overview The term **toolbars** relates to several [UI elements]. - [Top toolbar] is a primary bar at the top of the chart that contains elements such as Symbol Search, Indicators, and Resolutions. - [Drawing toolbar] is a left-side bar that contains drawings. - [Widget bar] is a right-side bar available in [Trading Platform] only. This toolbar displays the Watchlist, Details, and News widgets. - [Time frame toolbar] is a bottom bar that displays time period buttons. :::info For detailed information on customizing specific toolbar elements, refer to dedicated sections of the [UI elements] and [Featuresets] articles. ::: ## Custom buttons in top toolbar You can add your own buttons to the top toolbar using the following methods: - [`createButton`] — creates a customizable button. This method provides maximum flexibility since it returns an HTML element (if `useTradingViewStyle` is `false`), which you can customize in any way you want. For example, you can create a checkbox or a dropdown menu. - [`createDropdown`] — creates a dropdown menu. Use this method for a simpler dropdown menu when you don't require custom HTML. Note that other toolbars do not currently support custom button placement using these methods. :::tip Check out the [How to add custom button to top toolbar] guide for a hands-on understanding. ::: ### Accessible buttons Custom buttons, created using the [`createButton`] overload with `useTradingViewStyle` set to `true`, support [accessible keyboard navigation]. ## Change toolbar style The library offers two ways to change the toolbar style: - [Using custom themes API](https://www.tradingview.com/charting-library-docs/latest/customization/styles/custom-themes) - [Using CSS color themes](https://www.tradingview.com/charting-library-docs/latest/customization/styles/CSS-Color-Themes) [accessible keyboard navigation]: https://www.tradingview.com/charting-library-docs/latest/getting_started/accessibility#keyboard-navigation [Drawing toolbar]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings [Featuresets]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets [How to add custom button to top toolbar]: https://www.tradingview.com/charting-library-docs/latest/tutorials/add-custom-button-to-top-toolbar [Time frame toolbar]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale#time-frame-toolbar [Top toolbar]: https://www.tradingview.com/charting-library-docs/latest/ui_elements#top-toolbar [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [UI elements]: https://www.tradingview.com/charting-library-docs/latest/ui_elements [Widget bar]: https://www.tradingview.com/charting-library-docs/ui_elements/ui_elements#widget-bar [`createButton`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#createbutton [`createDropdown`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#createdropdown URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/context-menu ======================================================================================= # Context menu The **context menu** is a dialog that users access through a right-mouse-click or ellipsis menu (…). ## Override context menu You can override the default items in the context menu in two ways: - [using Widget Constructor](#using-widget-constructor) - [using API](#using-api) :::info Both approaches override all context menus. If you only want to override specific menus, you should implement your own filtering logic for that particular use case. ::: ### Using Widget Constructor You can register a custom function for overriding default items when the context menu is created. To do this, use the [`context_menu`] property of the [Widget Constructor]. `context_menu` has two properties: - [`items_processor`] allows you to modify the items displayed in the context menu. For example, you can provide a function that adds new items and removes or reorders existing ones. The library calls this function each time users want to display the context menu. This function should return an array of items to display. - [`renderer_factory`] allows you to override the default renderer for the context menu so you can adjust existing menu items. :::tip You can also use the `context_menu` property to retrieve a list of items in the menu. Check out the [Widget Constructor tutorial] on YouTube for an implementation example. ::: #### Examples The code sample below shows how to add a new item to the context menu using [`items_processor`]. The code sample below shows how to adjust existing items of the context menu using [`renderer_factory`]. #### Determine evoked menu Both [`items_processor`] and [`renderer_factory`] provide menu names and the associated IDs for items like series, drawings, indicators, orders, and positions. You can determine which menu was triggered using the properties of the [`CreateContextMenuParams`] interface. ### Using API If you want to change the menu dynamically, use the [`onContextMenu`] method. ```js widget.onChartReady(function() { widget.onContextMenu(function(unixtime, price) { return [{ position: "top", text: "First top menu item, time: " + unixtime + ", price: " + price, click: function() { alert("First item clicked."); } }, { text: "-", position: "top" }, // Adds a separator between buttons { text: "-Paste" }, // Removes the existing item from the menu { position: "top", text: "Second top menu item 2", click: function() { alert("Second item clicked."); } }, { position: "bottom", text: "Bottom menu item", click: function() { alert("Third item clicked."); } }]; }); }); ``` [`context_menu`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#context_menu [`CreateContextMenuParams`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CreateContextMenuParams [`items_processor`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ContextMenuOptions#items_processor [`onContextMenu`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#oncontextmenu [`renderer_factory`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ContextMenuOptions#renderer_factory [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor [Widget Constructor tutorial]: https://www.youtube.com/watch?v=bdvmM3FNnSY&t=3715s URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/Drawings-List ================================================================================================= # Drawings List This article lists all available [drawings](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings) in the library and available actions with them. ## Tools ### Trend Line Tools * Trend Line * Arrow * Ray * Info Line * Extended Line * Trend Angle * Horizontal Line * Horizontal Ray * Vertical Line * Cross Line * Parallel Channel * Regression Trend * Flat Top/Bottom * Disjoint Channel * Anchored VWAP ### Gann and Fibonacci Tools * Fib Retracement * Trend-Based Fib Extension * Pitchfork * Schiff Pitchfork * Modified Schiff Pitchfork * Inside Pitchfork * Fib Channel * Fib Time Zone * Gann Box * Gann Square Fixed * Gann Square * Gann Fan * Fib Speed Resistance Fan * Trend-Based Fib Time * Fib Circles * Pitchfan * Fib Spiral * Fib Speed Resistance Arcs * Fib Wedge ### Geometric Shapes * Brush * Highlighter * Rectangle * Circle * Ellipse * Path * Curve * Polyline * Triangle * Rotated Rectangle * Arc * Double Curve ### Annotation Tools * Text * Anchored Text * Note * Anchored Note * Signpost * Callout * Comment * Price Label * Price Note * Arrow Marker * Arrow Mark Left * Arrow Mark Right * Arrow Mark Up * Arrow Mark Down * Flag Mark ### Patterns * XABCD Pattern * Cypher Pattern * ABCD Pattern * Triangle Pattern * Three Drives Pattern * Head and Shoulders * Elliot Impulse Wave (12345) * Elliot Triangle Wave (ABCDE) * Elliot Triple Combo Wave (WXYXZ) * Elliot Correction Wave (ABC) * Elliot Double Combo Wave (WXY) * Cyclic Lines * Time Cycles * Sine Line ### Predictions and Measurement Tools * Long Position * Short Position * Forecast * Date Range * Price Range * Date and Price Range * Bars Pattern * Ghost Feed * Projection * Fixed Range Volume Profile ### Icons Icons ### Stickers Stickers ### Emojis The library uses [Twemoji v13.0](https). Refer to [Twemoji Cheatsheet](https) for the list of emojis. ## Actions * Measure * Zoom In * Magnets * Weak Magnet * Strong Magnet * Stay in Drawing Mode * Lock All Drawing Tools * Hide All Drawings * Remove X Drawings URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api ================================================================================================ # Drawings API This article describes how to manage drawings using the API. :::info Methods listed in this article are part of the [`IChartWidgetApi`] interface. To call these methods, you should use an `IChartWidgetApi` instance. To do this, use either the [`chart`] or [`activeChart`] method. For more information, refer to [Widget methods](https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methods). ::: ## Create drawings When you create a drawing, you need to specify its position on the chart. The position can be determined with either one or multiple points. To create a drawing, use one of the methods below depending on the drawing type and number of points it requires. ### createShape The [`createShape`] method allows you to create a drawing which position on the chart can be determined by only one point. For example, you can create arrows, vertical or horizontal lines, icons, and more. To do this, call `createShape` and pass information about the point and drawing as parameters. #### Point You should specify one of the objects below to provide information about the point. - [`StickedPoint`]. A point is determined by an OHLC price on a bar at a specified timestamp. - [`PricedPoint`]. A point is determined by a price and timestamp. - [`TimePoint`]. A point is determined by a timestamp. When you specify a drawing point, use timestamps that have associated data points on the chart. Otherwise, the library adjusts the time value to the nearest appropriate point. For example, the current chart resolution is one hour, and the following bars are displayed on the chart: [09:00, 10:00, 11:00, ...]. If you specify a drawing at 09:30, the library shifts it to 09:00. Moreover, if you change the resolution to 30 minutes and the data point at 09:30 appears, the library will still display the drawing at 09:00. #### Drawing You should specify a [`CreateShapeOptions`] object to provide information about the drawing, such as [drawing type](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CreateShapeOptions#shape) and [overrides](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CreateShapeOptions#overrides), and configure user control over drawings. For example, you can use the [`lock`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CreateShapeOptions#lock) property to disable moving and deleting drawings in the UI. Consider the code sample below that creates a play icon. ```javascript widget.chart().createShape( { time: 1514796562, price: 150 }, { shape: "icon", icon: 0xf0da, } ) ``` Note that the [`icon`] value should be a **hex number**, not a string. ### createMultipointShape The [`createMultipointShape`] method allows you to create a drawing which position on the chart is determined by multiple points. For example, you can create triangles, trend lines, rectangles, and more. To do this, call `createMultipointShape` and pass an array of [points](#point) and a [`CreateMultipointShapeOptions`] object as parameters. :::tip You can check the number of required points in the _Settings_ dialog of a certain drawing. If you pass a wrong number of points, you get the following issue: _Error: Wrong points count for "drawing_name". Required "number"_. ::: Consider the CodePen below that displays [_Parallel Channel_](https) and _Info Line_ right after the chart is loaded. ### createExecutionShape The [`createExecutionShape`] method allows you to display an execution drawing on the chart. The execution is represented with buy/sell arrows. Unlike other types of drawings, users cannot change or move the execution drawings in the UI. The `createExecutionShape` method returns an instance of the [`IExecutionLineAdapter`] interface that provides an extensive API for adjusting the drawing settings. For example, you can specify an arrow color and text. Note that you cannot change the arrow size. :::tip If execution drawings created via `createExecutionShape` do not meet your requirements, you can emulate these drawings using the [`createShape`](#createshape) method. ::: Consider the CodePen below that demonstrates how to display buy/sell arrows using `createExecutionShape`and `createShape`. These arrows represent trading history. ### createAnchoredShape The [`createAnchoredShape`] method allows you to create an anchored drawing. These drawings are fixed on the same position and do not move when a user scrolls the chart. The drawing points are measured as percentage from the top-left corner of the chart. To create an anchored drawing, call the `createAnchoredShape` method and pass a [`PositionPercents`] and [`CreateAnchoredShapeOptions`] objects as parameters. For example, the code sample below creates an anchored text. ```javascript widget.activeChart().createAnchoredShape( { x: 0.1, y: 0.3 }, { shape: "anchored_text", text: "This is an anchored drawing", overrides: { color: "green" }} ); ``` Anchored drawing ## Attach drawing to indicator You can attach a drawing to a certain indicator on the chart. To do this, specify the `ownerStudyId` property when you create a drawing using the methods [above](#create-drawings). For example, the code sample below attaches an icon to the [_Exponential Moving Average (EMA)_](https) indicator. ```javascript // Create the EMA indicator const emaId = await widget.activeChart().createStudy('Moving Average Exponential', false, false, { length: 26 }); // Draw an icon and attach it to EMA widget.chart().createShape( { time: 1714796562, price: 170 }, { shape: "icon", icon: 0xf0da, ownerStudyId: emaId, } ) ``` The attached drawing follows the indicator when the indicator is moved to another [pane](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossarypane). If you delete the indicator, all attached drawings are also deleted. By default, drawings are displayed on the pane with the main [series](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryseries). You can use `ownerStudyId` to display a drawing on a separate pane that contains indicator. For example, the code sample below creates the [_Moving Average Convergence/Divergence (MACD)_](https) indicator and displays an arrow on the indicator's pane. ```javascript // Create the MACD indicator const macdId = await widget.activeChart().createStudy('MACD', false, false, { in_0: 14, in_1: 30, in_3: 'close', in_2: 9 }); // Draw an arrow on the MACD pane widget.activeChart().createMultipointShape( [ { time: 1701698287, price: 2, }, { time: 1701698287, price: -1, }, ], { shape: 'arrow', text: "text", ownerStudyId: macdId } ) ``` Drawing on a separate pane ## Manage drawings When you create a drawing using either [`createShape`], [`createMultipointShape`], or [`createAnchoredShape`], the methods return the drawing's ID. You can use this ID to refer to the drawing and manage it. For example, you can specify if users can select the drawing in the UI or change drawing properties. To do this, use the [`getShapeById`] method and pass an ID as a parameter. `getShapeById` returns an instance of the [`ILineDataSourceApi`] interface that provides an extensive API for controlling the drawing. The code sample below gets all drawing properties. ```javascript widget.activeChart().getShapeById(id).getProperties(); ``` ## Get drawings To get a list of all drawings on the chart and their IDs, use the [`getAllShapes`] method. ```javascript widget.activeChart().getAllShapes(); ``` ## Remove drawings ### removeEntity When you create a drawing using either [`createShape`], [`createMultipointShape`], or [`createAnchoredShape`], the methods return the drawing's ID via a Promise. You can use this ID to remove the drawing from the chart. To do this, use the [`removeEntity`] method. ```javascript widget.activeChart().removeEntity(id); ``` ### removeAllShapes To remove all drawings from the chart, use the [`removeAllShapes`] method. ```javascript widget.activeChart().removeAllShapes(); ``` ## Drawing events To handle an event raised when a drawing is added to the chart, call the [`subscribe`] method with the [`drawing`] parameter. ```javascript widget.subscribe('drawing', (event) => { console.log(event.value); }); ``` You can also handle action events, such as moving a drawing or changing its properties. To do this, subscribe to [`drawing_event`]. ```javascript widget.subscribe('drawing_event', (id, type) => { console.log(id, type); }); ``` ## Drawing Groups API You can combine drawings into groups and manage them as single objects using the [group ID]. To do this, call the [`shapesGroupController`] method that returns an instance of the [`IShapesGroupControllerApi`] interface. This interface provides methods for controlling the drawing groups. For example, the code sample below creates a new group from the selected drawings. ```javascript widget.activeChart().shapesGroupController().createGroupFromSelection(); ``` When working with groups, consider the following rules: 1. Each drawing tool may or may not be part of a specific group. Drawings cannot be part of several groups at the same time. 2. Only drawings of the same pane can be grouped. 3. A group cannot be empty. Empty groups are automatically removed. 4. All drawings in the group have sequential z-indexes. Thus, no other object can be placed between drawings in a group. 5. Groups are bound with symbols. [`IChartWidgetApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi [`chart`]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methods#chart [`activeChart`]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methods#activechart [`createShape`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createshape [`StickedPoint`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.StickedPoint [`PricedPoint`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PricedPoint [`TimePoint`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.TimePoint [`CreateShapeOptions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CreateShapeOptions [`icon`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CreateShapeOptions#icon [`createMultipointShape`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createmultipointshape [`CreateMultipointShapeOptions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CreateMultipointShapeOptions [`createExecutionShape`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createexecutionshape [`IExecutionLineAdapter`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IExecutionLineAdapter [`createAnchoredShape`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createanchoredshape [`CreateAnchoredShapeOptions`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CreateAnchoredShapeOptions [`PositionPercents`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.PositionPercents [`getAllShapes`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#getallshapes [`getShapeById`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#getshapebyid [`removeEntity`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#removeentity [`removeAllShapes`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#removeallshapes [`shapesGroupController`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#shapesgroupcontroller [group ID]: https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library#shapesgroupid [`ILineDataSourceApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ILineDataSourceApi [`IShapesGroupControllerApi`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IShapesGroupControllerApi [`drawing_event`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap#drawing_event [`drawing`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.SubscribeEventsMap#drawing [`subscribe`]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/widget-methods#subscribe--unsubscribe URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings =================================================================================== # Drawings Drawings (shapes) are the tools that can help you analyze the charts and make clear annotations to them. The drawings toolbar is located on the left panel. Follow the [Drawings List] article for a complete list of tools included in the drawing toolbar. ## Style customization Each drawing tool has its own default properties, such as color and size, that users can change in the UI. ![Style customization](https://www.tradingview.com/charting-library-docs/img/drawings_style_customization.png) You can also customize the drawing style using the API. Refer to the [Drawing Overrides] article for more information. ## Drawing toolbar You can show/hide the drawing toolbar on the fly as follows: ```javascript widget.activeChart().executeActionById("drawingToolbarAction"); ``` Note that the toolbar is hidden in the fullscreen mode. To display the toolbar, enable the [`side_toolbar_in_fullscreen_mode`] featureset. ### Favorite tools You can specify a default list of favorite drawings using the [`favorites`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#favorites) property in [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor). In the UI, users can mark drawings as favorites using the _Add to favorites_ button. The selected drawings are added to _Favorite Drawings Toolbar_ that appears on the chart. If you do not want users to specify favorites, you should disable the [`items_favoriting`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsitems_favoriting) featureset. As a result, the _Add to favorites_ button will be hidden in the UI. ![Favorite tool](https://www.tradingview.com/charting-library-docs/img/drawings_favorite_tool.png) ### Custom restrictions You can hide some drawings from the toolbar or apply custom restrictions to the chart. To do this, use the [`drawings_access`] property of [Widget Constructor]. For example, you can choose which tools will be shown to users or hidden/disabled from them. ![Disabling drawings](https://www.tradingview.com/charting-library-docs/img/drawings_custom_restrictions.png) ## Drawing features ### Templates :::info These feature is only available in [Trading Platform]. ::: Users can use the template appliance option for multiple drawings of the same type. This option is available in the floating toolbar. To disable this feature, include the `drawing_templates` [featureset] in the [`disabled_features`] array. ![Template](https://www.tradingview.com/charting-library-docs/img/drawings_template.png) :::tip To save drawing templates on your server, you can use the [predefined REST API] or implement [API handlers]. ::: ## Drawing API The library allows you to create and manage drawings using the built-in API. You can also combine drawings into groups and subscribe to drawing-related events. Refer to [Drawings API](https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/drawings-api) for more information. [API handlers]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/save-load-adapter [`disabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features [`drawings_access`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#drawings_access [Drawings List]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings/Drawings-List [Drawing Overrides]: https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Drawings-Overrides [featureset]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets [predefined REST API]: https://www.tradingview.com/charting-library-docs/latest/api/save-load-rest-api [`side_toolbar_in_fullscreen_mode`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#side_toolbar_in_fullscreen_mode [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators/Indicators-List ===================================================================================================== # Indicators List Please find below all available indicators in the library ## 0-9 52 Week High/Low ## A Accelerator Oscillator Accumulation/Distribution Accumulative Swing Index Advance/Decline Arnaud Legoux Moving Average Aroon Average Directional Index Average Price Average True Range Awesome Oscillator ## B Balance of Power Bollinger Bands Bollinger Bands %B Bollinger Bands Width ## C Chaikin Money Flow Chaikin Oscillator Chaikin Volatility Chande Kroll Stop Chande Momentum Oscillator Chop Zone Choppiness Index Commodity Channel Index Connors RSI Coppock Curve Correlation Coefficient Correlation - Log ## D Detrended Price Oscillator Directional Movement Donchian Channels Double EMA ## E Ease of Movement Elder's Force Index EMA Cross Envelopes ## F Fisher Transform ## G Guppy Multiple Moving Average ## H Historical Volatility Hull Moving Average ## I Ichimoku Cloud ## K Keltner Channels Klinger Oscillator Know Sure Thing ## L Least Squares Moving Average Linear Regression Curve Linear Regression Slope ## M MA Cross MA with EMA Cross Mass Index McGinley Dynamic Median Price Momentum Money Flow Index Moving Average Moving Average Channel MACD Moving Average Exponential Moving Average Weighted Moving Average Double Moving Average Triple Moving Average Adaptive Moving Average Hamming Moving Average Multiple Majority Rule ## N Net Volume ## O On Balance Volume ## P Parabolic SAR Pivot Points Standard Price Channel Price Oscillator Price Volume Trend ## R Rank Correlation Index Rate Of Change Ratio Relative Strength Index Relative Vigor Index Relative Volatility Index ## S Standard Error Standard Error Bands SMI Ergodic Indicator/Oscillator Smoothed Moving Average Standard Deviation Stochastic Stochastic RSI SuperTrend Spread ## T TRIX Triple EMA True Strength Indicator Trend Strength Index Typical Price ## U Ultimate Oscillator ## V Volatility Close-to-Close Volatility Zero Trend Close-to-Close Volatility O-H-L-C Volatility Index VWAP VWMA Volume Oscillator Volume Profile Fixed Range Volume Profile Visible Range Vortex Indicator Volume ## W Williams %R Williams Alligator Williams Fractal ## Z Zig Zag URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators ===================================================================================== # Indicators An indicator (study) is a mathematical function built based on trading statistics such as opening and closing prices, minimum and maximum prices, trading volumes, and more. You can make predictions about the future movement of the market by analyzing changes in values of the indicator. The values of indicator functions can be displayed on the chart in the form of lines, columns, points, and geometric figures. For more information about indicators, refer to the [Technical Indicator](https) article. ![Indicator](https://www.tradingview.com/charting-library-docs/img/indicator.png) ## Built-in indicators Advanced Charts and Trading Platform support more than 100 indicators. Refer to [Indicators List](https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators/Indicators-List) to see all available indicators. ## Custom indicators You can create your custom indicators in JavaScript. Refer to [Custom Studies](https://www.tradingview.com/charting-library-docs/latest/custom_studies) for more information. Note that [Pine Script®](https) is not supported in the libraries. ## Add an indicator Indicators can be added [in the UI](#ui) and [using the API](#api). ### UI Users can add indicators in the UI as demonstrated below. ![Indicator in UI](https://www.tradingview.com/charting-library-docs/img/add-indicator-ui.gif) Users can also change the indicator's parameters in the _Settings_ dialog. ![Indicator Settings dialog in UI](https://www.tradingview.com/charting-library-docs/img/indicator-settings-ui.gif) :::info Users cannot see or change the code of built-in or custom indicators. ::: ### API You can use the [`createStudy`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createstudy) method to add an indicator to the chart. The method has the `inputs` parameter that allows you to specify an indicator's options. To get a list of options available for a certain indicator, call the [`getStudyInputs`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#getstudyinputs) method and pass the indicator's name as a parameter. Note that the indicator's name should match the one provided in the drop-down list. ```javascript widget.getStudyInputs('MACD'); ``` The code sample below demonstrates how to create an indicator. ```javascript widget.activeChart().createStudy('MACD', false, false, { in_0: 14, in_1: 30, in_3: 'close', in_2: 9 }); widget.activeChart().createStudy('Moving Average Exponential', false, false, { length: 26 }); widget.activeChart().createStudy('Stochastic', false, false, { in_0: 26 }, {"%d.color" : "#FF0000"}); widget.activeChart().createStudy('Price Channel', true, false, { in_0: 26 }, null, {checkLimit: false, priceScale: 'new-left'}); ``` ## Add and compare new series Users can add new [series](https://www.tradingview.com/charting-library-docs/latest/getting_started/glossaryseries) to the chart to compare symbols. To do this in the UI, users should click the _Compare or Add Symbol_ button. They can also specify a price scale and display the new symbol on a new pane. ![Compare in UI](https://www.tradingview.com/charting-library-docs/img/compare-indicator-ui.png) To add a symbol programmatically, you should use the _Overlay_ indicator. ```javascript widget.activeChart().createStudy('Overlay', true, false, { symbol: 'IBM' }); ``` Alternatively, you can use the _Compare_ indicator that allows you to additionally specify the data source. However, unlike _Overlay_, this indicator does not support the [_Allow extend time scale_](https://www.tradingview.com/charting-library-docs/latest/custom_studies/Studies-Extending-The-Time-Scalefor-overlay-study) feature or logos in the [_Legend_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legenddisplay-logos). ```javascript widget.activeChart().createStudy('Compare', false, false, { source: 'open', symbol: 'IBM'}); ``` ### Enable spread operators **Spread operators** are operators that allow comparison between a financial instrument, such as a stock, and an additional variable, such as another financial instrument or a numerical value. import SpreadOperatorsWarning from './../_spread-operators-warning.mdx'; To display spread operators, include the [`show_spread_operators`] and [`compare_symbol_search_spread_operators`] featuresets in the [`enabled_features`] array. ![Spread operators in the Compare Symbol dialog](https://www.tradingview.com/charting-library-docs/img/spread-operators-in-compare-symbol.png) ## Visibility customization ### Hide indicators You can use the [`studies_access`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#studies_access) property of the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) to customize the list of indicators available to users. For example, you can hide some indicators or only make them available to certain users. Check out the [Widget Constructor tutorial](https) on YouTube for an implementation example. ### Hide volume-based indicators If your datafeed does not provide volume data and you want to hide all volume-based indicators, you should add the indicators below to the blacklist in [`studies_access`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#studies_access). - Accumulation/Distribution - Chaikin Money Flow - Ease of Movement - Elders Force Index - Klinger Oscillator - Money Flow Index - Net Volume - On Balance Volume - Price Volume Trend - VWAP - Volume Oscillator ### Hide the Volume indicator The library adds the _Volume_ indicator to all financial instruments that have volume data. If you do not want to show this indicator, you should include the [`create_volume_indicator_by_default`](../../customization/Featuresets#create_volume_indicator_by_default) featureset in the [`disabled_features`] array. ### Limit indicator amount You can use the [`study_count_limit`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#study_count_limit) property of the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) to set the maximum amount of indicators that can be displayed on the chart simultaneously. ![Limit exceeded](https://www.tradingview.com/charting-library-docs/img/limit-indicator.png) ## Style customization You can use the [`studies_overrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#studies_overrides) property of the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) to specify the indicator's default parameters such as colors, line width, a plot type, and more. Refer to the [Indicator Overrides](https://www.tradingview.com/charting-library-docs/latest/customization/overrides/indicator-overrides) article for more information on how to customize an indicator. ## Indicator API After an indicator is created, you can manage it using `IStudyApi`. For example, you can change the indicator's visibility or position. Refer to [`IStudyApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IStudyApi) for more information. [`compare_symbol_search_spread_operators`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#compare_symbol_search_spread_operators [`disabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features [`enabled_features`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#enabled_features [`show_spread_operators`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#show_spread_operators URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/market-status ======================================================================================== # Market Status **Market Status** is a pop-up that contains information on the symbol trading session and current market status. Users should click the icon within the [_Legend_](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Legend) to open this pop-up. Market Status ## Session timeline The timeline in the pop-up depends on the session configuration for the current symbol. If the Market Status shows incorrect data, make sure you specified session correctly in the [`LibrarySymbolInfo`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo) object. For more information, refer to the [Session](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologysession) and [Extended sessions](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologyextended-sessions) sections. Note that the Market Status displays market hours in the **exchange time zone**. ## Customize the pop-up ### Change text You can specify the [`custom_translate_function`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_translate_function) property of the [Widget Constructor](https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) to change the default text in the pop-up. ```javascript var widget = (window.tvWidget = new TradingView.widget({ custom_translate_function: (key, options, isTranslated) => { console.log('key: ', key); if (key === "Market closed") { return "The market is closed. Check back later."; } return null; }, })); ``` ### Add custom section You can display additional information, such as warnings, in the Market Status for a certain symbol. To do this, use the methods from [`ICustomSymbolStatusApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ICustomSymbolStatusApi) that allows you to customize an icon, color, tooltip, and content of the pop-up. To retrieve an `ICustomSymbolStatusApi` object, call the [`customSymbolStatus`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#customsymbolstatus) method at any time after the chart is created. Consider the following code sample that specifies additional section for AAPL. Custom Market Status ```js // Icon from https://heroicons.com const myCustomIconSvgString = ` `; widget .customSymbolStatus() .symbol('NASDAQNM:AAPL') // Select the symbol .setVisible(true) // Make the status visible .setColor('rgb(255, 40, 60)') // Set the color .setIcon(myCustomIconSvgString) // String for an SVG icon, i.e. ' ... ' .setTooltip('Tooltip') // Text to be displayed within the hover tooltip .setDropDownContent([ // Content to be displayed within the large pop-up tooltip { title: 'Title', // Title to be displayed within the pop-up color: 'rgb(255, 60, 70)', // Optional, if you want it to be different to above content: ['Explanation of status', '

', 'More details...'], action: { // Optional action to be displayed text: 'Read more here', tooltip: 'opens in a new window', onClick: () => { window.open('https://www.tradingview.com/', '_blank'); }, }, }, ]); ``` :::caution Make sure you pass a correct symbol ID to the [`ICustomSymbolStatusApi.symbol`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ICustomSymbolStatusApi#symbol) method. The ID should be the same as your datafeed provides to the library when the [`resolveSymbol`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IDatafeedChartApi#resolvesymbol) method is called. To check the ID of the current symbol, call the [`IChartWidgetApi.symbol`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#symbol) method. ::: ## Disable the pop-up Add the [`display_market_status`](https://www.tradingview.com/charting-library-docs/latest/customization/Featuresetsdisplay_market_status) featureset to [`disabled_features`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#disabled_features) to hide the Market Status. URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/object-tree ====================================================================================== # Object tree The *Object tree* is a feature that allows managing (hiding, showing, or removing) drawings, indicators, and symbols on the chart. The *Object tree* is enabled by default but you can hide it by disabling the [`show_object_tree`] featureset. Users can access the *Object tree* through the left toolbar (in Advanced Charts) or the right toolbar (in Trading Platform). Object tree ## Fix undefined values The `undefined` string appears in the *Object tree* when the [`exchange`] and [`listed_exchange`] properties are missing from the [`LibrarySymbolInfo`] object. You should provide this object via the [`resolveSymbol`] callback. To resolve this issue, ensure these properties have appropriate values in the `LibrarySymbolInfo` object. Alternatively, you can hide the symbol exchange display by enabling the [`hide_object_tree_and_price_scale_exchange_label`] featureset. [`exchange`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#exchange [`hide_object_tree_and_price_scale_exchange_label`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#hide_object_tree_and_price_scale_exchange_label [`LibrarySymbolInfo`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo [`listed_exchange`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.LibrarySymbolInfo#listed_exchange [`resolveSymbol`]: https://www.tradingview.com/charting-library-docs/latest/api/required-methods#resolvesymbol [`show_object_tree`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#show_object_tree URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/timezones ==================================================================================== # Time zones ## Overview Time on the [time scale](https://www.tradingview.com/charting-library-docs/latest/ui_elements/Time-Scale) is displayed according to the chart time zone. To set the default time zone, specify the [`timezone`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#timezone) property in the [Widget Constructor]. ```javascript var widget = window.tvWidget = new TradingView.widget({ // ... overrides: { "timezone": "America/New_York", } }); ``` You can change the default time zone on the fly using the [`applyOverrides`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#applyoverrides) method. ```javascript widget.applyOverrides({ "timezone": "Europe/Belgrade"}); ``` :::caution Besides the time zone of the chart, you should also specify the time zone for each symbol. Make sure you provide correct values as it affects how the library aligns and displays the data. Refer to [Symbology](https://www.tradingview.com/charting-library-docs/latest/connecting_data/Symbologytime-zone) for more information. ::: ### Manage time zone Call the [`getTimezoneApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#gettimezoneapi) method to get an instance of the [`ITimezoneApi`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ITimezoneApi) interface. This interface provides an extensive API for managing time zone settings. For example, you can change the current time zone as follows: ```javascript widget.activeChart().getTimezoneApi().setTimezone("America/Chicago"); ``` In the UI, users can switch the time zone from the drop-down list at the bottom of the chart or through the *Settings* dialog. ## Supported time zones The library supports the following time zones: - `Etc/UTC` - `Africa/Cairo` - `Africa/Casablanca` - `Africa/Johannesburg` - `Africa/Lagos` - `Africa/Nairobi` - `Africa/Tunis` - `America/Anchorage` - `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/Astana` - `Asia/Ashkhabad` - `Asia/Bahrain` - `Asia/Bangkok` - `Asia/Chongqing` - `Asia/Colombo` - `Asia/Dhaka` - `Asia/Dubai` - `Asia/Ho_Chi_Minh` - `Asia/Hong_Kong` - `Asia/Jakarta` - `Asia/Jerusalem` - `Asia/Karachi` - `Asia/Kabul` - `Asia/Kathmandu` - `Asia/Kolkata` - `Asia/Kuala_Lumpur` - `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/Azores` - `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/Prague` - `Europe/Riga` - `Europe/Rome` - `Europe/Stockholm` - `Europe/Tallinn` - `Europe/Vienna` - `Europe/Vilnius` - `Europe/Warsaw` - `Europe/Zurich` - `Pacific/Auckland` - `Pacific/Chatham` - `Pacific/Fakaofo` - `Pacific/Honolulu` - `Pacific/Norfolk` - `US/Mountain` If your time zone is not supported, you can request it on [GitHub Issues](https) 🔐 (access is [restricted](https://www.tradingview.com/charting-library-docs/latest/getting_started/quick-startgetting-access )) or add your [custom time zone](#custom-time-zones). ## Custom time zones You can specify a custom time zone using the [`custom_timezones`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#custom_timezones) property in the [Widget Constructor]. Just like the built-in time zones, custom time zones will appear in the drop-down list and chart settings. You can also use them to specify time zones for symbols. You should map (alias) a custom time zone to either a [built-in](#supported-time-zones) or [GMT-based time zone](#gmt-based-time-zones) one. Ensure that the alias time zone correctly matches your desired time zone in all aspects including daylight saving time dates. The code sample below adds the following time zones: - the Cape Town time zone aliased to the built-in time zone of Johannesburg. - the Nuuk time zone aliased to a GMT-based time zone. ```js var widget new TradingView.widget({ // ... custom_timezones: [ { id: "Africa/Cape_Town", alias: "Africa/Johannesburg", title: "Cape Town", }, { id: "America/Nuuk", alias: "Etc/GMT+3", title: "Nuuk", }, ], })); ``` ### GMT-based time zones You can map your custom time zone to a GMT-based time zone. GMT-based time zones can only be used in the [`alias`](https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.CustomAliasedTimezone#alias) property of a custom time zone object. The GMT-based time zones should be specified in the following format: Element | Description ---------|---------- `Etc/GMT` | The default beginning. `+` or `-` | The sign showing the offset direction. Number | The number of hours offset. : | A separator between hours and minutes. Number (Optional) | The number of minutes offset. To conform with the [POSIX](https) style, time zone names use a sign that is reversed from the standard [ISO 8601](https) convention. In the `Etc/` namespace, time zones west of GMT have a positive sign, and those east of GMT have a negative sign. #### Examples - `Etc/GMT+0` : same as `Etc/UTC` - `Etc/GMT+2` : 2 hours behind GMT - `Etc/GMT-4` : 4 hours ahead of GMT - `Etc/GMT-3:21` : 3 hours and 21 minutes ahead of GMT [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements ========================================================================== # UI elements import CardLinkList from "@site/src/components/CardLinkList"; The library offers a feature-rich interface, providing the opportunity to tweak and customize it to fit specific needs. This article serves as a guide to understanding the various parts of the interface. Further articles within this section provide detailed explanations for each UI element. The interface can be divided into the following main parts. User interface ## Top toolbar ## Chart The main area on the chart where a [series] or [indicator] is displayed is called **pane**. The picture below shows the red pane with a main series and the green pane with an indicator. Chart panes The chart contains the following elements: ## Drawing toolbar Drawings are the tools that can help you analyze the charts and make clear annotations to them. For more information, refer to [Drawings]. ## Widget bar The widget bar is a right side toolbar available in [Trading Platform] only. You cannot change the widget bar location but you can hide it using the [`hide_right_toolbar`] and [`hide_right_toolbar_tabs`] featuresets. The bar displays the following widgets: ## Account Manager The Account Manager is a widget available in [Trading Platform] only. The widget displays the user's trading information, such as orders, positions, and account balance. Users can manage their orders and positions from the Account Manager. For more information, refer to [Account Manager]. [Account Manager]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal/account-manager [Drawings]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/drawings [indicator]: https://www.tradingview.com/charting-library-docs/latest/ui_elements/indicators [series]: https://www.tradingview.com/charting-library-docs/latest/getting_started/glossary#series [Trading Platform]: https://www.tradingview.com/charting-library-docs/latest/trading_terminal [`hide_right_toolbar`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#hide_right_toolbar [`hide_right_toolbar_tabs`]: https://www.tradingview.com/charting-library-docs/latest/customization/Featuresets#hide_right_toolbar_tabs URL: https://www.tradingview.com/charting-library-docs/latest/ui_elements/watermarks ===================================================================================== # Watermarks ## Overview Watermarks provide a visual text overlay on the chart. Users can manage the visibility and color of watermarks in the *Settings → Canvas → Watermark*. A default watermark contains a symbol ticker, interval, and description. TradingView recommends letting users enable the watermark themselves. This ensures their preferences are always respected. However, you can also programmatically manage watermarks in two ways: - Using the [Watermark API](#watermark-api-recommended) for dynamic changes. - Using the [settings adapter](#settings-adapter) to set the initial state. ## Watermark API (recommended) The [Watermark API] allows you to either customize the default watermark or implement a custom one. To access the API, use the [`watermark`] method of the `IChartingLibraryWidget` interface. ```js // Get an instance of IWatermarkApi widget.onChartReady(() => { const watermarkApi = widget.watermark(); }); ``` ### Color and visibility To manage the watermark color, use the [`color`] method. ```js watermarkApi.color().setValue("rgba(0, 150, 0, 0.5)"); ``` To control the visibility of the ticker, description, and interval of the watermark, use the [`tickerVisibility`], [`descriptionVisibility`], and [`intervalVisibility`] methods. ```js watermarkApi.descriptionVisibility().setValue(false); ``` ### Custom content To replace the default watermark with your own custom content, use the [`setContentProvider`] method. The provider function receives a `WatermarkContentData` object and should return an array of `WatermarkLine` objects. Each `WatermarkLine` defines a line of text with the following properties: - Text to be displayed - Font size - Line height - Vertical offset distance ## Settings adapter If you only need to control the initial visibility and color of the default watermark, you can use the [settings adapter] in your [Widget Constructor]. This method doesn't support custom text. It only applies to the default built-in watermark. To make the watermark visible, set the `symbolWatermark` property within the `initialSettings` of your [`settings_adapter`]. Note that defining `setValue` and `removeValue` functions is required. ```js new TradingView.widget({ /* Other Widget Constructor properties */ settings_adapter: { initialSettings: { "symbolWatermark": '{ "visibility": "true", "color": "rgba(244, 67, 54, 0.25)" }', }, setValue: function (key, value) { console.log(`set value: ${key} ${value}`); }, removeValue: function (key) { console.log(`remove value: ${key}`); }, } }) ``` [`color`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatermarkApi#color [`descriptionVisibility`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatermarkApi#descriptionvisibility [`intervalVisibility`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatermarkApi#intervalvisibility [`setContentProvider`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatermarkApi#setcontentprovider [`settings_adapter`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions#settings_adapter [settings adapter]: https://www.tradingview.com/charting-library-docs/latest/saving_loading/user-settings#settings-adapter [`tickerVisibility`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatermarkApi#tickervisibility [`watermark`]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartingLibraryWidget#watermark [Watermark API]: https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IWatermarkApi [Widget Constructor]: https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor --- ## Part 2: Answering Guidelines (Prompt) You are a helpful expert for the Advanced Charts and Trading Platform charting libraries. Your knowledge is based exclusively on the documentation provided in this file. Your primary goal is to help users understand and apply the library's features. To do this, you must follow these rules: 1. Base all facts, API details, and code examples related to the library exclusively on the text in this document. Use your general knowledge of JavaScript, TypeScript, and web development only to explain concepts and provide context. 2. If the answer to a question cannot be found in this document, you must respond with: "I'm sorry, but this information is not available in the provided documentation for version 30.0.0." 3. Do not invent or hallucinate functions, methods, properties, or APIs that are not explicitly mentioned in this file. It is better to say you don't know than to provide incorrect information. 4. When you mention a specific API, feature, or concept, include its full absolute documentation URL if one is available in the text. 5. If you are unable to locate a full absolute documentation link then suggest a search link instead where the search term is placed as the 'q' query parameter on this url: https://www.tradingview.com/charting-library-docs/search/ Spaces in the search term should be replaced with the '+' character. For example: https://www.tradingview.com/charting-library-docs/search/?q=search+term 6. When a user asks for a code example, provide a complete, clean, and well-formatted code block. Include comments explaining the code and specify the language (e.g., JavaScript, TypeScript). 7. Answer the user's question directly. If a question is vague, you may ask for clarification to provide a more useful response. 8. This documentation is for version 30.0.0. If a question seems related to a feature that might be version-dependent, gently remind the user of this fact. ## End of context