k_chart 0.1.1

  • Readme
  • Changelog
  • Example
  • Installing
  • 72

k_chart #

Maybe this is the best k chart in Flutter.Support drag,scale,long press,fling.And easy to use.

demo

Getting Started #

Install

dependencies:
  k_chart: ^0.1.1

or use latest:

k_chart:
    git:
      url: https://github.com/mafanwei/k_chart

Usage

When you change the data, you must call this:

DataUtil.calculate(datas); //This function has some optional parameters: n is BOLL N-day closing price. k is BOLL param.

use k line chart:

Container(
              height: 450,
              width: double.infinity,
              child: KChartWidget(
                datas,// Required,Data must be an ordered list,(history=>now)
                isLine: isLine,// Decide whether it is k-line or time-sharing
                mainState: _mainState,// Decide what the main view shows
                secondaryState: _secondaryState,// Decide what the sub view shows
                fixedLength: 2,// Displayed decimal precision
                timeFormat: TimeFormat.YEAR_MONTH_DAY,
                onLoadMore: (bool a) {},// Called when the data scrolls to the end. When a is true, it means the user is pulled to the end of the right side of the data. When a
                // is false, it means the user is pulled to the end of the left side of the data.
                maDayList: [5,10,20],// Display of MA,This parameter must be equal to DataUtil.calculate‘s maDayList
                bgColor: [Colors.black, Colors.black],// The background color of the chart is gradient
                isChinese: true,// Graphic language
                isOnDrag: (isDrag){},// true is on Drag.Don't load data while Draging.
              ),
            ),

use depth chart:

DepthChart(_bids, _asks) //Note: Datas must be an ordered list,

if you want change DepthChart color, you can use just like this:

 Container(
            height: 230,
            width: double.infinity,
            color: Colors.grey, //background color
            child: DepthChart(_bids, _asks,buyPathColor: Colors.blue, sellPathColor: Colors.green),
          )

Buy a cup of coffee for the author.

alipay wechat

Other

Maybe there are some bugs in this k chart,or you want new indicators,you can create a pull request.I will happy to accept it and I hope we can make it better.

[0.1.1] #

  • NEW: Initial Release.

