syncfusion-react-stock-chart

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing Syncfusion React Stock Charts

实现Syncfusion React股票图表

The Stock Chart component is a specialized financial chart for visualizing stock price movements over time. It provides essential features for financial data analysis including candlestick/OHLC visualization, period selectors for quick date range navigation, range selectors for precise data filtering, technical indicators, and interactive tools like tooltips and crosshair.
Stock Chart组件是一款专门用于可视化股票价格随时间变化的金融图表。它为金融数据分析提供了核心功能,包括K线/OHLC可视化、用于快速日期范围导航的周期选择器、用于精确数据筛选的范围选择器、技术指标,以及工具提示和十字线等交互式工具。

When to Use This Skill

何时使用该组件

Use this skill when you need to:
  • Visualize financial/stock data - Display stock prices, trading volumes, market movements
  • Display OHLC data - Show Open, High, Low, Close values with candlestick or Hilo charts
  • Implement period navigation - Add quick time range buttons (1D, 5D, 1M, 6M, YTD, 1Y, ALL)
  • Enable range selection - Allow users to select specific date ranges with thumb navigation
  • Add technical analysis - Include technical indicators (SMA, EMA, RSI, MACD, etc.)
  • Show stock events - Visualize earnings, dividends, splits, or other market events
  • Create financial dashboards - Build comprehensive stock analysis interfaces
  • Display time-series data - Any datetime-based financial or trading data
当你需要以下功能时,可使用该组件:
  • 可视化金融/股票数据 - 展示股票价格、交易量、市场走势
  • 显示OHLC数据 - 用K线图或高低图展示开盘价、最高价、最低价、收盘价
  • 实现周期导航 - 添加快速时间范围按钮(1日、5日、1月、6月、年初至今、1年、全部)
  • 启用范围选择 - 允许用户通过滑块导航选择特定日期范围
  • 添加技术分析 - 包含技术指标(SMA、EMA、RSI、MACD等)
  • 展示股票事件 - 可视化收益、分红、拆股或其他市场事件
  • 创建金融仪表盘 - 构建全面的股票分析界面
  • 显示时间序列数据 - 任何基于日期时间的金融或交易数据

Component Overview

组件概述

Package:
@syncfusion/ej2-react-charts

Component:
StockChartComponent

Key Features:
  • 6 series types (Line, Spline, Hilo, HiloOpenClose, Candle, Hollow Candle)
  • Built-in period selector for quick date range navigation
  • Range navigator with thumb controls for precise selection
  • Technical indicators (20+ types) and
    indicatorType
    support
  • Stock event annotations (
    stockEvents
    ) and
    stockEventRender
  • Interactive tooltip, crosshair (trackball), and legend
  • Selection and interaction:
    selectionMode
    ,
    isMultiSelect
    ,
    selectedDataIndexes
  • Zooming and panning (
    zoomSettings
    ,
    onZooming
    )
  • Export to image/PDF and print capabilities (
    exportType
    ,
    Export
    ,
    Print
    )
  • Persistence and RTL support (
    enablePersistence
    ,
    enableRtl
    )
  • Responsive and accessible (WCAG, ARIA, keyboard navigation)
包:
@syncfusion/ej2-react-charts

组件:
StockChartComponent

