### Install and Run HTTP Server with Node.js Source: https://github.com/1of1adam/docs/blob/master/tutorials/running-the-library.md These commands show how to install the `http-server` package globally using npm and then start a local HTTP server to host the charting library. ```JavaScript npm install http-server -g ``` ```JavaScript http-server -p 9090 ``` -------------------------------- ### Install Python Dependencies for Chart Storage Backend Source: https://github.com/1of1adam/docs/blob/master/saving_loading/rest-api.md This command-line snippet shows how to navigate into a Python project directory and install its required dependencies using `pip` from a `requirements.txt` file. This is a common and necessary step for setting up a Python application, such as the provided chart storage backend example. ```Shell cd your-repository pip install -r requirements.txt ``` -------------------------------- ### JavaScript Example for LibraryPineStudy.init Method Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-librarypinestudy.md Illustrates a practical implementation of the `init` method within a custom indicator. This example shows how to set up a symbol and period using `context.new_sym` and `PineJS.Std.period` for initial data loading. ```javascript this.init = function(context, inputCallback) { var symbol = '#EQUITY'; var period = PineJS.Std.period(this._context); context.new_sym(symbol, period);}; ``` -------------------------------- ### Example: Initializing Datafeed with UDFCompatibleDatafeed Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-tradingterminalwidgetoptions.md This example shows how to configure the `datafeed` property using a `UDFCompatibleDatafeed` instance, pointing to a demo data feed URL. ```JavaScript datafeed: new Datafeeds.UDFCompatibleDatafeed("https://demo_feed.tradingview.com") ``` -------------------------------- ### JavaScript: Datafeed Configuration Example Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-tradingterminalwidgetoptionsfavorites.md Example showing how to configure the `datafeed` property using a `Datafeeds.UDFCompatibleDatafeed` instance, pointing to a demo data feed URL. ```JavaScript datafeed: new Datafeeds.UDFCompatibleDatafeed("https://demo_feed.tradingview.com") ``` -------------------------------- ### Example: Datafeed Configuration with UDFCompatibleDatafeed Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-chartinglibrarywidgetoptions.md Illustrates how to configure the `datafeed` property by instantiating a `Datafeeds.UDFCompatibleDatafeed` object. This example points to a demo feed URL for data retrieval. ```javascript datafeed: new Datafeeds.UDFCompatibleDatafeed("https://demo_feed.tradingview.com") ``` -------------------------------- ### Example price_sources Array Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/Charting_Library.LibrarySymbolInfo/symbolinfodefines-the-structure-and-metadata-for-symbols-including-properties-like-ticker-and-exchange.md An example array illustrating the structure for defining multiple price sources, such as 'Spot Price' and 'Bid', for a symbol. ```JavaScript [{ id: '1', name: 'Spot Price' }, { id: '321', name: 'Bid' }] ``` -------------------------------- ### Example: Configuring Snapshot URL Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-chartinglibrarywidgetoptions.md Shows a simple configuration for the `snapshot_url` option, pointing to a hypothetical server endpoint for handling chart snapshots. ```JavaScript snapshot_url: "https://myserver.com/snapshot", ``` -------------------------------- ### Example Price Sources Array for LibrarySymbolInfo Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-symbolext.md An example of the JSON array structure expected for the `price_sources` property within `LibrarySymbolInfo`, defining supported price origins for a symbol. ```JSON [{ "id": "1", "name": "Spot Price" }, { "id": "321", "name": "Bid" }] ``` -------------------------------- ### Example Console Logs for Broker API Debug Mode Source: https://github.com/1of1adam/docs/blob/master/tutorials/enabling-debug-mode.md This snippet shows example console output generated when the TradingView widget's Broker API debug mode is enabled. It illustrates a `placeOrder` method call, including its arguments, and the subsequent asynchronous return, providing insight into the data flow during trading operations. ```Log 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): {} ``` -------------------------------- ### Example: Configuring Study Access Restrictions Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-chartinglibrarywidgetoptions.md Provides an example of `studies_access` configuration, demonstrating how to use 'black' or 'white' list types and specify individual studies to be grayed out or restricted. ```JavaScript studies_access: { type: "black" | "white", tools: [ { name: "", grayed: true }, < ... > ]} ``` -------------------------------- ### Start Django Development Server Source: https://github.com/1of1adam/docs/blob/master/saving_loading/rest-api.md This command starts Django's built-in development server, allowing local testing of the application. While suitable for development purposes, it is explicitly noted that this command should not be used in production environments, where a more robust WSGI server like Gunicorn is recommended. ```Shell python manage.py runserver ``` -------------------------------- ### Example Configuration for Widget Width Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-chartinglibrarywidgetoptions.md An example demonstrating how to set the 'width' property to a fixed pixel value (300) within a configuration object. It also includes a remark advising the use of the 'fullscreen' parameter instead of '100%' for charts to occupy all available space. ```Configuration width: 300, ``` -------------------------------- ### Example: Set Order Line Body Font Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-iorderlineadapter.md Demonstrates how to chain method calls to set both the price and the body font of an order line. ```javascript orderLine.setPrice(170).setBodyFont("bold 12px Verdana") ``` -------------------------------- ### Initialize Project Directory with Bash Commands Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/set-up-the-widget.md These Bash commands are used to prepare the development environment by creating a new directory named 'chart-project' and then navigating into it. This sets up the root for the charting application files. ```Bash mkdir chart-project cd chart-project ``` -------------------------------- ### Example: Get Current Chart Theme Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/Charting_Library.IChartingLibraryWidget/ichartinglibrary-widgetprimary-interface-for-library-interactions.md Illustrates how to retrieve and log the current theme name of the chart widget using the `getTheme` method. ```JavaScript console.log(widget.getTheme()); ``` -------------------------------- ### Clone TradingView Charting Library Repository via Git Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/set-up-the-widget.md This Bash command clones the TradingView charting library from its GitHub repository. The library files are placed into a new directory named 'charting_library_cloned_data', which will be referenced by the web application. ```Bash git clone https://github.com/tradingview/charting_library charting_library_cloned_data ``` -------------------------------- ### Implement Pine Study Main Logic for Symbol Alignment Source: https://github.com/1of1adam/docs/blob/master/custom_studies/examples.md Defines the 'main' method of a Pine Study, which contains the core calculation logic. This example demonstrates how to select primary and secondary symbols, retrieve their time data, and align the secondary symbol's close price to the primary symbol's timeline for consistent data processing, returning the aligned data. ```JavaScript 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]; }; ``` -------------------------------- ### API Method: watchList and Example Usage Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-ichartinglibrarywidget.md This method is available for the Trading Platform only. It returns a Promise that resolves with an API object, allowing interaction with the watchlist in the widgetbar (right sidebar). The example demonstrates how to retrieve the active watchlist, get its current items, and then update the list by appending a new section and an item. ```APIDOC watchList(): Promise Returns: Promise - An API object for interacting with the widgetbar (right sidebar) watchlist. ``` ```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']); ``` -------------------------------- ### Create Basic HTML Page for Chart Widget Container Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/set-up-the-widget.md This HTML file (`index.html`) establishes the fundamental structure of the web page. It includes script tags to load the TradingView charting library and a custom JavaScript module (`src/main.js`), along with a `div` element (`tv_chart_container`) that serves as the designated placeholder for the chart widget. ```HTML TradingView Advanced Charts example
``` -------------------------------- ### Run Local HTTP Server with Python Source: https://github.com/1of1adam/docs/blob/master/tutorials/running-the-library.md These commands demonstrate how to start a simple HTTP server using Python 2.x or 3.x to serve the charting library files locally for development and testing. ```Python python -m SimpleHTTPServer 9090 ``` ```Python python -m http.server 9090 ``` -------------------------------- ### Example: Update TradingView Watchlist Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/Charting_Library.IChartingLibraryWidget/ichartinglibrary-widgetprimary-interface-for-library-interactions.md Demonstrates how to obtain the watchlist API, retrieve the active list, get its current items, and then append new sections and symbols to it. ```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']); ``` -------------------------------- ### Create Basic HTML Structure for Chart Container Source: https://github.com/1of1adam/docs/blob/master/tutorials/running-the-library.md This HTML snippet provides the foundational structure for the web page, including meta tags and an empty body, ready to host the charting library. ```HTML ``` -------------------------------- ### Example: Get CSS Custom Property Value Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/Charting_Library.IChartingLibraryWidget/ichartinglibrary-widgetprimary-interface-for-library-interactions.md Demonstrates how to use the `getCSSCustomPropertyValue` method to retrieve the value of a CSS custom property named `--my-theme-color` from the widget. ```JavaScript const currentValue = widget.getCSSCustomPropertyValue('--my-theme-color'); ``` -------------------------------- ### Example: Get Available Z-Order Operations Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/Charting_Library.IChartWidgetApi/ichart-widgetprimary-interface-for-chart-interactions-such-as-creating-drawings-and-indicators.md Shows how to retrieve an object containing available Z-order operations for a specified array of entity IDs using the `availableZOrderOperations` method. ```JavaScript widget.activeChart().availableZOrderOperations([id]); ``` -------------------------------- ### Run Local Web Server for Charting Library Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/implement-datafeed.md Command to start a local web server using `npx serve` to host the implemented TradingView Charting Library project, allowing local testing and viewing of the chart. ```shell npx serve ``` -------------------------------- ### Get Main Series API (JavaScript) Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-ichartwidgetapi.md Obtains an API object for the main series of the active chart, allowing programmatic interaction with its properties and methods. For example, it can be used to control visibility. ```APIDOC getSeries(): ISeriesApi Get the main series. Returns: ISeriesApi: An API object for interacting with the main series. ``` ```JavaScript widget.activeChart().getSeries().setVisible(false); ``` -------------------------------- ### Get Active Chart Symbol Name Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/Charting_Library.IChartWidgetApi/ichart-widgetprimary-interface-for-chart-interactions-such-as-creating-drawings-and-indicators.md Documents the `symbol()` method of the active chart widget, which returns the name of the current symbol as a string. Includes a JavaScript example demonstrating its usage. ```APIDOC symbol(): string Get the name of the current symbol. ``` ```javascript console.log(widget.activeChart().symbol()); ``` -------------------------------- ### Clone Charting Library Tutorial Repository Source: https://github.com/1of1adam/docs/blob/master/tutorials/connecting-data-via-datafeed-api.md Clones the official TradingView Charting Library tutorial repository from GitHub to your local machine, providing the base project for following the tutorial. ```Shell git clone https://github.com/tradingview/charting-library-tutorial.git ``` -------------------------------- ### Get Study Input Information Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-ichartinglibrarywidget.md Provides an array of information about an indicator's inputs, including their names. This information is crucial for referring to specific input properties when modifying their values, for example, through overrides. ```APIDOC getStudyInputs(studyName: string): StudyInputInformation[] Parameters: studyName: string - The name of a study. Returns: StudyInputInformation[] ``` -------------------------------- ### HTML Setup for TradingView Chart Widget Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/implement-streaming.md This HTML file defines the basic page structure, loads the TradingView charting library, and includes a custom JavaScript datafeed module. It also creates a `div` element that serves as the container for the TradingView chart widget. ```html TradingView Advanced Charts example
``` -------------------------------- ### Initialize TradingView Advanced Chart Widget in HTML Source: https://github.com/1of1adam/docs/blob/master/tutorials/running-the-library.md This snippet provides a complete HTML page structure for embedding and initializing a TradingView Advanced Chart widget. It includes the necessary script imports for the charting library and a UDF-compatible datafeed, then configures the chart with a symbol, interval, and other display options. ```html TradingView - Advanced Charts
``` -------------------------------- ### API: interval - Get Symbol Interval Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-pinejsstd.md Retrieves the numerical interval of the symbol's resolution. For example, if the symbol has a resolution of '1D', this function would return `1`. It requires a PineJS execution context. ```APIDOC interval(ctx: IContext): number ctx: IContext - PineJS execution context. Returns: number Symbol interval. ``` -------------------------------- ### Example JSON Response for Symbol Group Request Source: https://github.com/1of1adam/docs/blob/master/connecting_data/udf.md Illustrates a sample JSON response for the GET /symbol_info?group=NYSE API call, showing the structure and typical data for multiple symbols like Apple, Microsoft, and S&P 500 index. ```JSON { "symbol": ["AAPL", "MSFT", "SPX"], "description": ["Apple Inc", "Microsoft corp", "S&P 500 index"], "exchange-listed": "NYSE", "exchange-traded": "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" } ``` -------------------------------- ### Initialize TradingView Chart Widget with JavaScript Constructor Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/set-up-the-widget.md This JavaScript code (`main.js`) initializes the TradingView chart widget using the `TradingView.widget` constructor. It configures essential parameters such as the default symbol ('BTC/EUR'), interval ('1D'), fullscreen display, the ID of the DOM container ('tv_chart_container'), a placeholder for the datafeed, and the relative path to the charting library files. ```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 an attribute of a DOM element datafeed: Datafeed, library_path: '../charting_library_cloned_data/charting_library/', }); ``` -------------------------------- ### Get Extended Active Chart Symbol Information Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/Charting_Library.IChartWidgetApi/ichart-widgetprimary-interface-for-chart-interactions-such-as-creating-drawings-and-indicators.md Explains the `symbolExt()` method, which provides an extended information object (`SymbolExt`) for the current symbol. A JavaScript example shows how to access properties like the symbol's name from this object. ```APIDOC symbolExt(): SymbolExt Get an extended information object for the current symbol. ``` ```javascript console.log(widget.activeChart().symbolExt().name); ``` -------------------------------- ### Define Intraday Trading Sessions in TradingView Source: https://github.com/1of1adam/docs/blob/master/connecting_data/trading-sessions.md These examples illustrate how to define trading sessions that occur entirely within a single day, typically from Monday to Friday. The format specifies a start and end time within the same 24-hour period. ```APIDOC 0930-1600 ``` ```APIDOC 0000-0000 ``` -------------------------------- ### Set Chart Visible Date Range (JavaScript) Source: https://github.com/1of1adam/docs/blob/master/ui_elements/chart.md This JavaScript example shows how to programmatically set the visible date range of the TradingView chart using the `setVisibleRange` method. It sets the chart's view to start from July 12, 2023, 13:30 UTC, and applies a default right margin. ```javascript widget.activeChart().setVisibleRange( { from: Date.UTC(2023, 6, 12, 13, 30) / 1000 }, { applyDefaultRightMargin: true } ) ``` -------------------------------- ### Create a mock Datafeed API implementation in JavaScript Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/implement-datafeed.md This JavaScript code provides a basic mock implementation of the TradingView Datafeed API. It defines all required methods (`onReady`, `searchSymbols`, `resolveSymbol`, `getBars`, `subscribeBars`, `unsubscribeBars`) and logs a message to the console when each method is called. This serves as a starting point for a custom datafeed that will be fully implemented in subsequent steps. ```JavaScript 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); } }; ``` -------------------------------- ### Initialize TradingView Chart Widget Source: https://github.com/1of1adam/docs/blob/master/tutorials/running-the-library.md This JavaScript code initializes the TradingView charting widget, configuring its container, locale, library path, datafeed, and default symbol/interval for display. ```JavaScript ``` -------------------------------- ### JavaScript Example: Basic Symbol Resolution for Charting Library Source: https://github.com/1of1adam/docs/blob/master/connecting_data/datafeed-api/required-methods.md This JavaScript snippet demonstrates a basic implementation of the `resolveSymbol` function for a charting library. It resolves a specific symbol ('TEST') with predefined properties, illustrating how to provide initial symbol information. This code serves as a starting point and needs modification for production use, also hinting at the `noData: true` concept for other symbols. ```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", ``` -------------------------------- ### Include Charting Library and Datafeed Scripts Source: https://github.com/1of1adam/docs/blob/master/tutorials/running-the-library.md These script tags link the standalone charting library and a sample UDF datafeed bundle, essential for rendering and populating the chart with data. ```HTML ``` -------------------------------- ### Example TimeFrameItem Object Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-timeframeitem.md An example object demonstrating the structure and typical values for a `TimeFrameItem` used in the charting library. ```JSON { "text": "3y", "resolution": "1W", "description": "3 Years", "title": "3yr" } ``` -------------------------------- ### Initialize TradingView Widget with Cross-Origin library_path Source: https://github.com/1of1adam/docs/blob/master/getting_started/cross-origin-hosting.md This JavaScript code demonstrates initializing the TradingView widget. It highlights the crucial `library_path` parameter, which must be set to the full URL of the directory containing the Charting Library files when hosted on a separate origin, ensuring it ends with a trailing slash. ```javascript 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' ), })); ``` -------------------------------- ### Example: Setting Default Chart Symbol Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-chartinglibrarywidgetoptions.md A simple example demonstrating how to set the default symbol for the chart using the `symbol` option. ```JavaScript symbol: 'AAPL', ``` -------------------------------- ### Example SearchSymbolResultItem JSON Structure Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-searchsymbolresultitem.md An example JSON object demonstrating the typical structure and values for a `SearchSymbolResultItem` returned by a symbol search operation. ```JSON { description: 'Apple Inc.', exchange: 'NasdaqNM', symbol: 'AAPL', ticker: 'AAPL', type: 'stock' } ``` -------------------------------- ### Example: Set CSS Custom Property Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/Charting_Library.IChartingLibraryWidget/ichartinglibrary-widgetprimary-interface-for-library-interactions.md This example demonstrates how to use the `setCSSCustomProperty` method to change a custom CSS variable on the charting widget. ```JavaScript widget.setCSSCustomProperty('--my-theme-color', '#123AAA'); ``` -------------------------------- ### Example Bitfinex WebSocket Response Format Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/implement-streaming.md Illustrates the structure of a raw data message received from the Bitfinex WebSocket, containing trade information like exchange, symbols, price, and time. This format needs to be parsed by the client application. ```text 0~Bitfinex~BTC~USD~2~335394436~1548837377~0.36~3504.1~1261.4759999999999~1f ``` -------------------------------- ### Example: Check and Perform Chart Zoom Out Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/Charting_Library.IChartWidgetApi/ichart-widgetprimary-interface-for-chart-interactions-such-as-creating-drawings-and-indicators.md Provides an example of checking if the chart can be zoomed out using `canZoomOut` and then executing the zoom out operation if possible. ```JavaScript if(widget.activeChart().canZoomOut()) { widget.activeChart().zoomOut(); }; ``` -------------------------------- ### showOrderDialog Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/trading-hostreceives-trading-information-from-your-backend-server-and-provides-the-library-with-updates.md Shows the Order Ticket. ```APIDOC showOrderDialog(order: T, focus?: OrderTicketFocusControl): Promise T: Type parameter extending PreOrder order: order to show in the dialog focus: input control to focus on when dialog is opened ``` -------------------------------- ### Initialize WebSocket Connection and Event Listeners Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/implement-streaming.md Establishes a WebSocket connection to the CryptoCompare streaming API using the imported API key. It sets up event listeners for 'open', 'close', and 'error' events to log connection status. Includes placeholder export functions for stream subscription and unsubscription. ```JavaScript 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 } ``` -------------------------------- ### setQty(symbol, quantity): void Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/trading-hostreceives-trading-information-from-your-backend-server-and-provides-the-library-with-updates.md Sets the quantity for a given symbol. ```APIDOC Method: setQty Signature: setQty(symbol, quantity): void Description: Sets the quantity for a given symbol. Parameters: symbol: string - symbol quantity: number - quantity to update Returns: void ``` -------------------------------- ### Example: Disable Specific Chart Features Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-chartinglibrarywidgetoptions.md Demonstrates how to use the `disabled_features` array to disable multiple chart components. This example disables both the 'header_widget' and 'left_toolbar'. ```javascript disabled_features: ["header_widget", "left_toolbar"], ``` -------------------------------- ### Example: Solid Color Hex Value Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-studyfilledareasolidcolorstyle.md A simple example demonstrating the format for a hexadecimal color string used by the `color` property within the `StudyFilledAreaSolidColorStyle` interface. ```JavaScript '#ffffff' ``` -------------------------------- ### Importing Helper Functions for Streaming Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/implement-streaming.md This snippet demonstrates how to import essential helper functions, `parseFullSymbol` and `apiKey`, from a local `helpers.js` file. These functions are crucial for correctly parsing symbol information and potentially for authentication within the streaming module. ```JavaScript import { parseFullSymbol, apiKey } from './helpers.js'; ``` -------------------------------- ### Example: Setting Widget Width Property Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-chartinglibrarywidgetoptionsfavorites.md An example of how to set the `width` property within a widget configuration. This snippet shows a direct assignment of a numerical value. ```Configuration width: 300, ``` -------------------------------- ### TradingTerminalWidgetOptions Interface Reference Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/Charting_Library.TradingTerminalWidgetOptions/trading-platform-widget-optionsproperties-for-trading-platform-widget-to-customize-its-appearance-and-behavior.md Detailed API documentation for the `TradingTerminalWidgetOptions` interface, including its hierarchy, properties, types, descriptions, and usage examples for configuring the TradingView Charting Library's Trading Terminal. ```APIDOC Interface: TradingTerminalWidgetOptions Hierarchy: `Omit`<`ChartingLibraryWidgetOptions`, `"enabled_features"` | `"disabled_features"` | `"favorites"`> ↳ `TradingTerminalWidgetOptions` Properties: additional_symbol_info_fields: `AdditionalSymbolInfoField`[] (Optional) Description: 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. Example: ``` additional_symbol_info_fields: [ { title: 'Ticker', propertyName: 'ticker' } ] ``` auto_save_delay: `number` (Optional) Description: A threshold delay in seconds that is used to reduce the number of `onAutoSaveNeeded` calls. Example: ``` auto_save_delay: 5, ``` autosize: `boolean` (Optional) Description: 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 Example: ``` autosize: true, ``` brokerConfig: `SingleBrokerMetaInfo` (Optional) Description: (Deprecated) 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` (Optional) Description: Defines the [configuration flags](https://www.tradingview.com/charting-library-docs/latest/trading_terminal/trading-concepts/trading-features-configuration) for the Trading Platform. charts_storage_api_version: `AvailableSaveloadVersions` (Optional) Description: A version of your backend. Supported values are: `"1.0"` | `"1.1"`. Study Templates are supported starting from version `"1.1"`. Example: ``` charts_storage_api_version: "1.1", ``` charts_storage_url: `string` (Optional) Description: 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/saving_loading/save-load-rest-api/) for more information. Example: ``` charts_storage_url: 'http://storage.yourserver.com', ``` client_id: `string` (Optional) Description: 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/) for more information. Example: ``` client_id: 'yourserver.com', ``` compare_symbols: `CompareSymbol`[] (Optional) Description: an array of custom compare symbols for the Compare window. Example: ``` compare_symbols: [ { symbol: 'DAL', title: 'Delta Air Lines' }, { symbol: 'VZ', title: 'Verizon' }, ], ``` container: `string` | `HTMLElement` Description: 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. Example: ``` container: "tv_chart_container", ``` or ``` container: document.getElementById("tv_chart_container"), ``` ``` -------------------------------- ### Add Postinstall Script for Charting Library Static Files Source: https://github.com/1of1adam/docs/blob/master/getting_started/npm.md Extends `package.json` with `postinstall` and `copy-files` scripts. This automation ensures that static assets from `node_modules/charting_library/` are automatically copied to a designated `public` folder (or similar static asset directory) after `npm install`, making them accessible for the application. ```json { "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" } } ``` -------------------------------- ### Example Custom Chart Description Function Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-tradingterminalwidgetoptionsdebugbroker.md A JavaScript example demonstrating how to implement a `custom_chart_description_function` that returns a Promise resolving to a dynamic chart description string for accessibility purposes. ```JavaScript custom_chart_description_function: (context) => { return Promise.resolve(`Chart ${context.chartIndex + 1} of ${context.chartCount}. ${context.chartTypeName} chart of ${context.symbol}.`);} ``` -------------------------------- ### Serve Static Files with npx serve Source: https://github.com/1of1adam/docs/blob/master/tutorials/connecting-data-via-datafeed-api.md Runs a local web server using `npx serve` to host the static files of the tutorial. This allows you to view the results of your implementation in a web browser and test the data connection. ```Shell npx serve ``` -------------------------------- ### Initialize Git Submodules for Charting Library Source: https://github.com/1of1adam/docs/blob/master/tutorials/connecting-data-via-datafeed-api.md Updates and initializes Git submodules, including the Charting Library itself, within the cloned tutorial repository. This command ensures all necessary dependencies and components are correctly set up for the project. ```Shell git submodule update --init --recursive ``` -------------------------------- ### Example: Setting Broker Debug Mode to Normal Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-tradingterminalwidgetoptions.md This example shows how to configure `debug_broker` to 'normal' to enable detailed logging for Broker API and Trading Host interactions. ```JavaScript debug_broker: 'normal', ``` -------------------------------- ### showSimpleConfirmDialog Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/trading-hostreceives-trading-information-from-your-backend-server-and-provides-the-library-with-updates.md Displays a simple confirmation dialog to a user and returns a Promise to the result. ```APIDOC showSimpleConfirmDialog(title: string, content: string | string, mainButtonText?: string, cancelButtonText?: string, showDisableConfirmationsCheckbox?: boolean): Promise title: title of the confirmation dialog content: content for the dialog mainButtonText: text for the main button (true result) cancelButtonText: text for the cancel button (false result) showDisableConfirmationsCheckbox: show disable confirmations checkbox within the dialog ``` -------------------------------- ### Example Format for LibrarySymbolInfo corrections Property Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-librarysymbolinfo.md Provides an example string format for the `corrections` property of the `LibrarySymbolInfo` interface, specifying session adjustments for specific trading days. ```text "1900F4-2350F4,1000-1845:20181113;1000-1400:20181114" ``` -------------------------------- ### API: Retrieve Server Time (GET /time) Source: https://github.com/1of1adam/docs/blob/master/connecting_data/udf.md Documents the `GET /time` endpoint for retrieving the current server time. The response is a numeric Unix timestamp without milliseconds. ```APIDOC GET /time Response: Numeric unix time without milliseconds. ``` ```text 1445324591 ``` -------------------------------- ### TradingView Charting Library Widget Options Reference Source: https://github.com/1of1adam/docs/blob/master/getting_started/online-editors.md Reference documentation for key configuration options of the TradingView Charting Library widget. This includes `custom_css_url` for applying custom styles and `library_path` for defining the base URL where library assets are located, crucial for correct widget initialization. ```APIDOC Charting_Library.ChartingLibraryWidgetOptions: custom_css_url: string Description: URL to a custom CSS file to apply additional styling. Note: The URL should be specified relative to the `library_path` option. library_path: string Description: The base URL for the charting library files. Example: 'https://charting-library.tradingview-widget.com/charting_library/' ``` -------------------------------- ### Configure Pane Background Gradient Start Color Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-chartpropertiesoverrides.md Sets the start color for the background gradient of the chart pane. This property expects a string representing a color value. ```APIDOC paneProperties.backgroundGradientStartColor: string ``` ```javascript "#ffffff" ``` -------------------------------- ### Configure and Run NGINX as Local Server Source: https://github.com/1of1adam/docs/blob/master/tutorials/running-the-library.md This NGINX server block configuration sets up a listener on port 9090, serving files from a specified absolute path, enabling local access to the charting library via NGINX. ```NGINX server { listen 9090; server_name localhost; location / { root ABSOLUTE_PATH_TO_THE_TUTORIAL_FOLDER; } } ``` -------------------------------- ### Example: Custom Formatters Configuration Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-tradingterminalwidgetoptionsfavorites.md Demonstrates how to configure `custom_formatters` with examples for `timeFormatter`, `dateFormatter`, `tickMarkFormatter`, `priceFormatterFactory`, and `studyFormatterFactory`. The `tickMarkFormatter` specifically highlights the need to display UTC dates. ```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; } } ``` -------------------------------- ### Example: Disabling Header Widget and Left Toolbar Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-tradingterminalwidgetoptions.md This example demonstrates how to disable specific UI features, such as the header widget and the left toolbar, by listing their names in the `disabled_features` array. ```JavaScript disabled_features: ["header_widget", "left_toolbar"], ``` -------------------------------- ### API: List of All Available Methods Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-ibrokerterminal.md A comprehensive list of all methods available in the trading platform API, covering account management, order handling, position management, and data subscriptions. ```APIDOC Methods: accountManagerInfo accountsMetainfo cancelOrder cancelOrders chartContextMenuActions closeIndividualPosition closePosition connectionStatus currentAccount editIndividualPositionBrackets editPositionBrackets executions formatter getOrderDialogOptions getPositionDialogOptions getSymbolSpecificTradingOptions individualPositions isTradable leverageInfo modifyOrder orders ordersHistory placeOrder positions previewLeverage previewOrder quantityFormatter reversePosition setCurrentAccount setLeverage spreadFormatter subscribeEquity subscribeMarginAvailable subscribePipValue symbolInfo unsubscribeEquity unsubscribeMarginAvailable unsubscribePipValue ``` -------------------------------- ### Example: Setting Study Plot Display Mode to None Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-studycharsplotpreferences.md This example demonstrates how to set the `display` property of a study plot to `StudyPlotDisplayTarget.None`, which instructs the charting library not to display the plot. ```TypeScript StudyPlotDisplayTarget.None // Do not display the plot. ``` -------------------------------- ### showPositionBracketsDialog Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/trading-hostreceives-trading-information-from-your-backend-server-and-provides-the-library-with-updates.md Shows the position brackets dialog. ```APIDOC showPositionBracketsDialog(position: Position | IndividualPosition, brackets: Brackets, focus: OrderTicketFocusControl): Promise position: position or individual position brackets: brackets for the position or individual position focus: input control to focus on when dialog is opened ``` -------------------------------- ### Define Chart Container Element Source: https://github.com/1of1adam/docs/blob/master/tutorials/running-the-library.md This HTML `div` element serves as the placeholder where the TradingView chart widget will be rendered by the JavaScript code. ```HTML
``` -------------------------------- ### API Comparison: Lightweight Charts™ vs. Advanced Charts Source: https://github.com/1of1adam/docs/blob/master/getting_started/other-tradingview-products.md This section compares common API methods and concepts between Lightweight Charts™ and Advanced Charts, outlining how similar functionalities are achieved in each library. ```APIDOC Functionality: Create a chart Lightweight Charts™: Method: createChart() Advanced Charts: Concept: Specify the Widget Constructor (https://www.tradingview.com/charting-library-docs/latest/core_concepts/Widget-Constructor) Functionality: Add a series of certain style Lightweight Charts™: Methods: - IChartApiBase.addLineSeries() (https://tradingview.github.io/lightweight-charts/docs/api/interfaces/IChartApiBase#addlineseries) - IChartApiBase.addCandlestickSeries() (https://tradingview.github.io/lightweight-charts/docs/api/interfaces/IChartApiBase#addcandlestickseries) Advanced Charts: Concept: Specify any series style using the 'overrides' property of the Widget Constructor. References: - Series Styles (https://www.tradingview.com/charting-library-docs/latest/customization/overrides/chart-overrides#chart-styles) - ChartingLibraryWidgetOptions.overrides (https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ChartingLibraryWidgetOptions/#overrides) Functionality: Get a pixel coordinate Lightweight Charts™: Method: ITimeScaleApi.timeToCoordinate() (https://tradingview.github.io/lightweight-charts/docs/api/interfaces/ITimeScaleApi#timetocoordinate) Advanced Charts: Note: Does not contain such method. As an alternative, consider using methods from the Charting_Library.ITimeScaleApi interface (https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.ITimeScaleApi). Functionality: Create a price line Lightweight Charts™: Method: ISeriesApi.createPriceLine() (https://tradingview.github.io/lightweight-charts/docs/api/interfaces/ISeriesApi#createpriceline) Advanced Charts: Methods: - Charting_Library.IChartWidgetApi.createOrderLine() (https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createorderline) - Charting_Library.IChartWidgetApi.createShape() (https://www.tradingview.com/charting-library-docs/latest/api/interfaces/Charting_Library.IChartWidgetApi#createshape) ``` -------------------------------- ### Generic Type Declaration Example Source: https://github.com/1of1adam/docs/blob/master/api/modules/module-formattername.md Illustrates a generic type declaration for a function. This example shows a function that accepts a value of a generic type `T` and returns `void`, detailing its parameters and return type. ```APIDOC Type declaration: ▸ (value: T): void Parameters: Name Type value T Returns: void ``` -------------------------------- ### Example: Custom Settings Adapter Configuration Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-chartinglibrarywidgetoptions.md Illustrates how to configure the `settings_adapter` option with placeholder functions for `initialSettings`, `setValue`, and `removeValue` to integrate custom storage logic. ```JavaScript settings_adapter: { initialSettings: { ... }, setValue: function(key, value) { ... }, removeValue: function(key) { ... },} ``` -------------------------------- ### Implement onReady Datafeed Method with Configuration Callback Source: https://github.com/1of1adam/docs/blob/master/tutorials/implement_datafeed_tutorial/implement-datafeed.md This JavaScript code snippet shows the implementation of the `onReady` method for the TradingView Datafeed API. It simulates an asynchronous operation using `setTimeout` to mimic a network request or data loading, and then calls the provided `callback` function, passing the `configurationData` object. This method is crucial for the charting library to retrieve the datafeed's capabilities and configuration upon initialization. ```JavaScript onReady: (callback) => { console.log('[onReady]: Method call'); setTimeout(() => callback(configurationData)); }, ``` -------------------------------- ### JavaScript: Custom Translate Function Example Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-tradingterminalwidgetoptionsfavorites.md Example demonstrating how to use the `custom_translate_function` property to rename the 'Trend Line' drawing tool to 'Line Drawing' in the Charting Library's user interface. ```JavaScript custom_translate_function: (originalText, singularOriginalText, translatedText) => { if (originalText === "Trend Line") { return "Line Drawing"; } return null; } ``` -------------------------------- ### Broker Factory Function Signature Example Source: https://github.com/1of1adam/docs/blob/master/api/interfaces/interface-tradingterminalwidgetoptions.md An example of the `broker_factory` function signature, which is used to create a broker instance within the TradingView Charting Library. It typically accepts a `host` object as a parameter. ```JavaScript broker_factory: function(host) { ... } ```