KLineChart Documentation

repository·main·Indexed 26 days ago

https://github.com/klinecharts/klinechart

A lightweight, high-performance k-line (candlestick) chart library built with HTML5 Canvas. It features zero dependencies and provides built-in indicators, drawing models, and support for custom DataLoaders, overlays, and localization. The library includes APIs for chart initialization, layout configuration, custom hotkey registration, and technical indicator management.

Tokens
90.1K
Snippets
163
Records
559
Agent score
86%

What's inside klinecharts

  1. Overview of KLineChart

    main

    KLineChart is a professional-grade, lightweight financial charting library for web frontends, specifically designed for K-line (candlestick) and derivative market data scenarios. It is suitable for trading platforms, market analysis, and investment research systems.

    Key features include:

    • Out-of-the-box: Simple and fast integration with minimal setup cost.
    • Lightweight & Smooth: Zero dependencies, with a size of only 40k under Gzip compression.
    • Powerful: Built-in support for various technical indicators and drawing models.
    • Highly Extensible: Rich style configurations and APIs for custom functionality.
    • Mobile Support: Single chart implementation works across multiple platforms/devices.
    • TypeScript Support: Provides complete type definitions for robust development.
  2. Overview of KLineChart features

    main

    KLineChart is a professional, lightweight financial charting library designed for web applications focusing on candlestick and market data.

    Key features include:

    • Zero dependencies: Lightweight bundle size (under 40k gzip).
    • Out of the box: Simple and fast integration.
    • Powerful functions: Built-in technical indicators and line drawing models.
    • Highly scalable: Rich style configuration and extensible API.
    • Mobile support: Single chart implementation that handles multiple terminals.
    • TypeScript support: Complete type definition files provided.
  3. Understand KLineChart architecture and entry points

    main

    Core Architecture Layers

    • Chart: Manages Panes, handles event dispatching, updates Store, and notifies lower layers.
    • Pane: Creates DOM containers, organizing Widgets into areas like main charts, indicator areas, or axes.
    • Widget: Manages canvas and groups related Views.
    • View: The smallest business drawing unit. Reads data from Store to draw K-lines, indicators, grids, etc.
    • Figure: Basic geometric primitives (circles, lines, polygons, text).

    Key Entry Points and Lifecycle

    • Public Entry: src/index.ts.
    • Initialization: init creates the chart instance and mounts it.
    • Destruction: dispose destroys the instance and releases resources.
    • Extensions: Use registerFigure, registerIndicator, registerOverlay, registerXAxis, registerYAxis, registerStyles, and registerLocale to add capabilities.

    Data and State

    • State Center: src/Store.ts maintains data lists, visible ranges, zoom/scroll states, styles, and indicator/overlay instances.
    • Data Types: Found in src/common/Data.ts, src/common/DataLoader.ts, and src/Options.ts.
  4. Access KLineChart Skill Documentation

    main

    KLineChart provides specialized skill files to assist AI agents and developers. The following files contain specific knowledge categories:

    • SKILL.md: Main skill containing minimal examples, data loading, framework integration, indicators/overlays, v9 migration, and troubleshooting.
    • api-reference.md: v10 API quick reference.
    • examples.md: Full copy-paste examples.
    • prompts.md: Prompt templates for common tasks.
  5. Quickstart: Minimal KLineChart Integration

    main

    To integrate KLineChart (v10) into your project, follow this specific initialization sequence: initsetSymbolsetPeriodsetDataLoader. The container element must have an explicit width and height defined in CSS.

    import { init, dispose } from 'klinecharts'
    
    const chart = init('chart') // HTMLElement or id
    chart.setSymbol({ ticker: 'BTCUSDT', pricePrecision: 2, volumePrecision: 0 })
    chart.setPeriod({ span: 1, type: 'day' })
    chart.setDataLoader({
      getBars: ({ callback }) => {
        callback([
          { timestamp: 1517846400000, open: 7424.6, high: 7511.3, low: 6032.3, close: 7310.1, volume: 224461 },
        ])
      }
    })
    // cleanup: dispose('chart')
  6. Integrate klinecharts with Vue

    main

    To use klinecharts in a Vue application, initialize the chart within the onMounted lifecycle hook to ensure the DOM element is available. Use init(id) to create the chart instance and dispose(id) within the onUnmounted hook to clean up the chart and prevent memory leaks.

    Key steps:

    1. Import init and dispose from klinecharts.
    2. Create a container element (e.g., <div id="chart">).
    3. Call init('chart') inside onMounted.
    4. Call dispose('chart') inside onUnmounted.
    <script setup>
    import { onMounted, onUnmounted } from 'vue'
    import { init, dispose } from 'klinecharts'
    
    onMounted(() => {
      const chart = init('chart')
      // Configure chart here...
    })
    
    onUnmounted(() => {
      dispose('chart')
    })
    </script>
    
    <template>
      <div id="chart" style="width:600px;height:600px"/>
    </template>
  7. Add KLineChart Agent Skills to your IDE

    main

    If you are using an IDE that supports Agent Skills (such as Cursor), you can add KLineChart skills to your environment to improve development efficiency. This provides the agent with context regarding minimal examples, data loading, framework integration, indicators, overlays, v9 migration, and troubleshooting.

    Use the following command to add the skills:

    npx skills add klinecharts/KLineChart
  8. Configure SSR, Next.js, and Nuxt environments

    main

    Because the chart depends on the DOM and Canvas API, it cannot be initialized during the server-side rendering (SSR) phase.

    To avoid errors in SSR frameworks like Next.js or Nuxt:

    • Only execute init(...) after the component has mounted on the client side.
    • Do not attempt to read or access the container DOM element at the top level of a module.
    • If the chart container is rendered conditionally (e.g., inside a hidden tab or modal), wait until the container is actually visible before initializing or manually calling resize(...).
  9. Quick Start with Vanilla JavaScript and CDN

    main

    To use klinecharts in a vanilla JavaScript environment without a build tool, you can include the library via a CDN.

    1. Include the script tag in your HTML <head>: <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/klinecharts/dist/umd/klinecharts.min.js"></script>
    2. Create a container element (e.g., a <div>) with a specific id and defined dimensions.
    3. Initialize the chart using klinecharts.init('container_id').
    4. Configure the symbol, period, and data loader to display information.
    <!DOCTYPE html>
    <html lang="cn" >
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="theme-color" content="#000000" />
        <meta name="keywords" content="Quick Start"/>
        <meta name="description" content="Quick Start"/>
        <title>Quick Start</title>
        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/klinecharts/dist/umd/klinecharts.min.js"></script>
      </head>
      <body>
        <div id="chart" style="width:600px;height:600px"></div>
        <script>
          window.onload = function () {
            var chart = klinecharts.init('chart')
            chart.setSymbol({ ticker: 'TestSymbol' })
            chart.setPeriod({ span: 1, type: 'day' })
            chart.setDataLoader({
              getBars: ({ callback}) => {
                callback([
                  { timestamp: 1517846400000, open: 7424.6, high: 7511.3, low: 6032.3, close: 7310.1, volume: 224461 },
                  { timestamp: 1517932800000, open: 7310.1, high: 8499.9, low: 6810, close: 8165.4, volume: 148807 },
                  { timestamp: 1518019200000, open: 8166.7, high: 8700.8, low: 7400, close: 8245.1, volume: 24467 },
                  { timestamp: 1518105600000, open: 8244, high: 8494, low: 7760, close: 8364, volume: 29834 },
                  { timestamp: 1518192000000, open: 8363.6, high: 9036.7, low: 8269.8, close: 8311.9, volume: 28203 },
                  { timestamp: 1518278400000, open: 8301, high: 8569.4, low: 7820.2, close: 8426, volume: 59854 },
                  { timestamp: 1518364800000, open: 8426, high: 8838, low: 8024, close: 8640, volume: 54457 },
                  { timestamp: 1518451200000, open: 8640, high: 8976.8, low: 8360, close: 8500, volume: 51156 },
                  { timestamp: 1518537600000, open: 8504.9, high: 9307.3, low: 8474.3, close: 9307.3, volume: 49118 },
                  { timestamp: 1518624000000, open: 9307.3, high: 9897, low: 9182.2, close: 9774, volume: 48092 }
                ])
              }
            })
          }
        </script>
      </body>
    </html>
  10. Manage container dimensions and initialization timing

    main

    The chart automatically fills its parent container, so the container must have explicit dimensions.

    Best practices for container setup:

    • Ensure the container has a defined height.
    • If the width is adaptive, ensure the parent layout is stable before initialization.
    • If the container starts as display: none or is inside an inactive tab, you must call resize(...) once the container becomes visible to ensure the chart renders correctly.

    Troubleshooting: If the chart only shows a single line or has abnormal height, check if the container has a valid width and height.

  11. Customize chart styles

    main

    You can customize the appearance of almost all visual elements on the chart, including points and lines. Styles can be applied in two ways:

    1. During initialization: Pass a styles object within the options parameter of the init(ds, options) method.
    2. After initialization: Use the setStyles(styles) method on the chart instance to update styles dynamically.