核心功能:
  • 6种系列类型(折线图、样条线图、高低图、OHLC图、K线图、空心K线图)
  • 内置周期选择器,用于快速日期范围导航
  • 带滑块控件的范围导航器,用于精确选择
  • 技术指标(20+种类型)和
    indicatorType
    支持
  • 股票事件标注(
    stockEvents
    )和
    stockEventRender
    事件
  • 交互式工具提示、十字线(追踪球)和图例
  • 选择与交互:
    selectionMode
    isMultiSelect
    selectedDataIndexes
  • 缩放和平移(
    zoomSettings
    onZooming
  • 导出为图片/PDF和打印功能(
    exportType
    Export
    Print
  • 状态持久化和RTL支持(
    enablePersistence
    enableRtl
  • 响应式设计与可访问性(WCAG、ARIA、键盘导航)

Documentation and Navigation Guide

文档与导航指南

Getting Started

入门指南

📄 Read: references/getting-started.md
Read this first for initial setup:
  • Installing @syncfusion/ej2-react-charts package
  • Project setup with Vite or create-react-app
  • Basic StockChartComponent implementation
  • Module injection pattern (Inject services)
  • Creating first chart with sample data
  • Understanding data structure (x, open, high, low, close, volume)
  • Adding chart title and basic configuration
📄 阅读: references/getting-started.md
首次设置请先阅读本指南:
  • 安装@syncfusion/ej2-react-charts包
  • 使用Vite或create-react-app搭建项目
  • 基础StockChartComponent实现
  • 模块注入模式(注入服务)
  • 使用示例数据创建第一个图表
  • 理解数据结构(x、open、high、low、close、volume)
  • 添加图表标题和基础配置

Axis Types and Configuration

轴类型与配置

📄 Read: references/configuration.md
For configuring and customizing axes:
  • DateTime Axis - Date/time based x-axis (most common for stock charts)
  • DateTimeCategory Axis - Business days only (excludes weekends/holidays)
  • Logarithmic Axis - Logarithmic scale for wide value ranges
  • Numeric Axis - Standard numeric axis for y-values
  • Axis title, labels, and formatting
  • Grid lines and tick customization
  • Multiple Y-axes for different data scales
  • Axis ranges and padding settings
📄 阅读: references/configuration.md
用于配置和自定义坐标轴:
  • 日期时间轴 - 基于日期/时间的X轴(股票图表最常用)
  • 日期时间分类轴 - 仅显示工作日(排除周末/节假日)
  • 对数轴 - 适用于数值范围较大的场景
  • 数值轴 - 标准数值轴,用于Y轴数值
  • 轴标题、标签和格式化
  • 网格线和刻度自定义
  • 多Y轴支持,适配不同数据尺度
  • 轴范围和内边距设置

Series Types and Visualization

系列类型与可视化

📄 Read: references/series-types.md
For choosing and configuring chart series:
  • Line series - Continuous price lines
  • Spline series - Smooth curves
  • Hilo series - High-low range bars
  • HiloOpenClose series - OHLC bars
  • Candle series - Traditional candlesticks (default for stock charts)
  • Hollow Candle series - Filled/hollow based on price movement
  • Bear/Bull fill colors for candlesticks
  • Series dropdown navigation and type switching
  • Module injection for each series type
  • When to use each type
📄 阅读: references/series-types.md
用于选择和配置图表系列:
  • 折线系列 - 连续价格线
  • 样条线系列 - 平滑曲线
  • 高低系列 - 高低范围柱
  • OHLC系列 - OHLC柱
  • K线系列 - 传统K线图(股票图表默认类型)
  • 空心K线系列 - 根据价格走势填充/空心显示
  • K线图的熊市/牛市填充颜色
  • 系列下拉导航与类型切换
  • 各系列类型的模块注入
  • 各类型的适用场景

Period and Range Selectors

周期与范围选择器

📄 Read: references/selectors.md
For implementing time range navigation:
  • Period Selector: Quick navigation buttons (1D, 5D, 1M, etc.)
    • Periods array configuration (interval, text, intervalType)
    • IntervalType options (Years, Months, Weeks, Days, Hours, etc.)
    • Enabling/disabling period selector
  • Range Selector: Precise range selection with thumbs
    • Thumb navigation and dragging
    • Label tapping for range selection
    • Date range button integration
    • Enabling/disabling range selector
📄 阅读: references/selectors.md
用于实现时间范围导航:
  • 周期选择器: 快速导航按钮(1日、5日、1月等)
    • 周期数组配置(interval、text、intervalType)
    • IntervalType选项(年、月、周、日、小时等)
    • 启用/禁用周期选择器
  • 范围选择器: 精确范围选择滑块
    • 滑块导航与拖拽
    • 点击标签选择范围
    • 日期范围按钮集成
    • 启用/禁用范围选择器

Interactive Features and Events

交互功能与事件

📄 Read: references/interactive-features.md
For adding user interaction and visual feedback:
  • Legend: Display series information
    • Position and alignment options (Top, Bottom, Left, Right, Custom)
    • Customization (size, shape, colors, icons)
    • Legend title and template
    • Legend click/render events
  • Tooltip: Show point data on hover
    • Format customization with tokens (${point.x}, ${point.open}, etc.)
    • Position control (Auto, Nearest)
    • Appearance styling (fill, border, textStyle)
    • Shared tooltips for multi-series
    • Header and custom formatting
  • Crosshair: Vertical/horizontal lines for precise value reading
    • Crosshair tooltip for axis values on both axes
    • Line customization (width, color, dashArray)
    • Snap to data for cleaner interactions
    • Trackball mode for shared tooltip across series
    • Line type (Both, Vertical, Horizontal)
  • Mouse Events: Comprehensive interaction tracking
    • pointClick, pointMove for data point interactions
    • stockChartMouseMove, stockChartMouseClick, etc.
    • stockChartMouseLeave for UI cleanup
    • Range change events for selector updates
📄 阅读: references/interactive-features.md
用于添加用户交互和视觉反馈:
  • 图例: 展示系列信息
    • 位置与对齐选项(顶部、底部、左侧、右侧、自定义)
    • 自定义设置(尺寸、形状、颜色、图标)
    • 图例标题和模板
    • 图例点击/渲染事件
  • 工具提示: 悬停时显示数据点信息
    • 使用令牌自定义格式(${point.x}、${point.open}等)
    • 位置控制(自动、最近)
    • 外观样式(填充色、边框、文本样式)
    • 多系列共享工具提示
    • 头部和自定义格式化
  • 十字线: 垂直/水平线,用于精确读取数值
    • 十字线工具提示,显示双轴的轴数值
    • 线条自定义(宽度、颜色、虚线样式)
    • 吸附到数据点,优化交互体验
    • 追踪球模式,跨系列共享工具提示
    • 线条类型(双轴、垂直、水平)
  • 鼠标事件: 全面的交互追踪
    • pointClick、pointMove用于数据点交互
    • stockChartMouseMove、stockChartMouseClick等
    • stockChartMouseLeave用于UI清理
    • 范围变化事件,用于选择器更新

Technical Analysis Tools

技术分析工具

📄 Read: references/technical-analysis.md
For financial analysis features:
  • Stock Events: Annotate significant market events
    • Event types (Flag, Circle, Square, Triangle, etc.)
    • Event markers with customizable colors and shapes
    • Event descriptions and tooltips
    • Events for specific series targeting
    • stockEventRender event for custom styling
    • Event visibility control
  • Technical Indicators: Add analysis overlays
    • 10+ indicator types:
      • Moving averages: SMA, EMA, TMA
      • Momentum: RSI, MACD, Stochastic, Momentum
      • Volume: Accumulation Distribution, ATR
      • Advanced: Bollinger Bands
    • Indicator configuration and styling
    • Multiple indicators on one chart
    • Field selection (Open, High, Low, Close)
    • Period and standard deviation customization
  • Trend Lines: Draw trend analysis lines
    • 6 trendline types: Linear, Exponential, Logarithmic, Polynomial, Power, MovingAverage
    • Line configuration (start/end points, series binding)
    • Styling and customization (color, width, dashArray)
    • Multiple trend lines per series
    • Polynomial order customization
    • Moving average period configuration
📄 阅读: references/technical-analysis.md
用于金融分析功能:
  • 股票事件: 标注重要市场事件
    • 事件类型(旗帜、圆形、方形、三角形等)
    • 可自定义颜色和形状的事件标记
    • 事件描述和工具提示
    • 针对特定系列的事件
    • stockEventRender事件,用于自定义样式
    • 事件可见性控制
  • 技术指标: 添加分析叠加层
    • 10+种指标类型:
      • 移动平均线:SMA、EMA、TMA
      • 动量指标:RSI、MACD、随机指标、动量指标
      • 成交量指标:累积分布指标、ATR
      • 高级指标:布林带
    • 指标配置与样式
    • 单图表多指标
    • 字段选择(开盘价、最高价、最低价、收盘价)
    • 周期和标准差自定义
  • 趋势线: 绘制趋势分析线
    • 6种趋势线类型:线性、指数、对数、多项式、幂函数、移动平均线
    • 线条配置(起始/结束点、系列绑定)
    • 样式和自定义(颜色、宽度、虚线样式)
    • 单系列多趋势线
    • 多项式阶数自定义
    • 移动平均线周期配置

Tooltip, Crosshair, and Axis Configuration

工具提示、十字线与轴配置

📄 Read: references/interactive-features.md and references/configuration.md
For tooltip and crosshair setup:
  • Tooltip Configuration: Point hover information
    • Enable/disable with
      enable
      property
    • Format strings for OHLC data display
    • Background color and border styling
    • Text style customization
    • Position modes (Auto, Nearest)
  • Crosshair Lines: Precise value reading
    • Enable crosshair with
      enable: true
    • Line type: Both, Vertical, or Horizontal
    • Line customization (width, color, dashArray)
    • Snap to data point alignment
    • Crosshair line styling
  • Axis Tooltips: Display axis values
    • Enable on primaryXAxis via
      crosshairTooltip
    • Enable on primaryYAxis via
      crosshairTooltip
    • Fill color and text style customization
    • Format axis value display
📄 阅读: references/interactive-features.mdreferences/configuration.md
用于工具提示和十字线设置:
  • 工具提示配置: 点悬停信息
    • 通过
      enable
      属性启用/禁用
    • OHLC数据显示的格式字符串
    • 背景色和边框样式
    • 文本样式自定义
    • 位置模式(自动、最近)
  • 十字线: 精确数值读取
    • 通过
      enable: true
      启用十字线
    • 线条类型:双轴、垂直或水平
    • 线条自定义(宽度、颜色、虚线样式)
    • 吸附到数据点对齐
    • 十字线样式设置
  • 轴工具提示: 显示轴数值
    • 在primaryXAxis上通过
      crosshairTooltip
      启用
    • 在primaryYAxis上通过
      crosshairTooltip
      启用
    • 填充色和文本样式自定义
    • 轴数值显示格式化

Chart Configuration and Styling

图表配置与样式

📄 Read: references/configuration.md
For customizing chart appearance and behavior:
  • Axes Configuration: Setup X and Y axes
    • Axis types: DateTime (default), DateTimeCategory, Logarithmic, Numeric
    • Label formatting and intervals
    • Multiple axes support with
      axes
      array
    • Axis ranges, padding, and grid lines
    • Major/minor tick and grid customization
  • Chart Dimensions: Control size
    • Width and height properties (pixels or percentage)
    • Responsive sizing strategies
    • Container-based sizing
  • Appearance: Theme and styling
    • Built-in themes (Material, Fabric, Bootstrap, HighContrast, etc.)
    • Background and border customization
    • Chart area styling
    • Margin and padding configuration
    • Title and title styling
  • Gradient Fills: Advanced styling
    • Linear gradients (x1, y1, x2, y2 stops)
    • Radial gradients (cx, cy, r stops)
    • Gradient for series fill
    • SVG gradient definitions
📄 阅读: references/configuration.md
用于自定义图表外观和行为:
  • 轴配置: 设置X轴和Y轴
    • 轴类型:日期时间轴(默认)、日期时间分类轴、对数轴、数值轴
    • 标签格式化和间隔
    • 通过
      axes
      数组支持多轴
    • 轴范围、内边距和网格线
    • 主次刻度和网格自定义
  • 图表尺寸: 控制大小
    • 宽度和高度属性(像素或百分比)
    • 响应式尺寸策略
    • 基于容器的尺寸设置
  • 外观: 主题和样式
    • 内置主题(Material、Fabric、Bootstrap、HighContrast等)
    • 背景和边框自定义
    • 图表区域样式
    • 边距和内边距配置
    • 标题和标题样式
  • 渐变填充: 高级样式
    • 线性渐变(x1、y1、x2、y2停止点)
    • 径向渐变(cx、cy、r停止点)
    • 系列填充渐变
    • SVG渐变定义

Export, Print, and Accessibility

导出、打印与可访问性

📄 Read: references/utilities.md
For export functionality and accessibility:
  • Export: Save charts as files
    • Export as PNG, JPEG, SVG
    • Export as PDF
    • Configuration options
  • Print: Print chart directly
    • Print method and options
  • Accessibility: WCAG compliance
    • Keyboard navigation
    • ARIA attributes
    • Screen reader support
    • Accessible color schemes
📄 阅读: references/utilities.md
用于导出功能和可访问性:
  • 导出: 将图表保存为文件
    • 导出为PNG、JPEG、SVG
    • 导出为PDF
    • 配置选项
  • 打印: 直接打印图表
    • 打印方法和选项
  • 可访问性: WCAG合规
    • 键盘导航
    • ARIA属性
    • 屏幕阅读器支持
    • 无障碍配色方案

Quick Start

快速开始

Basic Stock Chart

基础股票图表

typescript
import { StockChartComponent, StockChartSeriesCollectionDirective, 
         StockChartSeriesDirective, Inject, DateTime, Tooltip, 
         RangeTooltip, Crosshair, LineSeries, SplineSeries, 
         CandleSeries, HiloOpenCloseSeries, HiloSeries, 
         RangeAreaSeries, Trendlines } from '@syncfusion/ej2-react-charts';
import * as React from 'react';

function App() {
  const data = [
    { x: new Date('2012-04-02'), open: 85.97, high: 90.58, low: 85.97, close: 90.58, volume: 660187068 },
    { x: new Date('2012-04-09'), open: 89.02, high: 92.50, low: 88.50, close: 92.90, volume: 490033264 },
    { x: new Date('2012-04-16'), open: 92.52, high: 93.00, low: 88.50, close: 92.52, volume: 450167016 },
    // ... more data
  ];

  return (
    <StockChartComponent
      id='stockchart'
      title='AAPL Stock Price'
      primaryXAxis={{ valueType: 'DateTime' }}
    >
      <Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, LineSeries, 
                         SplineSeries, CandleSeries, HiloOpenCloseSeries, HiloSeries, 
                         RangeAreaSeries, Trendlines]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={data} 
          type='Candle'
          xName='x'
          high='high' 
          low='low' 
          open='open' 
          close='close'
          volume='volume'
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}

export default App;
typescript
import { StockChartComponent, StockChartSeriesCollectionDirective, 
         StockChartSeriesDirective, Inject, DateTime, Tooltip, 
         RangeTooltip, Crosshair, LineSeries, SplineSeries, 
         CandleSeries, HiloOpenCloseSeries, HiloSeries, 
         RangeAreaSeries, Trendlines } from '@syncfusion/ej2-react-charts';
import * as React from 'react';

function App() {
  const data = [
    { x: new Date('2012-04-02'), open: 85.97, high: 90.58, low: 85.97, close: 90.58, volume: 660187068 },
    { x: new Date('2012-04-09'), open: 89.02, high: 92.50, low: 88.50, close: 92.90, volume: 490033264 },
    { x: new Date('2012-04-16'), open: 92.52, high: 93.00, low: 88.50, close: 92.52, volume: 450167016 },
    // ... 更多数据
  ];

  return (
    <StockChartComponent
      id='stockchart'
      title='AAPL Stock Price'
      primaryXAxis={{ valueType: 'DateTime' }}
    >
      <Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, LineSeries, 
                         SplineSeries, CandleSeries, HiloOpenCloseSeries, HiloSeries, 
                         RangeAreaSeries, Trendlines]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={data} 
          type='Candle'
          xName='x'
          high='high' 
          low='low' 
          open='open' 
          close='close'
          volume='volume'
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}

export default App;

Stock Chart with Period Selector

带周期选择器的股票图表

typescript
import { StockChartComponent, StockChartSeriesCollectionDirective, 
         StockChartSeriesDirective, Inject, DateTime, Tooltip, 
         RangeTooltip, Crosshair, CandleSeries } from '@syncfusion/ej2-react-charts';

function App() {
  const data = [ /* stock data */ ];
  
  const periods = [
    { intervalType: 'Days', interval: 1, text: '1D' },
    { intervalType: 'Days', interval: 5, text: '5D' },
    { intervalType: 'Months', interval: 1, text: '1M' },
    { intervalType: 'Months', interval: 3, text: '3M' },
    { intervalType: 'Months', interval: 6, text: '6M' },
    { intervalType: 'Years', interval: 1, text: '1Y' },
    { text: 'All' }
  ];

  return (
    <StockChartComponent
      id='stockchart'
      title='Stock Analysis'
      primaryXAxis={{ valueType: 'DateTime' }}
      periods={periods}
      enablePeriodSelector={true}
    >
      <Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, CandleSeries]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={data} 
          type='Candle'
          xName='x'
          high='high' 
          low='low' 
          open='open' 
          close='close'
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}
typescript
import { StockChartComponent, StockChartSeriesCollectionDirective, 
         StockChartSeriesDirective, Inject, DateTime, Tooltip, 
         RangeTooltip, Crosshair, CandleSeries } from '@syncfusion/ej2-react-charts';

function App() {
  const data = [ /* 股票数据 */ ];
  
  const periods = [
    { intervalType: 'Days', interval: 1, text: '1D' },
    { intervalType: 'Days', interval: 5, text: '5D' },
    { intervalType: 'Months', interval: 1, text: '1M' },
    { intervalType: 'Months', interval: 3, text: '3M' },
    { intervalType: 'Months', interval: 6, text: '6M' },
    { intervalType: 'Years', interval: 1, text: '1Y' },
    { text: 'All' }
  ];

  return (
    <StockChartComponent
      id='stockchart'
      title='Stock Analysis'
      primaryXAxis={{ valueType: 'DateTime' }}
      periods={periods}
      enablePeriodSelector={true}
    >
      <Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, CandleSeries]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={data} 
          type='Candle'
          xName='x'
          high='high' 
          low='low' 
          open='open' 
          close='close'
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}

CSS Styling for Stock Chart

股票图表的CSS样式

For the Stock Chart period selector UI to work properly, you need to include the required CSS stylesheets in your HTML file. Add the following
<link>
tags to the
<head>
section of your
index.html
:
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
    <!-- Syncfusion Tailwind CSS for Stock Chart styling -->
    <link href="https://cdn.syncfusion.com/ej2/33.1.44/tailwind3.css" rel="stylesheet" />
    
    <!-- Bootstrap CSS for additional styling support -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    
    <title>Stock Chart App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
Key CSS Stylesheets:
  1. Syncfusion Tailwind CSS (
    tailwind3.css
    ) - Required for Stock Chart components
    • Version: 33.1.44 (update to match your Syncfusion version)
    • Provides styling for period selector buttons, range navigator, tooltips, and other UI elements
    • CDN URL:
      https://cdn.syncfusion.com/ej2/33.1.44/tailwind3.css
  2. Bootstrap CSS - Optional but recommended for additional styling support
    • Version: 3.3.7
    • Provides base styling and layout utilities
    • CDN URL:
      https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
Important Notes:
  • Ensure the Syncfusion CSS version matches your
    @syncfusion/ej2-react-charts
    package version
  • If you're using a different theme (Material, Bootstrap, Fabric, HighContrast), use the corresponding CSS file from Syncfusion CDN
  • Place these stylesheets before other custom stylesheets to allow proper CSS cascade and overrides
  • Without these stylesheets, the period selector buttons, tooltips, and other UI elements may not render correctly
Alternative CSS URLs by Theme:
  • Material:
    https://cdn.syncfusion.com/ej2/33.1.44/material.css
  • Bootstrap:
    https://cdn.syncfusion.com/ej2/33.1.44/bootstrap.css
  • Fabric:
    https://cdn.syncfusion.com/ej2/33.1.44/fabric.css
  • Tailwind:
    https://cdn.syncfusion.com/ej2/33.1.44/tailwind3.css
  • HighContrast:
    https://cdn.syncfusion.com/ej2/33.1.44/highcontrast.css
为了让股票图表的周期选择器UI正常工作,你需要在HTML文件中引入所需的CSS样式表。在
index.html
<head>
部分添加以下
<link>
标签:
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    
    <!-- Syncfusion Tailwind CSS 用于股票图表样式 -->
    <link href="https://cdn.syncfusion.com/ej2/33.1.44/tailwind3.css" rel="stylesheet" />
    
    <!-- Bootstrap CSS 用于额外样式支持 -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    
    <title>Stock Chart App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
核心CSS样式表:
  1. Syncfusion Tailwind CSS (
    tailwind3.css
    ) - 股票图表组件必需
    • 版本:33.1.44(请更新为与你的Syncfusion版本匹配)
    • 为周期选择器按钮、范围导航器、工具提示和其他UI元素提供样式
    • CDN地址:
      https://cdn.syncfusion.com/ej2/33.1.44/tailwind3.css
  2. Bootstrap CSS - 可选但推荐用于额外样式支持
    • 版本:3.3.7
    • 提供基础样式和布局工具
    • CDN地址:
      https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
重要注意事项:
  • 确保Syncfusion CSS版本与你的
    @syncfusion/ej2-react-charts
    包版本一致
  • 如果你使用其他主题(Material、Bootstrap、Fabric、HighContrast),请使用Syncfusion CDN中对应的CSS文件
  • 将这些样式表放在其他自定义样式表之前,以确保正确的CSS层叠和覆盖
  • 如果没有这些样式表,周期选择器按钮、工具提示和其他UI元素可能无法正确渲染
按主题分类的替代CSS地址:
  • Material:
    https://cdn.syncfusion.com/ej2/33.1.44/material.css
  • Bootstrap:
    https://cdn.syncfusion.com/ej2/33.1.44/bootstrap.css
  • Fabric:
    https://cdn.syncfusion.com/ej2/33.1.44/fabric.css
  • Tailwind:
    https://cdn.syncfusion.com/ej2/33.1.44/tailwind3.css
  • HighContrast:
    https://cdn.syncfusion.com/ej2/33.1.44/highcontrast.css

Axis Types Reference

轴类型参考

Stock Chart supports multiple axis types for different data scenarios:
股票图表支持多种轴类型,适配不同数据场景:

DateTime Axis (Default)

日期时间轴(默认)

Use for date-based stock data:
typescript
primaryXAxis={{ 
  valueType: 'DateTime',
  majorGridLines: { width: 0 },
  majorTickLines: { color: 'transparent' }
}}
Best for: Stock price data with dates Inject:
DateTime
module
用于基于日期的股票数据:
typescript
primaryXAxis={{ 
  valueType: 'DateTime',
  majorGridLines: { width: 0 },
  majorTickLines: { color: 'transparent' }
}}
最适合: 带日期的股票价格数据 注入:
DateTime
模块

DateTimeCategory Axis

日期时间分类轴

Displays only business days (excludes weekends/holidays):
typescript
primaryXAxis={{ 
  valueType: 'DateTimeCategory',
  majorGridLines: { width: 0 }
}}
Best for: Business day-only trading data Inject:
DateTimeCategory
module Note: Requires
DateTimeCategory
module import and injection
仅显示工作日(排除周末/节假日):
typescript
primaryXAxis={{ 
  valueType: 'DateTimeCategory',
  majorGridLines: { width: 0 }
}}
最适合: 仅包含工作日的交易数据 注入:
DateTimeCategory
模块 注意: 需要导入并注入
DateTimeCategory
模块

Logarithmic Axis

对数轴

For Y-axis with logarithmic scale (useful for wide value ranges):
typescript
primaryYAxis={{
  valueType: 'Logarithmic',
  labelFormat: '${value}'
}}
Best for: Data spanning multiple orders of magnitude Inject:
Logarithmic
module Note: Cannot contain zero or negative values
用于Y轴的对数刻度(适用于数值范围较大的场景):
typescript
primaryYAxis={{
  valueType: 'Logarithmic',
  labelFormat: '${value}'
}}
最适合: 跨越多个数量级的数据 注入:
Logarithmic
模块 注意: 不能包含零或负值

Numeric Axis (Y-axis default)

数值轴(Y轴默认)

Standard linear numeric scale:
typescript
primaryYAxis={{
  valueType: 'Double',
  labelFormat: '${value}',
  minimum: 0,
  maximum: 500,
  interval: 50
}}
Best for: Price values and general Y-axis No module injection required - This is the default
标准线性数值刻度:
typescript
primaryYAxis={{
  valueType: 'Double',
  labelFormat: '${value}',
  minimum: 0,
  maximum: 500,
  interval: 50
}}
最适合: 价格数值和通用Y轴 无需模块注入 - 这是默认设置

Multi-Axis Configuration

多轴配置

Use multiple Y-axes for different scales:
typescript
<StockChartComponent
  primaryXAxis={{ valueType: 'DateTime' }}
  primaryYAxis={{ title: 'Price', labelFormat: '${value}' }}
>
  {/* Additional axes using StockChartAxesDirective */}
  <StockChartAxesDirective>
    <StockChartAxisDirective
      name='volumeAxis'
      opposedPosition={true}
      title='Volume'
      labelFormat='{value}M'
    />
  </StockChartAxesDirective>
  
  {/* Series bind to respective axes */}
  <StockChartSeriesCollectionDirective>
    <StockChartSeriesDirective type='Candle' yAxisName='primaryYAxis' />
    <StockChartSeriesDirective type='Column' yAxisName='volumeAxis' />
  </StockChartSeriesCollectionDirective>
</StockChartComponent>
使用多个Y轴适配不同尺度:
typescript
<StockChartComponent
  primaryXAxis={{ valueType: 'DateTime' }}
  primaryYAxis={{ title: 'Price', labelFormat: '${value}' }}
>
  {/* 使用StockChartAxesDirective添加额外轴 */}
  <StockChartAxesDirective>
    <StockChartAxisDirective
      name='volumeAxis'
      opposedPosition={true}
      title='Volume'
      labelFormat='{value}M'
    />
  </StockChartAxesDirective>
  
  {/* 系列绑定到对应轴 */}
  <StockChartSeriesCollectionDirective>
    <StockChartSeriesDirective type='Candle' yAxisName='primaryYAxis' />
    <StockChartSeriesDirective type='Column' yAxisName='volumeAxis' />
  </StockChartSeriesCollectionDirective>
</StockChartComponent>

Common Patterns

常见模式

Pattern 1: Financial Dashboard with Multiple Features

模式1:包含多种功能的金融仪表盘

typescript
import { StockChartComponent, StockChartSeriesCollectionDirective, 
         StockChartSeriesDirective, Inject, DateTime, Tooltip, 
         RangeTooltip, Crosshair, CandleSeries, StockLegend, 
         Export, Print } from '@syncfusion/ej2-react-charts';

function FinancialDashboard() {
  const handlePointClick = (args) => {
    console.log(`Point clicked: ${args.x}, Value: ${args.y}`);
  };

  const handleMouseMove = (args) => {
    console.log('Mouse moved over chart');
  };

  const handleRangeChange = (args) => {
    console.log(`Range changed: ${args.start} to ${args.end}`);
  };

  return (
    <StockChartComponent
      id='stockchart'
      title='Comprehensive Stock Analysis'
      primaryXAxis={{ valueType: 'DateTime' }}
      tooltip={{ enable: true, shared: true }}
      crosshair={{ enable: true }}
      legendSettings={{ visible: true }}
      enablePeriodSelector={true}
      enableSelector={true}
      pointClick={handlePointClick}
      stockChartMouseMove={handleMouseMove}
      rangeChange={handleRangeChange}
    >
      <Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, 
                         CandleSeries, StockLegend, Export, Print]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={stockData} 
          type='Candle'
          name='Apple Inc'
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}
typescript
import { StockChartComponent, StockChartSeriesCollectionDirective, 
         StockChartSeriesDirective, Inject, DateTime, Tooltip, 
         RangeTooltip, Crosshair, CandleSeries, StockLegend, 
         Export, Print } from '@syncfusion/ej2-react-charts';

function FinancialDashboard() {
  const handlePointClick = (args) => {
    console.log(`Point clicked: ${args.x}, Value: ${args.y}`);
  };

  const handleMouseMove = (args) => {
    console.log('Mouse moved over chart');
  };

  const handleRangeChange = (args) => {
    console.log(`Range changed: ${args.start} to ${args.end}`);
  };

  return (
    <StockChartComponent
      id='stockchart'
      title='Comprehensive Stock Analysis'
      primaryXAxis={{ valueType: 'DateTime' }}
      tooltip={{ enable: true, shared: true }}
      crosshair={{ enable: true }}
      legendSettings={{ visible: true }}
      enablePeriodSelector={true}
      enableSelector={true}
      pointClick={handlePointClick}
      stockChartMouseMove={handleMouseMove}
      rangeChange={handleRangeChange}
    >
      <Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, 
                         CandleSeries, StockLegend, Export, Print]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={stockData} 
          type='Candle'
          name='Apple Inc'
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}

Pattern 2: Candlestick with Bear/Bull Colors and Animation

模式2:带熊市/牛市颜色和动画的K线图

typescript
function StyledCandleChart() {
  const stockData = [ /* stock data with open, high, low, close */ ];

  return (
    <StockChartComponent
      id='stockchart'
      primaryXAxis={{ valueType: 'DateTime' }}
      primaryYAxis={{ labelFormat: '${value}' }}
    >
      <Inject services={[DateTime, CandleSeries, Tooltip, RangeTooltip]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={stockData} 
          type='Candle'
          xName='x'
          open='open'
          high='high'
          low='low'
          close='close'
          bearFillColor='#ef5350'      // Red for downtrend
          bullFillColor='#26a69a'      // Green for uptrend
          animation={{ enable: true, duration: 500 }}
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}
typescript
function StyledCandleChart() {
  const stockData = [ /* 包含开盘价、最高价、最低价、收盘价的股票数据 */ ];

  return (
    <StockChartComponent
      id='stockchart'
      primaryXAxis={{ valueType: 'DateTime' }}
      primaryYAxis={{ labelFormat: '${value}' }}
    >
      <Inject services={[DateTime, CandleSeries, Tooltip, RangeTooltip]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={stockData} 
          type='Candle'
          xName='x'
          open='open'
          high='high'
          low='low'
          close='close'
          bearFillColor='#ef5350'      // 下跌趋势用红色
          bullFillColor='#26a69a'      // 上涨趋势用绿色
          animation={{ enable: true, duration: 500 }}
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}

Pattern 3: Technical Analysis Chart

模式3:技术分析图表

typescript
function TechnicalAnalysisChart() {
  const indicators = [
    {
      type: 'Sma',
      field: 'Close',
      period: 14,
      fill: 'blue'
    },
    {
      type: 'BollingerBands',
      field: 'Close',
      period: 20,
      standardDeviation: 2,
      upperLine: { color: '#ff0000', width: 1 },
      lowerLine: { color: '#ff0000', width: 1 }
    }
  ];

  return (
    <StockChartComponent
      id='stockchart'
      primaryXAxis={{ valueType: 'DateTime' }}
      indicators={indicators}
    >
      <Inject services={[DateTime, CandleSeries, Tooltip, 
                         LineSeries, RangeTooltip, SmaIndicator, BollingerBands]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={stockData} 
          type='Candle'
        />
      </StockChartSeriesCollectionDirective>
      <StockChartIndicatorsDirective>
        {/* Indicators can also be added here via directives */}
      </StockChartIndicatorsDirective>
    </StockChartComponent>
  );
}
typescript
function TechnicalAnalysisChart() {
  const indicators = [
    {
      type: 'Sma',
      field: 'Close',
      period: 14,
      fill: 'blue'
    },
    {
      type: 'BollingerBands',
      field: 'Close',
      period: 20,
      standardDeviation: 2,
      upperLine: { color: '#ff0000', width: 1 },
      lowerLine: { color: '#ff0000', width: 1 }
    }
  ];

  return (
    <StockChartComponent
      id='stockchart'
      primaryXAxis={{ valueType: 'DateTime' }}
      indicators={indicators}
    >
      <Inject services={[DateTime, CandleSeries, Tooltip, 
                         LineSeries, RangeTooltip, SmaIndicator, BollingerBands]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={stockData} 
          type='Candle'
        />
      </StockChartSeriesCollectionDirective>
      <StockChartIndicatorsDirective>
        {/* 也可以通过指令在此处添加指标 */}
      </StockChartIndicatorsDirective>
    </StockChartComponent>
  );
}

Pattern 4: Crosshair with Axis Tooltips

模式4:带轴工具提示的十字线

typescript
function CrosshairChart() {
  return (
    <StockChartComponent
      id='stockchart'
      primaryXAxis={{ 
        valueType: 'DateTime',
        majorGridLines: { width: 0 },
        majorTickLines: { color: 'transparent' },
        crosshairTooltip: { enable: true }  // X-axis tooltip
      }}
      primaryYAxis={{
        labelFormat: 'n0',
        majorTickLines: { width: 0 },
        crosshairTooltip: { enable: true }  // Y-axis tooltip
      }}
      crosshair={{ 
        enable: true,
        lineType: 'Both',
        line: { width: 1, color: '#0080ff' }
      }}
      tooltip={{ enable: true }}
    >
      <Inject services={[DateTime, CandleSeries, Crosshair, Tooltip, RangeTooltip]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={stockData} 
          type='Candle'
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}
typescript
function CrosshairChart() {
  return (
    <StockChartComponent
      id='stockchart'
      primaryXAxis={{ 
        valueType: 'DateTime',
        majorGridLines: { width: 0 },
        majorTickLines: { color: 'transparent' },
        crosshairTooltip: { enable: true }  // X轴工具提示
      }}
      primaryYAxis={{
        labelFormat: 'n0',
        majorTickLines: { width: 0 },
        crosshairTooltip: { enable: true }  // Y轴工具提示
      }}
      crosshair={{ 
        enable: true,
        lineType: 'Both',
        line: { width: 1, color: '#0080ff' }
      }}
      tooltip={{ enable: true }}
    >
      <Inject services={[DateTime, CandleSeries, Crosshair, Tooltip, RangeTooltip]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={stockData} 
          type='Candle'
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}

Pattern 5: Stock Events Visualization

模式5:股票事件可视化

typescript
function StockEventsChart() {
  const stockEvents = [
    {
      date: new Date('2012-04-01'),
      text: 'Q1 Earnings',
      description: 'Quarterly earnings release',
      type: 'Flag',
      background: '#6c757d'
    },
    {
      date: new Date('2012-07-01'),
      text: 'Dividend',
      description: 'Dividend payout',
      type: 'Circle',
      background: '#28a745'
    }
  ];

  return (
    <StockChartComponent
      id='stockchart'
      primaryXAxis={{ valueType: 'DateTime' }}
      stockEvents={stockEvents}
    >
      <Inject services={[DateTime, SplineSeries, Tooltip]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={stockData} 
          type='Spline'
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}
typescript
function StockEventsChart() {
  const stockEvents = [
    {
      date: new Date('2012-04-01'),
      text: 'Q1 Earnings',
      description: 'Quarterly earnings release',
      type: 'Flag',
      background: '#6c757d'
    },
    {
      date: new Date('2012-07-01'),
      text: 'Dividend',
      description: 'Dividend payout',
      type: 'Circle',
      background: '#28a745'
    }
  ];

  return (
    <StockChartComponent
      id='stockchart'
      primaryXAxis={{ valueType: 'DateTime' }}
      stockEvents={stockEvents}
    >
      <Inject services={[DateTime, SplineSeries, Tooltip]} />
      <StockChartSeriesCollectionDirective>
        <StockChartSeriesDirective 
          dataSource={stockData} 
          type='Spline'
        />
      </StockChartSeriesCollectionDirective>
    </StockChartComponent>
  );
}

Pattern 6: Export and Print

模式6:导出与打印

typescript
function ExportableChart() {
  const chartRef = useRef<StockChartComponent>(null);

  const handleExport = (type: string) => {
    if (chartRef.current) {
      chartRef.current.export(type, 'StockChart');
    }
  };

  const handlePrint = () => {
    if (chartRef.current) {
      chartRef.current.print();
    }
  };

  return (
    <div>
      <div>
        <button onClick={() => handleExport('PNG')}>Export PNG</button>
        <button onClick={() => handleExport('JPEG')}>Export JPEG</button>
        <button onClick={() => handleExport('SVG')}>Export SVG</button>
        <button onClick={() => handleExport('PDF')}>Export PDF</button>
        <button onClick={handlePrint}>Print Chart</button>
      </div>
      
      <StockChartComponent
        ref={chartRef}
        id='stockchart'
        primaryXAxis={{ valueType: 'DateTime' }}
        exportType={['PNG', 'JPEG', 'SVG', 'PDF']}
      >
        <Inject services={[DateTime, CandleSeries, Export]} />
        <StockChartSeriesCollectionDirective>
          <StockChartSeriesDirective 
            dataSource={stockData} 
            type='Candle'
          />
        </StockChartSeriesCollectionDirective>
      </StockChartComponent>
    </div>
  );
}
typescript
function ExportableChart() {
  const chartRef = useRef<StockChartComponent>(null);

  const handleExport = (type: string) => {
    if (chartRef.current) {
      chartRef.current.export(type, 'StockChart');
    }
  };

  const handlePrint = () => {
    if (chartRef.current) {
      chartRef.current.print();
    }
  };

  return (
    <div>
      <div>
        <button onClick={() => handleExport('PNG')}>Export PNG</button>
        <button onClick={() => handleExport('JPEG')}>Export JPEG</button>
        <button onClick={() => handleExport('SVG')}>Export SVG</button>
        <button onClick={() => handleExport('PDF')}>Export PDF</button>
        <button onClick={handlePrint}>Print Chart</button>
      </div>
      
      <StockChartComponent
        ref={chartRef}
        id='stockchart'
        primaryXAxis={{ valueType: 'DateTime' }}
        exportType={['PNG', 'JPEG', 'SVG', 'PDF']}
      >
        <Inject services={[DateTime, CandleSeries, Export]} />
        <StockChartSeriesCollectionDirective>
          <StockChartSeriesDirective 
            dataSource={stockData} 
            type='Candle'
          />
        </StockChartSeriesCollectionDirective>
      </StockChartComponent>
    </div>
  );
}

Key Props

核心属性

StockChartComponent

StockChartComponent

PropTypeDescription
primaryXAxis
ObjectX-axis configuration (typically DateTime)
primaryYAxis
ObjectY-axis configuration
axes
ArrayAdditional Y-axes for multi-axis scaling
title
stringChart title
titleStyle
ObjectTitle font styling
periods
ArrayPeriod selector buttons configuration
enablePeriodSelector
booleanShow/hide period selector (default: true)
enableSelector
booleanShow/hide range selector (default: true)
enableCustomRange
booleanEnable custom date range selection
tooltip
ObjectTooltip configuration
crosshair
ObjectCrosshair configuration
legendSettings
ObjectLegend configuration
stockEvents
ArrayStock event markers
indicators
ArrayTechnical indicators
height
stringChart height
width
stringChart width
margin
ObjectChart margin configuration
chartArea
ObjectChart area styling
background
stringChart background color
border
ObjectChart border configuration
theme
stringChart theme
zoomSettings
ObjectZoom and pan configuration
rows
ArrayRow definitions for multi-row layouts
selectedDataIndexes
ArrayProgrammatically select specific points
selectionMode
stringSelection mode (None, Point, Series, Cluster, DragXY, DragX, DragY)
isMultiSelect
booleanAllow multiple data point selection
exportType
ArrayExport formats (PNG, JPEG, SVG, PDF)
enablePersistence
booleanPersist chart state between page reloads
enableRtl
booleanEnable right-to-left rendering
locale
stringOverride global culture/localization
noDataTemplate
string/FunctionTemplate shown when no data available
isTransposed
booleanRender chart in transposed manner
seriesType
ArrayAvailable series types
indicatorType
ArrayAvailable technical indicator types
trendlineType
ArrayAvailable trendline types
bearFillColor
stringFill color for downtrend (bear) candles
bullFillColor
stringFill color for uptrend (bull) candles
animation
ObjectAnimation settings for series rendering
pointClick
FunctionEvent fired when a data point is clicked
stockChartMouseMove
FunctionEvent fired when mouse moves over chart
stockChartMouseClick
FunctionEvent fired when chart area is clicked
stockChartMouseDown
FunctionEvent fired on mouse down
stockChartMouseUp
FunctionEvent fired on mouse up
stockChartMouseLeave
FunctionEvent fired when cursor leaves chart
tooltipRender
FunctionEvent for customizing tooltip before display
axisLabelRender
FunctionEvent for customizing axis labels before rendering
seriesRender
FunctionEvent fired when series is rendered
legendClick
FunctionEvent fired when legend item is clicked
legendRender
FunctionEvent fired when legend items are rendered
crosshairLabelRender
FunctionEvent fired before crosshair tooltip is rendered
selectorRender
FunctionTriggered when range selector renders
onZooming
FunctionEvent fired during zoom interactions
load
FunctionLifecycle event fired before chart is loaded
loaded
FunctionLifecycle event fired after chart is loaded
beforeExport
FunctionEvent fired before export operation
stockEventRender
FunctionCustomize stock event marker rendering
rows
ArrayRow definitions for multi-row layouts
isTransposed
booleanRender chart in transposed manner
trendlines
ArrayTrend line configurations (StockChartTrendlinesDirective)
属性类型描述
primaryXAxis
ObjectX轴配置(通常为日期时间类型)
primaryYAxis
ObjectY轴配置
axes
Array额外的Y轴,用于多轴缩放
title
string图表标题
titleStyle
Object标题字体样式
periods
Array周期选择器按钮配置
enablePeriodSelector
boolean显示/隐藏周期选择器(默认:true)
enableSelector
boolean显示/隐藏范围选择器(默认:true)
enableCustomRange
boolean启用自定义日期范围选择
tooltip
Object工具提示配置
crosshair
Object十字线配置
legendSettings
Object图例配置
stockEvents
Array股票事件标记
indicators
Array技术指标
height
string图表高度
width
string图表宽度
margin
Object图表边距配置
chartArea
Object图表区域样式
background
string图表背景色
border
Object图表边框配置
theme
string图表主题
zoomSettings
Object缩放和平移配置
rows
Array多行布局的行定义
selectedDataIndexes
Array以编程方式选择特定数据点
selectionMode
string选择模式(None、Point、Series、Cluster、DragXY、DragX、DragY)
isMultiSelect
boolean允许多个数据点选择
exportType
Array导出格式(PNG、JPEG、SVG、PDF)
enablePersistence
boolean在页面刷新之间保留图表状态
enableRtl
boolean启用从右到左渲染
locale
string覆盖全局文化/本地化设置
noDataTemplate
string/Function无数据时显示的模板
isTransposed
boolean以转置方式渲染图表
seriesType
Array可用的系列类型
indicatorType
Array可用的技术指标类型
trendlineType
Array可用的趋势线类型
bearFillColor
string下跌趋势(熊市)K线的填充色
bullFillColor
string上涨趋势(牛市)K线的填充色
animation
Object系列渲染的动画设置
pointClick
Function数据点被点击时触发的事件
stockChartMouseMove
Function鼠标在图表上移动时触发的事件
stockChartMouseClick
Function图表区域被点击时触发的事件
stockChartMouseDown
Function鼠标按下时触发的事件
stockChartMouseUp
Function鼠标松开时触发的事件
stockChartMouseLeave
Function光标离开图表时触发的事件
tooltipRender
Function工具提示显示前自定义内容的事件
axisLabelRender
Function轴标签渲染前自定义内容的事件
seriesRender
Function系列渲染时触发的事件
legendClick
Function图例项被点击时触发的事件
legendRender
Function图例项渲染时触发的事件
crosshairLabelRender
Function十字线工具提示渲染前触发的事件
selectorRender
Function范围选择器渲染时触发的事件
onZooming
Function缩放交互期间触发的事件
load
Function图表加载前触发的生命周期事件
loaded
Function图表加载后触发的生命周期事件
beforeExport
Function导出操作前触发的事件
stockEventRender
Function自定义股票事件标记渲染的事件
rows
Array多行布局的行定义
isTransposed
boolean以转置方式渲染图表
trendlines
Array趋势线配置(StockChartTrendlinesDirective)

StockChartSeriesDirective

StockChartSeriesDirective

PropTypeDescription
dataSource
ArrayStock data array
type
stringSeries type (Candle, Line, Spline, Hilo, HiloOpenClose)
xName
stringData field for x-axis (date)
high
stringData field for high values
low
stringData field for low values
open
stringData field for open values
close
stringData field for close values
volume
stringData field for volume values
name
stringSeries name for legend
yName
stringData field for y-axis values
yAxisName
stringName of Y-axis to bind this series to (for multi-axis)
bearFillColor
stringFill color for downtrend candles/bars
bullFillColor
stringFill color for uptrend candles/bars
fill
stringSeries color or gradient fill (e.g., 'url(#gradient1)')
width
numberLine width for series
opacity
numberOpacity of series (0-1)
border
ObjectBorder configuration for series (width, color, dashArray)
marker
ObjectData point marker configuration (visible, size, shape, fill, border)
animation
ObjectAnimation settings (enable, duration, delay)
legendShape
stringLegend icon shape (Circle, Rectangle, Triangle, Diamond, etc.)
tooltip
ObjectSeries-specific tooltip configuration
trendlines
ArrayTrend lines for this series
cornerRadius
numberCorner radius for rectangular shapes
属性类型描述
dataSource
Array股票数据数组
type
string系列类型(Candle、Line、Spline、Hilo、HiloOpenClose)
xName
stringX轴的数据字段(日期)
high
string最高价的数据字段
low
string最低价的数据字段
open
string开盘价的数据字段
close
string收盘价的数据字段
volume
string成交量的数据字段
name
string图例中的系列名称
yName
stringY轴的数据字段
yAxisName
string绑定该系列的Y轴名称(用于多轴)
bearFillColor
string下跌趋势K线/柱的填充色
bullFillColor
string上涨趋势K线/柱的填充色
fill
string系列颜色或渐变填充(例如:'url(#gradient1)')
width
number系列线条宽度
opacity
number系列透明度(0-1)
border
Object系列边框配置(宽度、颜色、虚线样式)
marker
Object数据点标记配置(可见性、尺寸、形状、填充色、边框)
animation
Object动画设置(启用、时长、延迟)
legendShape
string图例图标形状(Circle、Rectangle、Triangle、Diamond等)
tooltip
Object系列专属的工具提示配置
trendlines
Array该系列的趋势线
cornerRadius
number矩形形状的圆角半径

Common Use Cases

常见用例

  1. Stock Trading Platform - Display real-time or historical stock prices with candlestick charts
  2. Financial Analytics Dashboard - Multi-chart layout with technical indicators and events
  3. Portfolio Tracker - Visualize investment performance over time
  4. Market Research Tool - Compare multiple stocks with different series types
  5. Trading Algorithm Backtesting - Visualize strategy results with indicators and trend lines
  6. Economic Data Visualization - Display time-series financial or economic data
  7. Cryptocurrency Charts - Track crypto price movements with OHLC data
  1. 股票交易平台 - 用K线图显示实时或历史股票价格
  2. 金融分析仪表盘 - 多图表布局,包含技术指标和事件
  3. 投资组合追踪器 - 可视化投资随时间的表现
  4. 市场研究工具 - 用不同系列类型比较多只股票
  5. 交易算法回测 - 用指标和趋势线可视化策略结果
  6. 经济数据可视化 - 显示时间序列的金融或经济数据
  7. 加密货币图表 - 用OHLC数据追踪加密货币价格走势

Module Injection

模块注入

Stock Chart requires explicit module injection for features:
typescript
import { Inject, DateTime, DateTimeCategory, Logarithmic, 
         Tooltip, RangeTooltip, Crosshair, 
         LineSeries, SplineSeries, CandleSeries, HiloOpenCloseSeries, 
         HiloSeries, RangeAreaSeries, StockLegend, Trendlines, Export } from '@syncfusion/ej2-react-charts';
import { EmaIndicator, RsiIndicator, BollingerBands, TmaIndicator, 
         MomentumIndicator, SmaIndicator, AtrIndicator, 
         AccumulationDistributionIndicator, MacdIndicator, 
         StochasticIndicator } from '@syncfusion/ej2-react-charts';

<StockChartComponent>
  <Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, 
                     CandleSeries, StockLegend, Trendlines, Export,
                     EmaIndicator, SmaIndicator, BollingerBands]} />
</StockChartComponent>
Common modules:
Axes:
  • DateTime - DateTime axis (required for stock charts)
  • DateTimeCategory - DateTime category axis for business days only
  • Logarithmic - Logarithmic scale axis
UI Features:
  • Tooltip - Hover tooltips for data points
  • RangeTooltip - Range selector tooltips
  • Crosshair - Crosshair lines with axis tooltips
  • StockLegend - Legend display for series
Series Types:
  • LineSeries, SplineSeries - Line charts
  • CandleSeries - Traditional candlestick chart
  • HiloOpenCloseSeries - OHLC bars
  • HiloSeries - High-Low bars
  • RangeAreaSeries - Range area visualization
Technical Analysis:
  • Trendlines - Trend line visualization (Linear, Exponential, Logarithmic, Polynomial, Power, Moving Average)
  • EmaIndicator, SmaIndicator, TmaIndicator - Moving average indicators
  • RsiIndicator, BollingerBands, MacdIndicator - Advanced indicators
  • StochasticIndicator, MomentumIndicator, AtrIndicator - Momentum indicators
  • AccumulationDistributionIndicator - Volume-based indicator
Export:
  • Export - Export to PNG, JPEG, SVG, PDF
股票图表需要显式注入模块以启用功能:
typescript
import { Inject, DateTime, DateTimeCategory, Logarithmic, 
         Tooltip, RangeTooltip, Crosshair, 
         LineSeries, SplineSeries, CandleSeries, HiloOpenCloseSeries, 
         HiloSeries, RangeAreaSeries, StockLegend, Trendlines, Export } from '@syncfusion/ej2-react-charts';
import { EmaIndicator, RsiIndicator, BollingerBands, TmaIndicator, 
         MomentumIndicator, SmaIndicator, AtrIndicator, 
         AccumulationDistributionIndicator, MacdIndicator, 
         StochasticIndicator } from '@syncfusion/ej2-react-charts';

<StockChartComponent>
  <Inject services={[DateTime, Tooltip, RangeTooltip, Crosshair, 
                     CandleSeries, StockLegend, Trendlines, Export,
                     EmaIndicator, SmaIndicator, BollingerBands]} />
</StockChartComponent>
常见模块:
轴模块:
  • DateTime - 日期时间轴(股票图表必需)
  • DateTimeCategory - 仅包含工作日的日期时间分类轴
  • Logarithmic - 对数刻度轴
UI功能模块:
  • Tooltip - 数据点悬停工具提示
  • RangeTooltip - 范围选择器工具提示
  • Crosshair - 带轴工具提示的十字线
  • StockLegend - 系列图例显示
系列类型模块:
  • LineSeries, SplineSeries - 折线图
  • CandleSeries - 传统K线图
  • HiloOpenCloseSeries - OHLC柱图
  • HiloSeries - 高低柱图
  • RangeAreaSeries - 范围区域可视化
技术分析模块:
  • Trendlines - 趋势线可视化(线性、指数、对数、多项式、幂函数、移动平均线)
  • EmaIndicator, SmaIndicator, TmaIndicator - 移动平均线指标
  • RsiIndicator, BollingerBands, MacdIndicator - 高级指标
  • StochasticIndicator, MomentumIndicator, AtrIndicator - 动量指标
  • AccumulationDistributionIndicator - 成交量指标
导出模块:
  • Export - 导出为PNG、JPEG、SVG、PDF

Event Handling

事件处理

Stock Chart provides comprehensive event support for tracking user interactions and building custom behaviors:
股票图表提供全面的事件支持,用于追踪用户交互和构建自定义行为:

Data Point Events

数据点事件

typescript
// Point click event
const handlePointClick = (args) => {
  console.log('Point clicked:', args.pointIndex, args.seriesIndex);
  console.log('X:', args.x, 'Y:', args.y);
};

// Point move event (hover)
const handlePointMove = (args) => {
  console.log('Hovering over point:', args.x);
};

<StockChartComponent
  pointClick={handlePointClick}
  pointMove={handlePointMove}
>
  {/* ... */}
</StockChartComponent>
typescript
// 点点击事件
const handlePointClick = (args) => {
  console.log('Point clicked:', args.pointIndex, args.seriesIndex);
  console.log('X:', args.x, 'Y:', args.y);
};

// 点移动事件(悬停)
const handlePointMove = (args) => {
  console.log('Hovering over point:', args.x);
};

<StockChartComponent
  pointClick={handlePointClick}
  pointMove={handlePointMove}
>
  {/* ... */}
</StockChartComponent>

Mouse Events

鼠标事件

typescript
// Various mouse tracking events
const handleMouseMove = (args) => {
  console.log('Mouse position:', args.x, args.y);
};

const handleMouseLeave = (args) => {
  console.log('Mouse left chart area');
};

const handleMouseClick = (args) => {
  console.log('Chart clicked');
};

<StockChartComponent
  stockChartMouseMove={handleMouseMove}
  stockChartMouseLeave={handleMouseLeave}
  stockChartMouseClick={handleMouseClick}
  stockChartMouseDown={(args) => console.log('Mouse down')}
  stockChartMouseUp={(args) => console.log('Mouse up')}
>
  {/* ... */}
</StockChartComponent>
typescript
// 各种鼠标追踪事件
const handleMouseMove = (args) => {
  console.log('Mouse position:', args.x, args.y);
};

const handleMouseLeave = (args) => {
  console.log('Mouse left chart area');
};

const handleMouseClick = (args) => {
  console.log('Chart clicked');
};

<StockChartComponent
  stockChartMouseMove={handleMouseMove}
  stockChartMouseLeave={handleMouseLeave}
  stockChartMouseClick={handleMouseClick}
  stockChartMouseDown={(args) => console.log('Mouse down')}
  stockChartMouseUp={(args) => console.log('Mouse up')}
>
  {/* ... */}
</StockChartComponent>

Range and Selector Events

范围与选择器事件

typescript
// Range change event (period selector or range selector)
const handleRangeChange = (args) => {
  console.log('Range changed:', args.start, 'to', args.end);
  // Refresh data or update analysis
};

<StockChartComponent
  rangeChange={handleRangeChange}
>
  {/* ... */}
</StockChartComponent>
typescript
// 范围变化事件(周期选择器或范围选择器)
const handleRangeChange = (args) => {
  console.log('Range changed:', args.start, 'to', args.end);
  // 刷新数据或更新分析
};

<StockChartComponent
  rangeChange={handleRangeChange}
>
  {/* ... */}
</StockChartComponent>

Legend Events

图例事件

typescript
// Legend click event
const handleLegendClick = (args) => {
  console.log('Legend item clicked:', args.legendText);
};

// Legend render event (for customization)
const handleLegendRender = (args) => {
  if (args.legendText === 'AAPL') {
    args.fill = '#ff0000'; // Customize legend color
  }
};

<StockChartComponent
  legendClick={handleLegendClick}
  legendRender={handleLegendRender}
>
  {/* ... */}
</StockChartComponent>
typescript
// 图例点击事件
const handleLegendClick = (args) => {
  console.log('Legend item clicked:', args.legendText);
};

// 图例渲染事件(用于自定义)
const handleLegendRender = (args) => {
  if (args.legendText === 'AAPL') {
    args.fill = '#ff0000'; // 自定义图例颜色
  }
};

<StockChartComponent
  legendClick={handleLegendClick}
  legendRender={handleLegendRender}
>
  {/* ... */}
</StockChartComponent>

Tooltip Events

工具提示事件

typescript
// Customize tooltip before rendering
const handleTooltipRender = (args) => {
  args.text = `<b>Stock Price: ${args.text}</b>`;
};

<StockChartComponent
  tooltip={{ enable: true }}
  tooltipRender={handleTooltipRender}
>
  {/* ... */}
</StockChartComponent>
typescript
// 渲染前自定义工具提示
const handleTooltipRender = (args) => {
  args.text = `<b>Stock Price: ${args.text}</b>`;
};

<StockChartComponent
  tooltip={{ enable: true }}
  tooltipRender={handleTooltipRender}
>
  {/* ... */}
</StockChartComponent>

Stock Event Rendering

股票事件渲染事件

typescript
// Customize stock event markers
const handleStockEventRender = (args) => {
  // Customize event styling, position, etc.
  if (args.text === 'Earnings') {
    args.background = '#ff0000'; // Custom color for earnings
  }
};

<StockChartComponent
  stockEvents={stockEvents}
  stockEventRender={handleStockEventRender}
>
  {/* ... */}
</StockChartComponent>
typescript
// 自定义股票事件标记
const handleStockEventRender = (args) => {
  // 自定义事件样式、位置等
  if (args.text === 'Earnings') {
    args.background = '#ff0000'; // 收益事件自定义颜色
  }
};

<StockChartComponent
  stockEvents={stockEvents}
  stockEventRender={handleStockEventRender}
>
  {/* ... */}
</StockChartComponent>

Lifecycle Events

生命周期事件

typescript
// Load event (before rendering)
const handleLoad = (args) => {
  console.log('Chart loading');
};

// Loaded event (after rendering)
const handleLoaded = (args) => {
  console.log('Chart loaded');
};

<StockChartComponent
  load={handleLoad}
  loaded={handleLoaded}
>
  {/* ... */}
</StockChartComponent>
typescript
// 加载事件(渲染前)
const handleLoad = (args) => {
  console.log('Chart loading');
};

// 加载完成事件(渲染后)
const handleLoaded = (args) => {
  console.log('Chart loaded');
};

<StockChartComponent
  load={handleLoad}
  loaded={handleLoaded}
>
  {/* ... */}
</StockChartComponent>

API Reference

API参考

Below is a concise API reference derived from the official Syncfusion
StockChart
API. Include or expand these entries in
references/*
as needed.
Complete API Documentation:
以下是从官方Syncfusion
StockChart
API中提取的简明API参考。可根据需要在
references/*
中包含或扩展这些条目。
完整API文档:

Selected Props (StockChartComponent)

StockChartComponent精选属性

Data & Series:
Axes:
Navigation & Selectors:
Analysis & Events:
Interaction & UI:
Selection & Appearance:
Theming & Layout:
Export & Persistence:
Series & Analysis:
Accessibility & RTL:
Zoom & Pan:
数据与系列:
轴:
导航与选择器:
分析与事件:
交互与UI:
选择与外观:
主题与布局:
导出与持久化:
系列与分析:
可访问性与RTL:
缩放与平移:

Methods

方法

Events

事件

Lifecycle Events:
Data & Rendering Events:
User Interaction Events:
Tooltip & Crosshair Events:
Range & Selector Events:
Technical Analysis Events:
生命周期事件:
数据与渲染事件:
用户交互事件:
工具提示与十字线事件:
范围与选择器事件:
技术分析事件:

Suggested reference files and sections

建议的参考文件和章节

  • references/api.md
    — Full API surface summary (props, methods, events) with links to official docs.
  • references/configuration.md
    — Move/expand prop-specific docs (axes, theme, sizing).
  • references/interactive-features.md
    — Add event hooks and examples for
    tooltipRender
    ,
    pointClick
    ,
    axisLabelRender
    .
  • references/technical-analysis.md
    — Expand
    indicators
    and
    stockEvents
    API samples.
  • references/api.md
    — 完整API表面摘要(属性、方法、事件),带官方文档链接。
  • references/configuration.md
    — 移动/扩展属性特定文档(轴、主题、尺寸)。
  • references/interactive-features.md
    — 添加
    tooltipRender
    pointClick
    axisLabelRender
    的事件钩子和示例。
  • references/technical-analysis.md
    — 扩展
    indicators
    stockEvents
    的API示例。

Minimal API example (props + events)

最小API示例(属性 + 事件)

tsx
<StockChartComponent
  id="stockchart"
  dataSource={data}
  primaryXAxis={{ valueType: 'DateTime' }}
  enablePeriodSelector={true}
  indicators={[{ type: 'Sma', period: 14 }]}
  stockEvents={[{ date: new Date(2023,0,1), text: 'Earnings' }]}
  tooltip={{ enable: true }}
  crosshair={{ enable: true }}
  load={(args) => console.log('loading', args)}
  loaded={(args) => console.log('loaded', args)}
  axisLabelRender={(args) => {/* modify labels */}}
  pointClick={(args) => {/* handle point click */}}
>
  <Inject services={[DateTime, CandleSeries, Tooltip, Crosshair]} />
  <StockChartSeriesCollectionDirective>
    <StockChartSeriesDirective type="Candle" xName="x" open="open" high="high" low="low" close="close" />
  </StockChartSeriesCollectionDirective>
</StockChartComponent>
tsx
<StockChartComponent
  id="stockchart"
  dataSource={data}
  primaryXAxis={{ valueType: 'DateTime' }}
  enablePeriodSelector={true}
  indicators={[{ type: 'Sma', period: 14 }]}
  stockEvents={[{ date: new Date(2023,0,1), text: 'Earnings' }]}
  tooltip={{ enable: true }}
  crosshair={{ enable: true }}
  load={(args) => console.log('loading', args)}
  loaded={(args) => console.log('loaded', args)}
  axisLabelRender={(args) => {/* 修改标签 */}}
  pointClick={(args) => {/* 处理点点击 */}}
>
  <Inject services={[DateTime, CandleSeries, Tooltip, Crosshair]} />
  <StockChartSeriesCollectionDirective>
    <StockChartSeriesDirective type="Candle" xName="x" open="open" high="high" low="low" close="close" />
  </StockChartSeriesCollectionDirective>
</StockChartComponent>