itgiup-lwc-plugins
v0.0.15
Published
Plugins for TradingView Lightweight Charts.
Readme
itgiup-lwc-plugins
A plugin for TradingView Lightweight Charts to display price ranges.
Installation
yarn install itgiup-lwc-plugins lightweight-chartsUsage
Path
The Path plugin allows you to draw custom polylines (paths) on your Lightweight Charts. You can create paths by clicking points on the chart, edit them by dragging points, and delete individual points or entire paths.
Basic Usage
import { createChart, LineSeries } from 'lightweight-charts';
import { PathPrimitive } from 'itgiup-lwc-plugins';
// Create a chart instance
const chart = createChart(document.getElementById('chart-container'), {
autoSize: true,
});
// Add a series
const lineSeries = chart.addSeries(LineSeries, {
color: '#000000',
});
// Create a path with predefined points
const path = new PathPrimitive([
{ time: 1609459200, price: 100 },
{ time: 1609545600, price: 150 },
{ time: 1609632000, price: 120 },
]);
// Attach the path to your series
lineSeries.attachPrimitive(path);Interactive Drawing Mode
The Path plugin supports an interactive drawing mode where users can click to add points:
import { PathPrimitive } from 'itgiup-lwc-plugins';
// Toggle drawing mode (recommended for mobile)
const drawButton = document.getElementById('drawButton');
drawButton.addEventListener('click', () => {
const result = PathPrimitive.toggleDrawing(chart, lineSeries, (completedPath) => {
console.log('Path completed with points:', completedPath.points());
// Store the path reference for later use
allPaths.push(completedPath);
drawButton.textContent = 'Draw Path';
});
// Update button text based on state
if (result) {
drawButton.textContent = 'Stop Drawing';
} else {
drawButton.textContent = 'Draw Path';
}
});
// Or use separate start/stop methods
PathPrimitive.startDrawing(chart, lineSeries, (completedPath) => {
console.log('Path completed');
});
// Stop drawing programmatically
PathPrimitive.stopDrawing();
// Check if currently drawing
const isDrawing = PathPrimitive.isDrawing();
// Get the currently active drawing path
const activePath = PathPrimitive.getActiveDrawingPath();Customization Options
You can customize the appearance of paths:
import { LineStyle } from 'lightweight-charts';
import { PathPrimitive } from 'itgiup-lwc-plugins';
const customPath = new PathPrimitive(
[
{ time: 1609459200, price: 100 },
{ time: 1609545600, price: 150 },
],
{
lineColor: 'rgba(255, 0, 0, 1)',
lineWidth: 3,
lineStyle: LineStyle.Dashed,
pointColor: 'rgba(255, 0, 0, 1)',
pointRadius: 6,
selectedLineColor: 'rgba(255, 100, 0, 1)',
selectedPointColor: 'rgba(255, 200, 0, 1)',
}
);
lineSeries.attachPrimitive(customPath);Available Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| lineColor | string | 'rgba(0, 122, 255, 1)' | Color of the path line |
| lineWidth | number | 2 | Width of the path line |
| lineStyle | LineStyle | LineStyle.Solid | Style of the line (Solid, Dotted, Dashed, etc.) |
| hoverLineColor | string | 'rgba(0, 122, 255, 0.8)' | Color when hovering over the line |
| selectedLineColor | string | 'rgba(0, 80, 255, 1)' | Color when the path is selected |
| pointColor | string | 'rgba(0, 122, 255, 1)' | Color of the path points |
| pointRadius | number | 5 | Radius of the path points |
| hoverPointColor | string | 'rgba(0, 122, 255, 0.8)' | Color when hovering over points |
| selectedPointColor | string | 'rgba(223, 172, 5, 1)' | Color when a point is selected |
User Interactions
Drawing Mode:
- Click on the chart to add points to the path
- Double-click anywhere to finish drawing
- Click the toggle button again to stop drawing
- Press Escape to finish drawing
- Click on existing points while drawing to edit them
Editing Mode (Desktop):
- Click on any point to select it
- Move mouse to preview new position
- Click to confirm the new position
- Click far away (>50px) to cancel and deselect
- Delete or Backspace key to remove the selected point
- Click on the delete button (red circle on first point) to remove the entire path
- Escape to deselect the current point
Editing Mode (Mobile/Touch):
- Tap on any point to select it
- Tap near the point (<50px) to move it to that position
- Tap repeatedly to fine-tune position
- Tap far away (>50px) to deselect
- Tap on another point to switch to editing that point
Path Management
// Get all points in a path
const points = path.points();
// Check if path is selected
const isSelected = path.isSelected();
// Set selection state
path.setSelected(true);
// Delete the entire path
path.deletePath();
// Destroy and remove from chart
path.destroy();Keyboard Event Handling
The Path plugin handles keyboard events for better user experience:
// Handle keyboard events in your application
document.addEventListener('keydown', (event) => {
// Let the path handle the event
const handled = path.handleKeyDown(event);
if (handled) {
event.preventDefault();
}
});Priceranges
This plugin allows you to draw custom price ranges on your Lightweight Charts series. Here's a basic example of how to use it:
import { CrosshairMode, LineSeries, createChart } from 'lightweight-charts';
import { Priceranges } from 'itgiup-lwc-plugins';
// Create a chart instance
const chart = createChart(document.getElementById('chart-container'), {
autoSize: true,
crosshair: {
mode: CrosshairMode.Normal
},
});
// Add a line series
const lineSeries = chart.addSeries(LineSeries, {
color: '#000000',
});
// Set your data for the line series
// const data = generateLineData(); // Replace with your actual data
// lineSeries.setData(data);
// Define your price range points
// Example points (replace with your actual data points)
const time1 = /* your first time point */;
const price1 = /* your first price point */;
const time2 = /* your second time point */;
const price2 = /* your second price point */;
const primitive = new Priceranges(
{ price: price1, time: time1 },
{ price: price2, time: time2 }
);
// Attach the price range primitive to your series
lineSeries.attachPrimitive(primitive);
// Remember to update your chart and series data as neededExample from example.ts
import { CrosshairMode, LineSeries, createChart } from 'lightweight-charts';
import { generateLineData } from './sample-data';
import { Priceranges } from 'itgiup-lwc-plugins';
const chart = ((window as unknown as any).chart = createChart('chart', {
autoSize: true,
crosshair: {
mode: CrosshairMode.Normal
},
}));
const lineSeries = chart.addSeries(LineSeries, {
color: '#000000',
});
const data = generateLineData();
lineSeries.setData(data);
Priceranges.setChart(chart);
Priceranges.setTargetSeries(lineSeries);
const time1 = data[data.length - 50].time;
const time2 = data[data.length - 10].time;
const primitive = new Priceranges(
{ price: 100, time: time1 },
{ price: 500, time: time2 }
);
lineSeries.attachPrimitive(primitive);
function calculateVolumeForPriceRange(priceRange: Priceranges) {
let totalVolume = 0;
const p1Time = priceRange.p1.time as number;
const p2Time = priceRange.p2.time as number;
const minTime = Math.min(p1Time, p2Time);
const maxTime = Math.max(p1Time, p2Time);
for (const candle of volumes.data) {
const candleTime = candle.time as number; // Convert to milliseconds for comparison with p1Time/p2Time
const candleVolume = candle.value;
if (candleTime >= minTime && candleTime <= maxTime) {
totalVolume += candleVolume;
}
}
return totalVolume;
}
// Set callback for price range modifications
Priceranges.setOnPriceRangeModified(() => {
// Update volumes with custom color for volume label
Priceranges.updateAllVolumes(calculateVolumeForPriceRange);
});Source code
https://github.com/itgiup/lwc-plugins/
Demo
https://itgiup-lwc-plugins.pages.dev/
Features
- Improved Drag Behavior: Dragging price range handles (top/bottom) now works independently, preventing unintended movement of the opposite handle.
- Selected Handle Highlighting: The actively selected price range handle is visually highlighted for better user feedback.
- Enhanced Usability: Increased the size of corner handles for easier selection.
- Refined Aesthetics: Reduced the border thickness of the price range box for a cleaner look.
Running the Example Application
To run the interactive example application with the chart and its features:
Install Dependencies: Open your terminal in the project root directory (
itgiup-lwc-plugins/) and run:yarn installStart the Development Server: After installing dependencies, run the development script:
yarn devAccess the Application: Once the development server starts, it will typically provide a local URL (e.g.,
http://localhost:5173). Open this URL in your web browser to see the chart with the symbol and timeframe selectors, the reset scale button, and the updated price range drawing functionality including volume display.
New Features in Example Application
The example application has been enhanced with the following features:
- Dynamic Symbol Selection: Use the dropdown to choose from a comprehensive list of active trading pairs fetched directly from Binance (e.g., BTCUSDT, ETHUSDT). The chart will automatically update with data for the selected symbol.
- Timeframe Selection: A dedicated dropdown allows you to easily switch between various candlestick intervals (e.g., 1m, 5m, 1h, 1d). The chart will re-render to reflect the chosen timeframe.
- Price Range Volume Display: When you draw a price range, it now displays the aggregated trading volume within its time and price boundaries. This volume is dynamically calculated and updated when:
- The chart's symbol or timeframe changes.
- The price range itself is dragged or resized by the user.
- Reset Chart Scale: A "Reset Scale" button has been added to quickly adjust the chart's time and price scales to fit all visible data, providing a convenient way to revert zoom and pan operations.
- Delete Price Range with Keyboard: Select a drawn price range by clicking on it. You can now press the
DeleteorBackspacekey on your keyboard to remove the selected price range from the chart.
Contributing
(Add information on how others can contribute to your project)
License
This project is licensed under the MIT License - see the LICENSE file for details.
