UNPKG

candlestick-chart-generator

Version:

A Node.js library for generating candlestick chart screenshots using financial data

291 lines (222 loc) 7.76 kB
# Candlestick Chart Generator for Node.js A production-ready Node.js library for generating high-quality candlestick chart screenshots using real-time financial data. This library leverages Yahoo Finance for data retrieval and a pure Node.js canvas implementation for reliable chart rendering. ## Features - 📈 **Multi-Asset Support**: Stocks, cryptocurrencies, and FOREX pairs - ⏱️ **Flexible Intervals**: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo - 🎨 **Customizable Styling**: Full control over chart appearance and colors - 📸 **Multiple Output Formats**: Save as PNG files or get base64 image data - 🚀 **Production Ready**: Robust error handling and resource management - 🌐 **Real-time Data**: Powered by Yahoo Finance API - 💻 **Reliable Charts**: Pure Node.js canvas rendering (no headless browser required) ## Installation ```bash npm install candlestick-chart-generator ``` ### Prerequisites This library requires Node.js 14.0.0 or higher. ## Quick Start ```javascript const CandlestickChartGenerator = require("candlestick-chart-generator"); async function generateChart() { const generator = new CandlestickChartGenerator(); try { await generator.generateChartScreenshot({ symbol: "AAPL", interval: "1d", startDate: "2023-01-01", endDate: "2023-12-31", outputPath: "aapl_chart.png", width: 1200, height: 600 }); console.log("Chart generated successfully!"); } finally { await generator.close(); // No-op for canvas renderer } } generateChart(); ``` ## API Reference ### Constructor ```javascript const generator = new CandlestickChartGenerator(); ``` ### generateChartScreenshot(params) Generate a candlestick chart and save as PNG file. **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `symbol` | string | ✅ | Ticker symbol (e.g., "AAPL", "BTC-USD", "EURUSD=X") | | `interval` | string | ✅ | Time interval ("1m", "1h", "1d", etc.) | | `startDate` | string/Date | ❌ | Start date for historical data | | `endDate` | string/Date | ❌ | End date for historical data | | `outputPath` | string | ❌ | Output file path (default: "chart.png") | | `width` | number | ❌ | Chart width in pixels (default: 1200) | | `height` | number | ❌ | Chart height in pixels (default: 600) | | `chartOptions` | object | ❌ | Custom styling options for the chart (e.g., `backgroundColor`) | **Returns:** `Promise<string>` - Path to the saved screenshot ### generateChartBase64(params) Generate a candlestick chart and return as base64 image data. **Parameters:** Same as `generateChartScreenshot` (except `outputPath`) **Returns:** `Promise<string>` - Base64 encoded image data ### close() Close the generator. (This is a no-op for the canvas renderer, but included for API consistency). **Returns:** `Promise<void>` ## Supported Assets ### Stocks - US stocks: `AAPL`, `GOOGL`, `MSFT`, `TSLA`, `AMZN`, etc. - International stocks: `ASML.AS`, `SAP.DE`, `NESN.SW`, etc. ### Cryptocurrencies - `BTC-USD`, `ETH-USD`, `ADA-USD`, `DOT-USD`, etc. ### FOREX - `EURUSD=X`, `GBPUSD=X`, `USDJPY=X`, `AUDUSD=X`, etc. ## Supported Intervals | Interval | Description | |----------|-------------| | `1m` | 1 minute | | `2m` | 2 minutes | | `5m` | 5 minutes | | `15m` | 15 minutes | | `30m` | 30 minutes | | `60m` | 60 minutes | | `90m` | 90 minutes | | `1h` | 1 hour | | `1d` | 1 day | | `5d` | 5 days | | `1wk` | 1 week | | `1mo` | 1 month | | `3mo` | 3 months | ## Examples ### Basic Stock Chart ```javascript const CandlestickChartGenerator = require("candlestick-chart-generator"); async function stockChart() { const generator = new CandlestickChartGenerator(); try { await generator.generateChartScreenshot({ symbol: "AAPL", interval: "1d", startDate: "2023-01-01", endDate: "2023-12-31", outputPath: "aapl_daily.png" }); } finally { await generator.close(); } } ``` ### Cryptocurrency Chart with Custom Styling ```javascript async function cryptoChart() { const generator = new CandlestickChartGenerator(); try { await generator.generateChartScreenshot({ symbol: "BTC-USD", interval: "1h", startDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7 days ago endDate: new Date(), outputPath: "btc_hourly.png", width: 1400, height: 700, chartOptions: { backgroundColor: "#000000" } }); } finally { await generator.close(); } } ``` ### FOREX Chart ```javascript async function forexChart() { const generator = new CandlestickChartGenerator(); try { await generator.generateChartScreenshot({ symbol: "EURUSD=X", interval: "15m", startDate: new Date(Date.now() - 24 * 60 * 60 * 1000), // 24 hours ago endDate: new Date(), outputPath: "eurusd_15m.png" }); } finally { await generator.close(); } } ``` ### Generate Base64 Image Data ```javascript async function base64Chart() { const generator = new CandlestickChartGenerator(); try { const base64Data = await generator.generateChartBase64({ symbol: "TSLA", interval: "1d", startDate: "2023-06-01", endDate: "2023-12-31", width: 800, height: 400 }); console.log(`Base64 data length: ${base64Data.length} characters`); // Use base64Data for web applications, APIs, etc. } finally { await generator.close(); } } ``` ## Chart Customization The `chartOptions` parameter allows for basic customization of the chart background. For more advanced styling, you may need to modify the `chartRenderer_simple.js` file directly. ### Custom Background Color ```javascript chartOptions: { backgroundColor: "#2c2c54" } ``` ## Error Handling The library includes comprehensive error handling for common scenarios: ```javascript async function robustChart() { const generator = new CandlestickChartGenerator(); try { await generator.generateChartScreenshot({ symbol: "INVALID_SYMBOL", interval: "1d", outputPath: "test.png" }); } catch (error) { if (error.message.includes("No data found")) { console.error("Invalid symbol or no data available"); } else if (error.message.includes("Unsupported interval")) { console.error("Invalid time interval specified"); } else { console.error("Unexpected error:", error.message); } } finally { await generator.close(); } } ``` ## Performance Considerations - **Memory Management**: The canvas renderer is generally efficient and does not require explicit resource cleanup like a browser. - **Data Limits**: Large datasets (>5000 data points) may take longer to render. ## Troubleshooting ### Common Issues **1. No Data Found** ``` No data found for symbol: INVALID ``` Verify the symbol format and ensure it's available on Yahoo Finance. **2. Unsupported Interval** ``` Unsupported interval: 1h. Supported intervals: 1m, 2m, 5m, ... ``` Ensure you are using one of the supported intervals listed in the documentation. ## Author HoomanDigital ## Changelog ### v1.0.0 - Initial release - Support for stocks, crypto, and FOREX - Pure Node.js canvas rendering for reliability - Base64 output support - Comprehensive error handling