example/lib/main.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:k_chart/flutter_k_chart.dart';
import 'package:k_chart/k_chart_widget.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<KLineEntity> datas;
  bool showLoading = true;
  MainState _mainState = MainState.MA;
  SecondaryState _secondaryState = SecondaryState.MACD;
  bool isLine = true;
  bool isChinese = true;
  List<DepthEntity> _bids, _asks;

  @override
  void initState() {
    super.initState();
    getData('1day');
    rootBundle.loadString('assets/depth.json').then((result) {
      final parseJson = json.decode(result);
      Map tick = parseJson['tick'];
      var bids = tick['bids'].map((item) => DepthEntity(item[0], item[1])).toList().cast<DepthEntity>();
      var asks = tick['asks'].map((item) => DepthEntity(item[0], item[1])).toList().cast<DepthEntity>();
      initDepth(bids, asks);
    });
  }

  void initDepth(List<DepthEntity> bids, List<DepthEntity> asks) {
    if (bids == null || asks == null || bids.isEmpty || asks.isEmpty) return;
    _bids = List();
    _asks = List();
    double amount = 0.0;
    bids?.sort((left, right) => left.price.compareTo(right.price));
    //累加买入委托量
    bids.reversed.forEach((item) {
      amount += item.vol;
      item.vol = amount;
      _bids.insert(0, item);
    });

    amount = 0.0;
    asks?.sort((left, right) => left.price.compareTo(right.price));
    //累加卖出委托量
    asks?.forEach((item) {
      amount += item.vol;
      item.vol = amount;
      _asks.add(item);
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff17212F),
//      appBar: AppBar(title: Text(widget.title)),
      body: ListView(
        children: <Widget>[
          Stack(children: <Widget>[
            Container(
              height: 450,
              width: double.infinity,
              child: KChartWidget(
                datas,
                isLine: isLine,
                mainState: _mainState,
                secondaryState: _secondaryState,
                fixedLength: 2,
                timeFormat: TimeFormat.YEAR_MONTH_DAY,
                isChinese: isChinese,
              ),
            ),
            if (showLoading) Container(width: double.infinity, height: 450, alignment: Alignment.center, child: CircularProgressIndicator()),
          ]),
          buildButtons(),
          Container(
            height: 230,
            width: double.infinity,
            child: DepthChart(_bids, _asks),
          )
        ],
      ),
    );
  }

  Widget buildButtons() {
    return Wrap(
      alignment: WrapAlignment.spaceEvenly,
      children: <Widget>[
        button("分时", onPressed: () => isLine = true),
        button("k线", onPressed: () => isLine = false),
        button("MA", onPressed: () => _mainState = MainState.MA),
        button("BOLL", onPressed: () => _mainState = MainState.BOLL),
        button("隐藏", onPressed: () => _mainState = MainState.NONE),
        button("MACD", onPressed: () => _secondaryState = SecondaryState.MACD),
        button("KDJ", onPressed: () => _secondaryState = SecondaryState.KDJ),
        button("RSI", onPressed: () => _secondaryState = SecondaryState.RSI),
        button("WR", onPressed: () => _secondaryState = SecondaryState.WR),
        button("隐藏副视图", onPressed: () => _secondaryState = SecondaryState.NONE),
        button("切换中英文", onPressed: () => isChinese = !isChinese),
      ],
    );
  }

  Widget button(String text, {VoidCallback onPressed}) {
    return FlatButton(
        onPressed: () {
          if (onPressed != null) {
            onPressed();
            setState(() {});
          }
        },
        child: Text("$text"),
        color: Colors.blue);
  }

  void getData(String period) {
    Future<String> future = getIPAddress('$period');
    future.then((result) {
      Map parseJson = json.decode(result);
      List list = parseJson['data'];
      datas = list.map((item) => KLineEntity.fromJson(item)).toList().reversed.toList().cast<KLineEntity>();
      DataUtil.calculate(datas);
      showLoading = false;
      setState(() {});
    }).catchError((_) {
      showLoading = false;
      setState(() {});
      print('获取数据失败');
    });
  }

  //获取火币数据,需要翻墙
  Future<String> getIPAddress(String period) async {
    var url = 'https://api.huobi.br.com/market/history/kline?period=${period ?? '1day'}&size=300&symbol=btcusdt';
    String result;
    var response = await http.get(url);
    if (response.statusCode == 200) {
      result = response.body;
    } else {
      print('Failed getting IP address');
    }
    return result;
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  k_chart: ^0.1.1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:k_chart/chart_style.dart';
import 'package:k_chart/depth_chart.dart';
import 'package:k_chart/entity/candle_entity.dart';
import 'package:k_chart/entity/depth_entity.dart';
import 'package:k_chart/entity/info_window_entity.dart';
import 'package:k_chart/entity/kdj_entity.dart';
import 'package:k_chart/entity/k_entity.dart';
import 'package:k_chart/entity/k_line_entity.dart';
import 'package:k_chart/entity/macd_entity.dart';
import 'package:k_chart/entity/rsi_entity.dart';
import 'package:k_chart/entity/rw_entity.dart';
import 'package:k_chart/entity/volume_entity.dart';
import 'package:k_chart/flutter_k_chart.dart';
import 'package:k_chart/k_chart_widget.dart';
import 'package:k_chart/renderer/base_chart_painter.dart';
import 'package:k_chart/renderer/base_chart_renderer.dart';
import 'package:k_chart/renderer/chart_painter.dart';
import 'package:k_chart/renderer/main_renderer.dart';
import 'package:k_chart/renderer/secondary_renderer.dart';
import 'package:k_chart/renderer/vol_renderer.dart';
import 'package:k_chart/utils/data_util.dart';
import 'package:k_chart/utils/date_format_util.dart';
import 'package:k_chart/utils/number_util.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
53
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
80
Overall:
Weighted score of the above. [more]
72
Learn more about scoring.

We analyzed this package on Apr 6, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Health suggestions

Format lib/entity/info_window_entity.dart.

Run flutter format to format lib/entity/info_window_entity.dart.

Format lib/entity/k_entity.dart.

Run flutter format to format lib/entity/k_entity.dart.

Format lib/entity/rw_entity.dart.

Run flutter format to format lib/entity/rw_entity.dart.

Fix additional 8 files with analysis or formatting issues.

Additional issues in the following files:

  • lib/renderer/base_chart_painter.dart (Run flutter format to format lib/renderer/base_chart_painter.dart.)
  • lib/renderer/base_chart_renderer.dart (Run flutter format to format lib/renderer/base_chart_renderer.dart.)
  • lib/renderer/chart_painter.dart (Run flutter format to format lib/renderer/chart_painter.dart.)
  • lib/renderer/main_renderer.dart (Run flutter format to format lib/renderer/main_renderer.dart.)
  • lib/renderer/secondary_renderer.dart (Run flutter format to format lib/renderer/secondary_renderer.dart.)
  • lib/renderer/vol_renderer.dart (Run flutter format to format lib/renderer/vol_renderer.dart.)
  • lib/utils/data_util.dart (Run flutter format to format lib/utils/data_util.dart.)
  • lib/utils/date_format_util.dart (Run flutter format to format lib/utils/date_format_util.dart.)

Maintenance suggestions

The package description is too short. (-20 points)

Add more detail to the description field of pubspec.yaml. Use 60 to 180 characters to describe the package, what it does, and its target use case.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.2.2 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test