KLineChart Pro

repository·main·Indexed 43 days ago

https://github.com/klinecharts/pro

A professional financial chart library built on top of the KLineChart engine, providing out-of-the-box charting capabilities. Version 0.1.1 includes features for managing chart themes, styles, locales, and timezones, as well as support for custom datafeeds or a built-in DefaultDatafeed that integrates with Polygon.io.

Tokens
18.6K
Snippets
72
Records
78
Agent score
53%

What's inside KLineChart Pro

  1. What is KLineChart Pro?

    main
    KLineChart Pro is a financial charting library that provides an encapsulated UI layer built on top of the core KLineChart engine. It is designed to simplify the integration process for developers who want to implement financial charts quickly without needing deep front-end UI development expertise.
  2. Define a Period object

    main

    A Period object defines the time interval for chart data. It consists of a multiplier, a timespan unit, and a display string.

    • multiplier: A number representing the time span multiplier (e.g., 1, 3, 5).
    • timespan: A string representing the time unit (e.g., 'year', 'month', 'day', 'hour', 'minute').
    • text: The string used for UI display (e.g., '1H', '5M').
    interface Period {
      // Time span multiplier, such as 1, 3, 5
      multiplier: number;
    
      // Time span, such as 'year', 'month'
      timespan: string;
    
      // Text for display, such as '1H', '5H'
      text: string;
    }
  3. Implement a custom datafeed API

    main

    To use your own data source, you must implement a class that satisfies the datafeed interface. Your implementation must provide the following four methods:

    1. searchSymbols(search?: string): Performs a fuzzy search for symbols. Returns a Promise<SymbolInfo[]>. Triggered when the search box is used.
    2. getHistoryKLineData(symbol: SymbolInfo, period: Period, from: number, to: number): Fetches historical k-line data. Returns a Promise<KLineData[]>. Triggered when the symbol or period changes.
    3. subscribe(symbol: SymbolInfo, period: Period, callback: DatafeedSubscribeCallback): Subscribes to real-time data (via WebSocket or HTTP polling). Uses the provided callback to notify the chart of new data.
    4. unsubscribe(symbol: SymbolInfo, period: Period): Cancels the real-time data subscription.
    class CustomDatafeed {
      /**
       * Fuzzy search symbols
       * Triggered when the search box is entered
       * Returns an array of symbol information
       */
      searchSymbols (search?: string): Promise<SymbolInfo[]> {
        // Remote pull of symbol data based on fuzzy fields
      }
    
      /**
       * Pull historical k-line data
       * Triggered when the symbol and period change
       * 
       * Returns the symbol k-line data array
       */
      getHistoryKLineData (symbol: SymbolInfo, period: Period, from: number, to: number): Promise<KLineData[]> {
        // Complete data request
      }
    
      /**
       * Subscribe to real-time data of the symbol in a certain period
       * Triggered when the symbol and period change
       * 
       * Notify chart to receive data through callback
       */
      subscribe (symbol: SymbolInfo, period: Period, callback: DatafeedSubscribeCallback): void {
        // Complete ws subscription or http polling
      }
    
      /**
       * Unsubscribe to real-time data of the symbol in a certain period
       * Triggered when the symbol and period change
       * 
       */ 
      unsubscribe (symbol: SymbolInfo, period: Period): void {
        // Complete ws subscription cancellation or http polling cancellation
      }
    }
  4. Install @klinecharts/pro via npm or yarn

    main

    You can install the KLineChart Pro package using standard package managers like npm or yarn to add it to your project dependencies.

    # using npm
    npm install @klinecharts/pro --save
    
    # using yarn
    yarn add @klinecharts/pro
  5. Integrate custom data into KLineChart Pro

    main

    Once you have implemented your CustomDatafeed class, pass an instance of it to the datafeed option in the KLineChartPro constructor.

    import { KLineChartPro } from '@klinecharts/pro'
    
    // Assuming CustomDatafeed is implemented as described in the API guide
    const chart = new KLineChartPro({
      container: document.getElementById('container'),
      datafeed: new CustomDatafeed()
    })
  6. Install @klinecharts/pro via CDN (unpkg or jsDelivr)

    main

    For quick prototyping or environments without a build step, you can include KLineChart Pro directly in your HTML using a <script> tag via unpkg or jsDelivr. The UMD build is located at dist/klinecharts-pro.umd.js.

    <!-- using unpkg -->
    <script src="https://unpkg.com/@klinecharts/pro/dist/klinecharts-pro.umd.js"></script>
    
    <!-- using jsdelivr -->
    <script src="https://cdn.jsdelivr.net/npm/@klinecharts/pro/dist/klinecharts-pro.umd.js"></script>
  7. Register a new language for the Pro chart

    main

    To add support for a custom language specifically for the Pro features, use the loadLocales function from @klinecharts/pro. This function requires a locale key and an object containing the Pro-specific translations (such as indicator, main_indicator, and sub_indicator).

    For a complete list of required keys, refer to the Pro locale JSON definitions in the source repository.

    import { loadLocales } from '@klinecharts/pro'
    
    // For specific keys, see https://github.com/klinecharts/pro/blob/main/src/i18n/zh-CN.json
    loadLocales(`${key}`, {
      "indicator": "xxx",
      "main_indicator": "xxx",
      "sub_indicator": "xxx",
      ......
      ......
    })
  8. Install KLineChart Pro via npm or yarn

    main

    To use KLineChart Pro in a modern JavaScript project, install both the core klinecharts package and the @klinecharts/pro package using your preferred package manager.

    # npm
    npm install klinecharts @klinecharts/pro
    
    # yarn
    yarn install klinecharts @klinecharts/pro
  9. Initialize KLineChart Pro via script tags

    main

    To use KLineChart Pro without a package manager, include the UMD script and the CSS link in your HTML. The global namespace for the library will be klinechartspro.

    <!-- Import js -->
    <script src="https://cdn.jsdelivr.net/@klinecharts/pro/dist/klinecharts-pro.umd.js"></script>
    
    <!-- Import css -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/@klinecharts/pro/dist/klinecharts-pro.css"/>
    
    <script>
      // Create Instance
      const chart = new klinechartspro.KLineChartPro({
        container: document.getElementById('container'),
        // Default symbol info
        symbol: {
          exchange: 'XNYS',
          market: 'stocks',
          name: 'Alibaba Group Holding Limited American Depositary Shares, each represents eight Ordinary Shares',
          shortName: 'BABA',
          ticker: 'BABA',
          priceCurrency: 'usd',
          type: 'ADRC',
        },
        // Default period
        period: { multiplier: 15, timespan: 'minute', text: '15m' },
        // The default data access is used here. If the default data is also used in actual use, you need to go to the https://polygon.io/ apply for API key
        datafeed: new klinechartspro.DefaultDatafeed(`${polygonIoApiKey}`)
      })
    </script>
  10. Initialize a KLineChart Pro instance via script tags

    main

    When using the CDN approach, include the UMD script and the CSS link in your HTML. Access the classes through the global klinechartspro namespace.

    <!-- 引入js -->
    <script src="https://cdn.jsdelivr.net/@klinecharts/pro/dist/klinecharts-pro.umd.js"></script>
    
    <!-- 引入css -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/@klinecharts/pro/dist/klinecharts-pro.css"/>
    <script>
      // 创建实例
      const chart = new klinechartspro.KLineChartPro({
        container: document.getElementById('container'),
        // 初始化标的信息
        symbol: {
          exchange: 'XNYS',
          market: 'stocks',
          name: 'Alibaba Group Holding Limited American Depositary Shares, each represents eight Ordinary Shares',
          shortName: 'BABA',
          ticker: 'BABA',
          priceCurrency: 'usd',
          type: 'ADRC',
        },
        // 初始化周期
        period: { multiplier: 15, timespan: 'minute', text: '15m' },
        // 这里使用默认的数据接入,如果实际使用中也使用默认数据,需要去 https://polygon.io/ 申请 API key
        datafeed: new klinechartspro.DefaultDatafeed(`${polygonIoApiKey}`)
      })
    </script>
  11. Install KLineChart Pro via CDN

    main

    For projects using direct <script> tags, you can include KLineChart Pro via unpkg or jsDelivr.

    ::: warning For production environments, it is recommended to use a specific version number to avoid unexpected breaking changes from new releases. :::

    <!-- unpkg -->
    <script src="https://unpkg.com/@klinecharts/pro/dist/klinecharts-pro.umd.js"></script>
    
    <!-- jsdelivr -->
    <script src="https://cdn.jsdelivr.net/@klinecharts/pro/dist/klinecharts-pro.umd.js"></script>
  12. Use the default Polygon.io datafeed

    main

    KLineChart Pro provides a built-in DefaultDatafeed class that connects to https://polygon.io/. To use it, you must obtain an API key from Polygon.io and pass it to the DefaultDatafeed constructor when initializing KLineChartPro.

    import { KLineChartPro, DefaultDatafeed } from '@klinecharts/pro'
    const chart = new KLineChartPro({
      container: document.getElementById('container'),
      datafeed: new DefaultDatafeed(`${polygonIoApiKey}`)
    })