### Start Plugin Examples Development Server
Source: https://github.com/tradingview/lightweight-charts/blob/master/plugin-examples/README.md
Navigate to the plugin-examples folder, install dependencies, and start the development server. The development server will be available at localhost:5173 for testing and viewing plugin examples.
```shell
cd plugin-examples
npm install
npm run dev
```
--------------------------------
### Install example dependencies with CocoaPods
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/ios.md
Run this command in the example directory to install the necessary dependencies for the LightweightChartsIOS example project.
```sh
pod install
```
--------------------------------
### Run Lightweight Charts Indicator Examples Locally using npm
Source: https://github.com/tradingview/lightweight-charts/blob/master/indicator-examples/README.md
This snippet provides the shell commands to navigate into the indicator examples directory, install its specific dependencies, and start the development server. After execution, the examples will be accessible in a web browser at `localhost:5173`.
```shell
cd indicator-examples
npm install
npm run dev
```
--------------------------------
### Clone and setup React Parcel starter kit
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/react/01-simple.mdx
Initialize a new project by cloning the Parcel starter kit repository and installing dependencies. This sets up the development environment for embedding Lightweight Charts™ in React.
```console
git clone git@github.com:brandiqa/react-parcel-starter.git lwc-react
cd lwc-react
npm install
```
--------------------------------
### Run React development server
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/react/01-simple.mdx
Execute the npm start command to launch the development server locally. The application will be accessible at http://localhost:1234 in the web browser.
```console
npm start
```
--------------------------------
### Build Lightweight Charts Library using npm
Source: https://github.com/tradingview/lightweight-charts/blob/master/indicator-examples/README.md
This snippet shows the shell commands required to install dependencies and build the Lightweight Charts library. This step is a prerequisite for running the indicator examples locally.
```shell
npm install
npm run build:prod
```
--------------------------------
### Install lightweight-charts via npm
Source: https://github.com/tradingview/lightweight-charts/blob/master/README.md
Use this command to install the stable version of the lightweight-charts library from npm.
```bash
npm install lightweight-charts
```
--------------------------------
### Install Dependencies with npm
Source: https://github.com/tradingview/lightweight-charts/blob/master/packages/create-lwc-plugin/BUILDING.md
Installs all project dependencies required for development and building. This command reads the package.json and package-lock.json files to install exact versions of dependencies needed for the create-lwc-plugin project.
```shell
npm install
```
--------------------------------
### Compile Lightweight Charts Indicator Examples
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/analysis-indicators.mdx
Steps to navigate to the indicator examples directory, install its dependencies, and compile the examples after the main library has been built. The compiled output will be in the `indicator-examples/compiled` folder.
```shell
cd indicator-examples
npm install
npm run compile
```
--------------------------------
### Test Case Initialization Script
Source: https://github.com/tradingview/lightweight-charts/blob/master/tests/e2e/coverage/helpers/test-page-dummy.html
Global setup logic to initialize interaction sequences and prepare the DOM container for testing.
```javascript
window.interactions = interactionsToPerform(); window.finishedSetup = beforeInteractions( document.getElementById('container') );
```
--------------------------------
### Compile Lightweight Charts Indicator Examples using npm
Source: https://github.com/tradingview/lightweight-charts/blob/master/indicator-examples/README.md
This snippet demonstrates the shell command to compile the Lightweight Charts indicator examples. The compiled output will be generated and placed into the `compiled` folder, ready for integration into other projects.
```shell
npm run compile
```
--------------------------------
### Install Lightweight Charts npm package
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/intro.mdx
Install the lightweight-charts package from npm to use the library in your project.
```console
npm install --save lightweight-charts
```
--------------------------------
### Initialize Test Case Interactions in JavaScript
Source: https://github.com/tradingview/lightweight-charts/blob/master/tests/e2e/interactions/helpers/test-page-dummy.html
This snippet demonstrates how to initialize the setup process for a test case by calling beforeInteractions on a specific DOM element. It assigns the result to a global window property to signal that the setup is finished.
```javascript
window.finishedSetup = beforeInteractions(document.getElementById('container'));
```
--------------------------------
### Basic implementation of the IPanePrimitive interface (JavaScript)
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/plugins/pane-primitives.md
This example shows the basic structure for implementing a custom Pane Primitive, focusing on the `paneViews` method which defines the drawing logic for the chart pane.
```javascript
class MyCustomPanePrimitive {
paneViews() {
return [
{
renderer: {
draw: target => {
// Custom drawing logic here
},
},
},
];
}
// Other methods as needed...
}
```
--------------------------------
### Create a Yield Curve Chart with Line Series
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/chart-types.mdx
This example demonstrates creating a yield curve chart with custom options, adding a LineSeries, setting yield curve data, and fitting the content to the time scale.
```js
const chartOptions = {
layout: { textColor: CHART_TEXT_COLOR, background: { type: 'solid', color: CHART_BACKGROUND_COLOR } },
yieldCurve: { baseResolution: 1, minimumTimeRange: 10, startTimeRange: 3 },
handleScroll: false, handleScale: false,
};
const chart = createYieldCurveChart(document.getElementById('container'), chartOptions);
const lineSeries = chart.addSeries(LineSeries, { color: LINE_LINE_COLOR });
const curve = [{ time: 1, value: 5.378 }, { time: 2, value: 5.372 }, { time: 3, value: 5.271 }, { time: 6, value: 5.094 }, { time: 12, value: 4.739 }, { time: 24, value: 4.237 }, { time: 36, value: 4.036 }, { time: 60, value: 3.887 }, { time: 84, value: 3.921 }, { time: 120, value: 4.007 }, { time: 240, value: 4.366 }, { time: 360, value: 4.290 }];
lineSeries.setData(curve);
chart.timeScale().fitContent();
```
--------------------------------
### Chart Initialization and Event Listener Setup
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/a11y/assets/a11y-chart.html
Initializes the Lightweight Chart with auto-sizing and time scale options, adds a line series, and attaches event listeners to UI buttons and checkboxes for interactive control.
```javascript
const chart = createChart('chart', {
autoSize: true,
timeScale: { rightOffset: 20, barSpacing: 3 }
});
const mainSeries = chart.addSeries(LineSeries, {
priceFormat: { minMove: 1, precision: 0 },
title: 'A11y'
});
mainSeries.setData(generateSampleData());
document.querySelector('#random-data-button')?.addEventListener('click', () => {
mainSeries.setData(generateSampleData());
});
document.querySelector('#high-contrast-checkbox')?.addEventListener('change', event => {
setHighContrast(event.target.checked);
});
document.querySelector('#reset-chart-button')?.addEventListener('click', () => {
chart.timeScale().resetTimeScale();
mainSeries.priceScale().applyOptions({ autoScale: true });
});
```
--------------------------------
### Configure Lightweight Charts layout and localization
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/android.md
Apply custom layout and localization options to the chart's API. This example sets background color, text color, locale, and custom formatters for price and time.
```kotlin
charts_view.api.applyOptions {
layout = layoutOptions {
background = SolidColor(Color.LTGRAY)
textColor = Color.BLACK.toIntColor()
}
localization = localizationOptions {
locale = "ru-RU"
priceFormatter = PriceFormatter(template = "{price:#2:#3}$")
timeFormatter = TimeFormatter(
locale = "ru-RU",
dateTimeFormat = DateTimeFormat.DATE_TIME
)
}
}
```
--------------------------------
### Install latest master build via npm
Source: https://github.com/tradingview/lightweight-charts/blob/master/README.md
Install the latest development build directly from the master branch using this npm command. This allows testing unreleased features.
```bash
npm install https://pkg.pr.new/lightweight-charts@master
```
--------------------------------
### Build Package for Publishing with npm
Source: https://github.com/tradingview/lightweight-charts/blob/master/packages/create-lwc-plugin/BUILDING.md
Runs the prepublishOnly script to build and prepare the package for publication to NPM. This script handles all necessary build steps and validation before the package is ready for publishing.
```shell
npm run prepublishOnly
```
--------------------------------
### Example: Tag Docusaurus Documentation Version 3.7.0 (npm)
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/README.md
This provides a concrete example of how to tag a new version for the Docusaurus documentation, specifically version `3.7.0`. This command helps in managing and publishing different versions of the documentation content.
```bash
npm run docusaurus docs:version 3.7.0
```
--------------------------------
### Create a Standard Time-based Chart with Area Series
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/chart-types.mdx
This example demonstrates creating a standard time-based chart with custom layout options, adding an AreaSeries, setting data, and fitting the content to the time scale.
```js
const chartOptions = { layout: { textColor: CHART_TEXT_COLOR, background: { type: 'solid', color: CHART_BACKGROUND_COLOR } } };
const chart = createChart(document.getElementById('container'), chartOptions);
const areaSeries = chart.addSeries(AreaSeries, { lineColor: LINE_LINE_COLOR, topColor: AREA_TOP_COLOR, bottomColor: AREA_BOTTOM_COLOR });
const data = [{ value: 0, time: 1642425322 }, { value: 8, time: 1642511722 }, { value: 10, time: 1642598122 }, { value: 20, time: 1642684522 }, { value: 3, time: 1642770922 }, { value: 43, time: 1642857322 }, { value: 41, time: 1642943722 }, { value: 43, time: 1643030122 }, { value: 56, time: 1643116522 }, { value: 46, time: 1643202922 }];
areaSeries.setData(data);
chart.timeScale().fitContent();
```
--------------------------------
### Handling Different Time Types with Helpers
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/migrations/from-v3-to-v4.md
This example shows how to use `isUTCTimestamp` and `isBusinessDay` helper functions to check the type of `param.time` within event handlers after the v4 migration.
```js
import {
createChart,
isUTCTimestamp,
isBusinessDay,
} from 'lightweight-charts';
const chart = createChart(document.body);
chart.subscribeClick(param => {
if (param.time === undefined) {
// the time is undefined, i.e. there is no any data point where a time could be received from
return;
}
if (isUTCTimestamp(param.time)) {
// param.time is UTCTimestamp
} else if (isBusinessDay(param.time)) {
// param.time is a BusinessDay object
} else {
// param.time is a business day string in ISO format, e.g. `'2010-01-01'`
}
});
```
--------------------------------
### Create Development Stub with npm
Source: https://github.com/tradingview/lightweight-charts/blob/master/packages/create-lwc-plugin/BUILDING.md
Runs the dev script to create a development stub for testing the plugin locally. This sets up a development environment for testing the create-lwc-plugin functionality before publishing.
```shell
npm run dev
```
--------------------------------
### Run CLI Locally with Node.js
Source: https://github.com/tradingview/lightweight-charts/blob/master/packages/create-lwc-plugin/BUILDING.md
Executes the create-lwc-plugin CLI tool directly using Node.js by running the index.js entry point. This allows testing the CLI functionality during local development.
```shell
node index.js
```
--------------------------------
### Initialize Lightweight Chart within Web Component (JavaScript)
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/webcomponents/01-custom-element.mdx
This JavaScript code completes the Web Component setup by initializing a Lightweight Chart instance. It uses the `createChart` function, passing the previously created container element, and stores the returned `IChartApi` instance for further interaction and data manipulation.
```js
const elementStyles = `
:host {
display: block;
}
:host[hidden] {
display: none;
}
.chart-container {
height: 100%;
width: 100%;
}
`;
// Inside LightweightChartWC class
connectedCallback() {
// Create the div container for the chart
const container = document.createElement('div');
container.setAttribute('class', 'chart-container');
// create the stylesheet for the custom element
const style = document.createElement('style');
style.textContent = elementStyles;
this.shadowRoot.append(style, container);
// Create the Lightweight Chart
this.chart = createChart(container);
}
```
--------------------------------
### Standalone HTML Page Example Using Custom Element
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/webcomponents/01-custom-element.mdx
This complete HTML file demonstrates how to integrate the `lightweight-chart` custom element into a web page. It includes loading the standalone Lightweight Charts library, defining basic styling, and instantiating the custom element with initial configuration and data.
```html
Web component Example
```
--------------------------------
### Validate Package Configuration with publint
Source: https://github.com/tradingview/lightweight-charts/blob/master/packages/create-lwc-plugin/BUILDING.md
Runs the latest version of publint to validate the generated package.json and ensure there are no configuration issues before publishing to NPM. This tool checks for common packaging problems and best practices.
```shell
npx publint@latest
```
--------------------------------
### Configure and Populate an Options Chart
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/chart-types.mdx
Demonstrates how to configure an options chart with layout options, add a line series, and populate it with sample data. The `timeScale().fitContent()` method adjusts the view to fit all data.
```js
const chartOptions = {
layout: { textColor: CHART_TEXT_COLOR, background: { type: 'solid', color: CHART_BACKGROUND_COLOR } },
};
const chart = createOptionsChart(document.getElementById('container'), chartOptions);
const lineSeries = chart.addSeries(LineSeries, { color: LINE_LINE_COLOR });
const data = [];
for (let i = 0; i < 1000; i++) {
data.push({
time: i * 0.25,
value: Math.sin(i / 100) + i / 500,
});
}
lineSeries.setData(data);
chart.timeScale().fitContent();
```
--------------------------------
### Complete HTML Code for Chart Customization
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/customization/chart-colors.mdx
This snippet contains the full HTML code for the chart customization example at this stage of the guide. It includes all necessary elements and configurations for rendering the chart with custom colors.
```html
Lightweight Charts - Custom Colors
```
--------------------------------
### Publish Package to NPM Registry
Source: https://github.com/tradingview/lightweight-charts/blob/master/packages/create-lwc-plugin/BUILDING.md
Publishes the built package to the NPM registry, making it available for public installation. Can be appended with --dry-run flag to preview the publish results without actually uploading to NPM.
```shell
npm publish
```
```shell
npm publish --dry-run
```
--------------------------------
### Apply Crosshair Options in Lightweight Charts
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/customization/crosshair.mdx
Customizes the crosshair appearance and behavior by applying options to the chart instance. This example sets the crosshair mode to 'normal' for free movement, styles the vertical line with a spotlight effect (width 8, semi-transparent color), and configures both lines with custom colors and label backgrounds. The code should be placed after chart creation and price formatter setup.
```javascript
// Customizing the Crosshair
chart.applyOptions({
crosshair: {
// Change mode from default 'magnet' to 'normal'.
// Allows the crosshair to move freely without snapping to datapoints
mode: LightweightCharts.CrosshairMode.Normal,
// Vertical crosshair line (showing Date in Label)
vertLine: {
width: 8,
color: '#C3BCDB44',
style: LightweightCharts.LineStyle.Solid,
labelBackgroundColor: '#9B7DFF',
},
// Horizontal crosshair line (showing Price in Label)
horzLine: {
color: '#9B7DFF',
labelBackgroundColor: '#9B7DFF',
},
},
});
```
--------------------------------
### Start Local Development Server for Docusaurus Website (npm)
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/README.md
This command initiates a local development server for the Docusaurus website and automatically opens it in your browser. Most changes made to the source code are reflected live without requiring a server restart. Note that API documentation will only be generated if the library and its `typings.d.ts` file have been pre-built.
```bash
npm run start
```
--------------------------------
### Configure Existing Line Series with applyOptions in Lightweight Charts (JavaScript)
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/customization/_apply-options-tabs-partial.mdx
This example demonstrates how to modify the options of an already created line series using the `applyOptions` method. After adding a basic line series, this method is used to update its properties, such as setting the `color` to a specific hex value. This is useful for dynamic updates to series appearance.
```js
const lineSeries = chart.addSeries(LineSeries, {
});
lineSeries.applyOptions({
color: '#2962FF'
});
```
--------------------------------
### Install AI Coding Assistant Skill
Source: https://github.com/tradingview/lightweight-charts/blob/master/README.md
Install the Agent Skill for AI coding assistants to enable them to work with Lightweight Charts v5 API conventions. This streamlines chart scaffolding, series wiring, and API questions.
```console
npx skills add https://github.com/tradingview/lightweight-charts
```
--------------------------------
### Serve Built Docusaurus Website Locally (npm)
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/README.md
This command serves the previously built Docusaurus website locally, allowing you to preview the static content. It's important to note that embedded `.html` examples might not display correctly when served this way, but they will function as expected once hosted online.
```bash
npm run serve
```
--------------------------------
### Calculate Financial Statistics (High, Low, Start, Close) in JavaScript
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/a11y/assets/a11y-chart.html
This JavaScript function, 'getStats', processes an array of financial data points to determine the starting value, closing value, lowest value, and highest value. It iterates through the data to identify the extreme points, returning an object containing these key statistics.
```javascript
function getStats(data) {
const stats = { start: data[0], close: data[data.length - 1], low: data[0], high: data[0], };
for (const point of data) {
if (point.value > stats.high.value) {
stats.high = point;
}
if (point.value < stats.low.value) {
stats.low = point;
}
}
return stats;
}
```
--------------------------------
### Customize Crosshair Mode
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/customization/assets/step8.html
Configures the chart's crosshair. This example changes the crosshair mode from the default 'magnet' to 'normal'.
```javascript
chart.applyOptions({
crosshair: {
// Change mode from default 'magnet' to 'normal'.
},
});
```
--------------------------------
### Install Lightweight Charts iOS wrapper with CocoaPods
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/ios.md
Add this line to your Podfile to integrate LightweightCharts into your Xcode project using CocoaPods.
```ruby
pod 'LightweightCharts', '~> 3.8.0'
```
--------------------------------
### Initialize a Standard Time-based Chart
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/chart-types.mdx
Import `createChart` and initialize a standard time-based chart, which is suitable for general financial and time series data.
```js
import { createChart } from 'lightweight-charts';
const chart = createChart(document.getElementById('container'), options);
```
--------------------------------
### Add Lightweight Charts CDN script to HTML head
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/customization/creating-a-chart.mdx
This snippet demonstrates how to include the Lightweight Charts library using a CDN. It adds a
```
--------------------------------
### Set Bar Spacing for Time Scale
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/customization/assets/step6.html
Adjusts the starting bar width, which affects the horizontal zoom level of the chart's time scale.
```javascript
chart.timeScale().applyOptions({
barSpacing: 10,
});
```
--------------------------------
### Using hoveredObjectId for Marker Identification
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/migrations/from-v3-to-v4.md
This example shows how to access the ID of a hovered or clicked object using the new `param.hoveredObjectId` property in `subscribeCrosshairMove` and `subscribeClick` handlers.
```js
chart.subscribeCrosshairMove(param => {
console.log(param.hoveredObjectId);
});
chart.subscribeClick(param => {
console.log(param.hoveredObjectId);
});
```
--------------------------------
### Deploy Docusaurus Website to GitHub Pages (npm)
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/README.md
This command builds the Docusaurus website into static files and then pushes these files to the `gh-pages` branch for deployment. You must replace the placeholders with your GitHub username and organization name, and ensure `USE_SSH=true` is set. As with other build processes, API documentation generation depends on a pre-built library and its `typings.d.ts` file.
```bash
GIT_USER= GITHUB_ORGANIZATION_NAME= USE_SSH=true npm deploy
```
--------------------------------
### Invert Specific Price Scale
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/how_to/inverted-price-scale.mdx
Get a specific price scale by its ID and apply the `invertScale: true` option to it. This allows for granular control over individual scales.
```javascript
const priceScale = chart.priceScale('right');
priceScale.applyOptions({
invertScale: true,
});
```
--------------------------------
### Apply Custom CSS Styling
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/customization/assets/step2.html
Example of applying custom CSS to style the chart's background. This targets the chart container and sets a dark background color.
```css
body {
padding: 0;
margin: 0;
/* Add a background color to match the chart */
background-color: #222;
}
```
--------------------------------
### Chart Initialization and Styling
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/customization/assets/step4.html
Initializes a Lightweight Chart with custom background, text, and grid colors. It also sets border colors for the price scales.
```javascript
const chart = LightweightCharts.createChart( document.getElementById('container'), {
layout: {
background: { color: "#222" },
textColor: "#C3BCDB",
},
grid: {
vertLines: { color: "#444" },
horzLines: { color: "#444" },
},
} );
chart.priceScale('right').applyOptions({
borderColor: "#71649C",
});
chart.timeScale().applyOptions({
borderColor: "#71649C",
});
```
--------------------------------
### Initialize Lightweight Charts with Candlestick Data and Resize Handling
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/customization/assets/step1.html
This snippet demonstrates how to set up a basic candlestick chart using the Lightweight Charts library. It includes a function to generate sample candlestick data, creates a chart instance within a specified DOM element, adds a candlestick series, sets the data, and implements a window resize listener to ensure the chart adjusts to layout changes.
```javascript
function generateCandlestickData() {
return [
{ time: "2019-04-17", open: 205.34, high: 206.84, low: 205.32, close: 206.55 },
{ time: "2019-04-18", open: 206.02, high: 207.78, low: 205.1, close: 205.66 },
{ time: "2019-04-22", open: 204.11, high: 206.25, low: 204.0, close: 204.78 },
{ time: "2019-04-23", open: 205.14, high: 207.33, low: 203.43, close: 206.05 },
{ time: "2019-04-24", open: 206.16, high: 208.29, low: 205.54, close: 206.72 },
{ time: "2019-04-25", open: 206.01, high: 207.72, low: 205.06, close: 206.5 },
{ time: "2019-04-26", open: 205.88, high: 206.14, low: 203.34, close: 203.61 },
{ time: "2019-04-29", open: 203.31, high: 203.8, low: 200.34, close: 202.16 },
{ time: "2019-04-30", open: 201.55, high: 203.75, low: 200.79, close: 203.7 },
{ time: "2019-05-01", open: 203.2, high: 203.52, low: 198.66, close: 198.8 },
{ time: "2019-05-02", open: 199.3, high: 201.06, low: 198.8, close: 201.01 },
{ time: "2019-05-03", open: 202.0, high: 202.31, low: 200.32, close: 200.56 },
{ time: "2019-05-06", open: 198.74, high: 199.93, low: 198.31, close: 199.63 },
{ time: "2019-05-07", open: 196.75, high: 197.65, low: 192.96, close: 194.77 },
{ time: "2019-05-08", open: 194.49, high: 196.61, low: 193.68, close: 195.17 },
{ time: "2019-05-09", open: 193.31, high: 195.08, low: 191.59, close: 194.58 },
{ time: "2019-05-10", open: 193.21, high: 195.49, low: 190.01, close: 194.58 },
{ time: "2019-05-13", open: 191.0, high: 191.66, low: 189.14, close: 190.34 },
{ time: "2019-05-14", open: 190.5, high: 192.76, low: 190.01, close: 191.62 },
{ time: "2019-05-15", open: 190.81, high: 192.81, low: 190.27, close: 191.76 },
{ time: "2019-05-16", open: 192.47, high: 194.96, low: 192.2, close: 192.38 },
{ time: "2019-05-17", open: 190.86, high: 194.5, low: 190.75, close: 192.58 },
{ time: "2019-05-20", open: 191.13, high: 192.86, low: 190.61, close: 190.95 },
{ time: "2019-05-21", open: 187.13, high: 192.52, low: 186.34, close: 191.45 },
{ time: "2019-05-22", open: 190.49, high: 192.22, low: 188.05, close: 188.91 },
{ time: "2019-05-23", open: 188.45, high: 192.54, low: 186.27, close: 192.0 },
{ time: "2019-05-24", open: 192.54, high: 193.86, low: 190.41, close: 193.59 }
];
}
// Create the Lightweight Chart within the container element
const chart = LightweightCharts.createChart(
document.getElementById('container')
);
// Generate sample data to use within a candlestick series
const candleStickData = generateCandlestickData();
// Create the Main Series (Candlesticks)
const mainSeries = chart.
```
--------------------------------
### calculateColumnPositions
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/plugins/pixel-perfect-rendering/widths/columns.md
Calculates the column positions and widths for the x positions. This function creates a new array. You may get faster performance using the `calculateColumnPositionsInPlace` function instead.
```APIDOC
## Function: `calculateColumnPositions`
### Description
Calculates the column positions and widths for the x positions. This function creates a new array. You may get faster performance using the `calculateColumnPositionsInPlace` function instead.
### Signature
`calculateColumnPositions(xMediaPositions: number[], barSpacingMedia: number, horizontalPixelRatio: number): ColumnPosition[]`
### Parameters
- **xMediaPositions** (number[]) - x positions for the bars in media coordinates
- **barSpacingMedia** (number) - spacing between bars in media coordinates
- **horizontalPixelRatio** (number) - horizontal pixel ratio
### Returns
(ColumnPosition[]) - Positions for the columns
```
--------------------------------
### Import createChart function
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/versioned_docs/version-5.2/intro.mdx
Import the createChart function from the lightweight-charts library to begin creating charts.
```js
import { createChart } from 'lightweight-charts';
```
--------------------------------
### Comprehensive JavaScript Functions for Chart Description Generation
Source: https://github.com/tradingview/lightweight-charts/blob/master/website/tutorials/a11y/screenreader.mdx
This set of JavaScript functions provides a starting point for generating detailed, human-readable descriptions of financial charts. It includes utilities for formatting dates and values, calculating statistical data (start, end, high, low prices), extracting visible series data, and composing a descriptive string based on these statistics. This logic helps translate complex chart data into accessible text for screen readers.
```js
function formatDate(time) {
return new Date(time * 1000).toDateString();
}
function formatValue(value) {
return `${value < 0 ? '-' : ''}$${Math.abs(value).toFixed(2)}`;
}
function getStats(data) {
const stats = {
start: data[0],
close: data[data.length - 1],
low: data[0],
high: data[0]
};
for (const point of data) {
if (point.value > stats.high.value) {
stats.high = point;
}
if (point.value < stats.low.value) {
stats.low = point;
}
}
return stats;
}
function getVisibleSeriesData(chart, series) {
const timeScale = chart.timeScale();
const visibleRange = timeScale.getVisibleLogicalRange();
const data = [];
for (let i = Math.round(visibleRange.from); i <= visibleRange.to; i++) {
const d = series.dataByIndex(i, 0);
if (d !== null) {
data.push(d);
}
}
return data;
}
function describeFinanceChart(data) {
if (!data || data.length === 0) {
return 'The data set is empty.';
}
const stats = getStats(data);
const firstPrice = `The first price is ${formatValue(
stats.start.value
)} at ${formatDate(stats.start.time)}.`;
const lastPrice = `The last price is ${formatValue(
stats.close.value
)} at ${formatDate(stats.close.time)}.`;
const actualChange = stats.close.value - stats.start.value;
const percentChange = (actualChange / stats.start.value) * 100;
const changeDescription = `The actual change in price was ${formatValue(
actualChange
)}, corresponding to a percentage change of ${percentChange.toFixed(2)}%.`;
let lowHigh = '';
if (
stats.low.time !== stats.start.time &&
stats.low.time !== stats.close.time
) {
lowHigh += `The lowest price was ${formatValue(
stats.low.value
)} at ${formatDate(stats.low.time)}.`;
}
if (
stats.high.time !== stats.start.time &&
stats.high.time !== stats.close.time
) {
lowHigh += ` The highest price was ${formatValue(
stats.high.value
)} at ${formatDate(stats.high.time)}.`;
}
return `${firstPrice} ${lastPrice} ${changeDescription} ${lowHigh}`.trim();
}
```