UNPKG

trace-chart

Version:

A lightweight, fully customizable financial charting library for global markets

449 lines (352 loc) 12.7 kB
<a href="https://zerodha.tech"><img src="https://zerodha.tech/static/images/github-badge.svg" align="right" /></a> <br> <div align="center"> <img src="docs/images/trace-logo.png" alt="Trace Chart Logo" style="width: 225px;"> **A lightweight, fully customizable financial charting library for global markets** <p style="font-size: 13px;">Built on <a href="https://echarts.apache.org/" target="_blank">Apache ECharts</a></p> [![npm version](https://badge.fury.io/js/trace-chart.svg)](https://www.npmjs.com/package/trace-chart) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0) <!-- [![Downloads](https://img.shields.io/npm/dm/trace-chart.svg)](https://www.npmjs.com/package/trace-chart) --> <a href="https://srv91.github.io/trace-chart/" target="_blank"><img src="docs/images/trace-demo.png" alt="Trace Chart Demo"></a> </div> Check out the <a href="https://srv91.github.io/trace-chart/" target="_blank">live demo</a>. <br> Built for trading applications with a modular architecture that's easy to customize and extend. Supports equities, forex, futures, options, and crypto trading with real-time data, technical indicators, and drawing tools. ## Features - **Lightweight Core**: Minimal bundle size with optional features - **Fully Customizable**: Every aspect can be configured or extended - **Chart Types**: Candlestick, Line, Bar, Mountain, Heikin Ashi - **Extendable Indicators**: Built-in SMA, EMA, RSI, MACD, Bollinger Bands + easy custom indicator creation - **Interactive Drawing Tools**: Lines, Rectangles, Circles with full editing support - **Performance-Optimized**: Incremental updates for smooth real-time data handling - **Multi-Market Ready**: Easily configurable for any market's trading hours - **Zero-Config Demo**: Works immediately with realistic data, no API required ## Installation & Setup ```bash npm install trace-chart ``` ### Basic usage ```html <!DOCTYPE html> <html> <head> <title>Trace</title> <!-- Required: ECharts --> <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script> </head> <body> <div id="chart-container" style="width: 100%; height: 600px;"></div> </body> </html> ``` ```javascript // ES Module - Works immediately with realistic demo data import TraceChart from 'trace-chart'; // Basic setup with demo data const chart = new TraceChart('#chart-container', { theme: { backgroundColor: '#1a1a1a', bullishColor: '#26a69a', bearishColor: '#ef5350' } }); // Symbol selection (works with demo data too) chart.setSymbol('RELIANCE', 'NSE'); chart.changeInterval('5min'); chart.changeChartType('candlestick'); ``` **That's it!** You now have a fully functional trading chart with toolbar, search, settings, indicators, and drawings. ### With Real API ```javascript const chart = new TraceChart('#chart', { api: { baseURL: '/api/quotes', refreshInterval: 1000 }, demo: { enabled: false // Use real data } }); // Performance-optimized real-time updates chart.setTick('RELIANCE', { lastPrice: 1500.75, volume: 1500000, timestamp: Date.now() }); ``` ## Easy Customization ### Theme Customization ```javascript const chart = new TraceChart('#chart', { // Complete theme customization theme: { backgroundColor: '#ffffff', // Light theme gridColor: '#e0e0e0', // Subtle grid textColor: '#333333', // Dark text bullishColor: '#00aa00', // Green candles bearishColor: '#ff0000' // Red candles }, // Modular feature toggles features: { crosshairEnabled: true, tooltipEnabled: true, volumeEnabled: true, drawingEnabled: true, // Disable to reduce bundle size indicatorsEnabled: true // Disable if not needed } }); ``` ### Minimal Configuration ```javascript // Streamlined setup for basic charts const minimalChart = new TraceChart('#chart', { features: { drawingEnabled: false, // Reduces bundle size indicatorsEnabled: false // Further optimization }, chartTypes: [ { id: 'line', name: 'Line', default: true } // Single chart type ], intervals: [ { id: '1D', name: '1 Day', default: true } // Single timeframe ] }); ``` ### Performance Tuning ```javascript // Optimized for high-frequency updates const chart = new TraceChart('#chart', { api: { refreshInterval: 500, // Balance between real-time and performance timeout: 10000, // Faster timeout retryAttempts: 1 // Quick failure recovery } }); ``` ## API Reference ### Simple Control Methods ```javascript // Easy chart control chart.setSymbol('INFY', 'NSE'); chart.changeInterval('5min'); chart.changeChartType('line'); // Simple indicator management chart.addIndicator('sma', { period: 50 }); chart.removeIndicator('sma'); // Drawing tools chart.setDrawingMode('rectangle'); chart.clearDrawings(); // Optimized real-time updates chart.setTick('INFY', { lastPrice: 1500.50, volume: 1000000, timestamp: Date.now() }); // Runtime customization chart.updateConfig({ theme: { backgroundColor: '#fff' } }); // Clean resource management chart.destroy(); ``` ## Custom Indicators - Easy to Extend The modular indicator system makes it simple to create custom technical analysis tools with optimal performance. ### Built-in Performance-Optimized Indicators - **SMA/EMA**: Incremental updates using sliding window optimization - **RSI**: Efficient gain/loss tracking for real-time performance - **MACD**: Smart calculation with proper signal line handling - **Bollinger Bands**: Optimized standard deviation updates - **Volume**: Color-coded rendering based on price direction ### Creating Custom Indicators **Step 1: Extend BaseIndicator** ```javascript import { BaseIndicator } from 'trace-chart'; class VWAPIndicator extends BaseIndicator { constructor(params = {}) { super('vwap', 'Volume Weighted Average Price', params, { color: '#ff9500', lineWidth: 2 }); // Efficient state tracking this.cumulativeVolumePrice = 0; this.cumulativeVolume = 0; } getDefaultParams() { return { period: 20, source: 'typical' }; } // Full calculation for historical data calculate(ohlcvData) { const result = []; this.cumulativeVolumePrice = 0; this.cumulativeVolume = 0; for (let i = 0; i < ohlcvData.length; i++) { const candle = ohlcvData[i]; const typicalPrice = (candle.high + candle.low + candle.close) / 3; const volume = candle.volume || 0; this.cumulativeVolumePrice += typicalPrice * volume; this.cumulativeVolume += volume; const vwap = this.cumulativeVolume > 0 ? this.cumulativeVolumePrice / this.cumulativeVolume : typicalPrice; result.push(vwap); } return result; } // Performance-optimized single value calculation calculateSingleValue(ohlcvData, index) { const candle = ohlcvData[index]; const typicalPrice = (candle.high + candle.low + candle.close) / 3; const volume = candle.volume || 0; // Incremental update this.cumulativeVolumePrice += typicalPrice * volume; this.cumulativeVolume += volume; return this.cumulativeVolume > 0 ? this.cumulativeVolumePrice / this.cumulativeVolume : typicalPrice; } reset() { super.reset(); this.cumulativeVolumePrice = 0; this.cumulativeVolume = 0; } } ``` **Step 2: Simple Registration and Usage** ```javascript const chart = new TraceChart('#chart'); const indicatorFactory = chart.api.getChartEngine().indicatorFactory; // Easy registration indicatorFactory.register('vwap', VWAPIndicator); // Use like built-in indicators chart.addIndicator('vwap', { period: 0 }); ``` ### Multi-Series Custom Indicators Easy to create indicators with multiple data series: ```javascript class StochasticIndicator extends BaseIndicator { constructor(params = {}) { super('stochastic', 'Stochastic Oscillator', params); this.auxiliaryData.d = []; // Additional data series this.kValues = []; // Efficient value tracking } getDefaultParams() { return { kPeriod: 14, dPeriod: 3 }; } // Automatic panel positioning getGridIndex(hasVolume = false) { return hasVolume ? 2 : 1; } // Optimized calculation calculate(ohlcvData) { const { kPeriod, dPeriod } = this.params; const kResult = []; const dResult = []; for (let i = 0; i < ohlcvData.length; i++) { if (i < kPeriod - 1) { kResult.push(null); dResult.push(null); continue; } // Efficient stochastic calculation const slice = ohlcvData.slice(i - kPeriod + 1, i + 1); const high = Math.max(...slice.map(d => d.high)); const low = Math.min(...slice.map(d => d.low)); const close = ohlcvData[i].close; const k = ((close - low) / (high - low)) * 100; kResult.push(k); this.kValues.push(k); // Simple moving average for %D if (this.kValues.length >= dPeriod) { const recentK = this.kValues.slice(-dPeriod); const d = recentK.reduce((sum, val) => sum + val, 0) / dPeriod; dResult.push(d); } else { dResult.push(null); } } this.auxiliaryData.d = dResult; return kResult; } // Multi-series rendering getSeries(xAxisIndex = 0, yAxisIndex = 0) { return [ { type: 'line', name: 'Stochastic %K', data: this.data, xAxisIndex, yAxisIndex, lineStyle: { color: '#ff6b35', width: 2 }, showSymbol: false }, { type: 'line', name: 'Stochastic %D', data: this.auxiliaryData.d, xAxisIndex, yAxisIndex, lineStyle: { color: '#4ecdc4', width: 2 }, showSymbol: false } ]; } } ``` ## Flexible Market Hours Easy to customize for any market worldwide: ```javascript import { TraceMarketHours } from 'trace-chart'; // Fully customizable market sessions const marketHours = new TraceMarketHours({ NSE: { name: 'NSE', timezone: 'Asia/Kolkata', rules: [ { dayofweek: 1, open: '09:15', close: '15:30' }, { dayofweek: 2, open: '09:15', close: '15:30' } // Easy to customize for any schedule ] } }); // Simple market status checking const isOpen = marketHours.isMarketOpen({ tradingsymbol: 'INFY', segment: 'NSE' }); ``` ## Development ```bash git clone https://github.com/srv91/trace-chart.git cd trace-chart npm install # Development build npm run build # Run demo npm run dev # Serve existing build npm run serve ``` ### Project Structure ``` trace-chart/ ├── src/ │ ├── index.js # Main entry point │ ├── core/ # Performance-optimized chart engine │ ├── indicators/ # Extendable indicator system │ ├── config/ # Customization system │ ├── demo/ # Demo data generator │ └── assets/ # Styles and assets ├── dist/ # Built files └── docs/ # GitHub Pages demo ``` ## What's Next - More technical indicators (Stochastic, Williams %R, ATR) - Advanced drawing tools (Fibonacci retracements, trend channels) - Options chain visualization - Multi-timeframe analysis ## License Trace is licensed under the Apache 2.0 license. --- <div align="center"> <!-- **[Try the Demo](https://trace-chart.dev/demo)** | **[Get Started](https://www.npmjs.com/package/trace-chart)** | **[Documentation](https://trace-chart.dev/docs)** --> *Lightweight • Fully Customizable • Built for Performance* </div>