输入/搜索内容
内置函数
Global
Log
Log
LogProfit
LogProfitReset
LogStatus
EnableLog
Chart
KLineChart
LogReset
LogVacuum
console.log
console.error
Market
Trade
Account
Futures
Threads
TA
Talib
OS
结构体
内置变量

用于自定义绘制图表的函数。

Chart(options)

示例

  • 多图表绘制配置:

    • extension.layout属性
      若将该属性设置为 "single",则图表不会叠加显示(即不以分页标签的方式显示),而是独立平铺显示。
    • extension.height属性
      该属性用于设置图表的高度,取值可以为数值类型,也可以采用 "300px" 的形式设置。
    • extension.col属性
      该属性用于设置图表的宽度。页面宽度共划分为 12 个单元,设置为 8 即表示该图表占用 8 个单元的宽度。
    javascript
    function main() { var cfgA = { extension: { layout: 'single', // 不参与分组,单独显示,默认为分组 'group' height: 300, // 指定高度 }, title: { text: '盘口图表' }, xAxis: { type: 'datetime' }, series: [{ name: '买一', data: [], }, { name: '卖一', data: [], }] } var cfgB = { title: { text: '差价图' }, xAxis: { type: 'datetime' }, series: [{ name: '差价', type: 'column', data: [], }] } var cfgC = { __isStock: false, title: { text: '饼图' }, series: [{ type: 'pie', name: 'one', data: [ ["A", 25], ["B", 25], ["C", 25], ["D", 25], ] // 指定初始数据后无需使用 add 函数更新,直接更改图表配置即可更新序列 }] }; var cfgD = { extension: { layout: 'single', col: 8, // 指定宽度所占的单元值,总值为 12 height: '300px', }, title: { text: '盘口图表' }, xAxis: { type: 'datetime' }, series: [{ name: '买一', data: [], }, { name: '卖一', data: [], }] } var cfgE = { __isStock: false, extension: { layout: 'single', col: 4, height: '300px', }, title: { text: '饼图2' }, series: [{ type: 'pie', name: 'one', data: [ ["A", 25], ["B", 25], ["C", 25], ["D", 25], ] }] }; var chart = Chart([cfgA, cfgB, cfgC, cfgD, cfgE]); chart.reset() // 为饼图追加一个数据点,add 只能更新通过 add 方式添加的数据点,内置的数据点无法后期更新 chart.add(3, { name: "ZZ", y: Math.random() * 100 }); while (true) { Sleep(1000) exchange.SetContractType("rb888") var ticker = exchange.GetTicker() if (!ticker) { continue; } var diff = ticker.Sell - ticker.Buy cfgA.subtitle = { text: '买一 ' + ticker.Buy + ', 卖一 ' + ticker.Sell, }; cfgB.subtitle = { text: '价差 ' + diff, }; chart.add([0, [new Date().getTime(), ticker.Buy]]); chart.add([1, [new Date().getTime(), ticker.Sell]]); // 相当于更新第二个图表的第一个数据序列 chart.add([2, [new Date().getTime(), diff]]); chart.add(4, [new Date().getTime(), ticker.Buy]); chart.add(5, [new Date().getTime(), ticker.Buy]); cfgC.series[0].data[0][1] = Math.random() * 100; cfgE.series[0].data[0][1] = Math.random() * 100; // update 实际上等于重置图表的配置 chart.update([cfgA, cfgB, cfgC, cfgD, cfgE]); } }
    python
    import random import time def main(): cfgA = { "extension" : { "layout" : "single", "height" : 300, "col" : 8 }, "title" : { "text" : "盘口图表" }, "xAxis" : { "type" : "datetime" }, "series" : [{ "name" : "买一", "data" : [] }, { "name" : "卖一", "data" : [] }] } cfgB = { "title" : { "text" : "差价图" }, "xAxis" : { "type" : "datetime", }, "series" : [{ "name" : "差价", "type" : "column", "data" : [] }] } cfgC = { "__isStock" : False, "title" : { "text" : "饼图" }, "series" : [{ "type" : "pie", "name" : "one", "data" : [ ["A", 25], ["B", 25], ["C", 25], ["D", 25], ] }] } cfgD = { "extension" : { "layout" : "single", "col" : 8, "height" : "300px" }, "title" : { "text" : "盘口图表" }, "series" : [{ "name" : "买一", "data" : [] }, { "name" : "卖一", "data" : [] }] } cfgE = { "__isStock" : False, "extension" : { "layout" : "single", "col" : 4, "height" : "300px" }, "title" : { "text" : "饼图2" }, "series" : [{ "type" : "pie", "name" : "one", "data" : [ ["A", 25], ["B", 25], ["C", 25], ["D", 25] ] }] } chart = Chart([cfgA, cfgB, cfgC, cfgD, cfgE]) chart.reset() chart.add(3, { "name" : "ZZ", "y" : random.random() * 100 }) while True: Sleep(1000) exchange.SetContractType("rb888") ticker = exchange.GetTicker() if not ticker : continue diff = ticker["Sell"] - ticker["Buy"] cfgA["subtitle"] = { "text" : "买一" + str(ticker["Buy"]) + "卖一" + str(ticker["Sell"]) } cfgB["subtitle"] = { "text" : "价差 " + str(diff) } chart.add(0, [time.time() * 1000, ticker["Buy"]]) chart.add(1, [time.time() * 1000, ticker["Sell"]]) chart.add(2, [time.time() * 1000, diff]) chart.add(4, [time.time() * 1000, ticker["Buy"]]) chart.add(5, [time.time() * 1000, ticker["Buy"]]) cfgC["series"][0]["data"][0][1] = random.random() * 100 cfgE["series"][0]["data"][0][1] = random.random() * 100
    rust
    fn main() { // Rust 中图表配置为 JSON 字符串,可变部分使用占位符表示,更新时替换占位符重新构建配置 let cfg_a_tpl = r#"{ "extension": { "layout": "single", "height": 300, "col": 8 }, "title": {"text": "盘口图表"}, "subtitle": {"text": "__SUBTITLE__"}, "xAxis": {"type": "datetime"}, "series": [{"name": "买一", "data": []}, {"name": "卖一", "data": []}] }"#; let cfg_b_tpl = r#"{ "title": {"text": "差价图"}, "subtitle": {"text": "__SUBTITLE__"}, "xAxis": {"type": "datetime"}, "series": [{"name": "差价", "type": "column", "data": []}] }"#; let cfg_c_tpl = r#"{ "__isStock": false, "title": {"text": "饼图"}, "series": [{ "type": "pie", "name": "one", "data": [["A", __Y__], ["B", 25], ["C", 25], ["D", 25]] }] }"#; let cfg_d = r#"{ "extension": { "layout": "single", "col": 8, "height": "300px" }, "title": {"text": "盘口图表"}, "xAxis": {"type": "datetime"}, "series": [{"name": "买一", "data": []}, {"name": "卖一", "data": []}] }"#; let cfg_e_tpl = r#"{ "__isStock": false, "extension": { "layout": "single", "col": 4, "height": "300px" }, "title": {"text": "饼图2"}, "series": [{ "type": "pie", "name": "one", "data": [["A", __Y__], ["B", 25], ["C", 25], ["D", 25]] }] }"#; let cfg_a = cfg_a_tpl.replace("__SUBTITLE__", ""); let cfg_b = cfg_b_tpl.replace("__SUBTITLE__", ""); let cfg_c = cfg_c_tpl.replace("__Y__", "25"); let cfg_e = cfg_e_tpl.replace("__Y__", "25"); let chart = Chart::new(&format!("[{},{},{},{},{}]", cfg_a, cfg_b, cfg_c, cfg_d, cfg_e)); chart.reset(0); // 为饼图追加一个数据点,add 只能更新通过 add 方式添加的数据点,内置的数据点无法后期更新 let y = (UnixNano() % 100) as f64; // 用时间戳模拟随机数 chart.add(3, &format!(r#"{{"name": "ZZ", "y": {}}}"#, y), -1); loop { Sleep(1000); let _ = exchange.SetContractType("rb888"); let ticker = match exchange.GetTicker(None) { Ok(t) => t, Err(_) => continue, }; let diff = ticker.Sell - ticker.Buy; let cfg_a = cfg_a_tpl.replace("__SUBTITLE__", &format!("买一 {}, 卖一 {}", ticker.Buy, ticker.Sell)); let cfg_b = cfg_b_tpl.replace("__SUBTITLE__", &format!("价差 {}", diff)); let now = Unix() * 1000; chart.add(0, &format!("[{}, {}]", now, ticker.Buy), -1); chart.add(1, &format!("[{}, {}]", now, ticker.Sell), -1); // 相当于更新第二个图表的第一个数据序列 chart.add(2, &format!("[{}, {}]", now, diff), -1); chart.add(4, &format!("[{}, {}]", now, ticker.Buy), -1); chart.add(5, &format!("[{}, {}]", now, ticker.Buy), -1); let cfg_c = cfg_c_tpl.replace("__Y__", &format!("{}", (UnixNano() % 100) as f64)); let cfg_e = cfg_e_tpl.replace("__Y__", &format!("{}", (UnixNano() % 100) as f64)); // update 实际上等于重置图表的配置 chart.update(&format!("[{},{},{},{},{}]", cfg_a, cfg_b, cfg_c, cfg_d, cfg_e)); } }
  • 简单的绘图示例:

    javascript
    // 在 JavaScript 中,chart 是一个对象。在调用 Chart 函数之前,我们需要先声明一个用于配置图表的对象变量 chart var chart = { // 该字段标记图表是否为普通图表,感兴趣的话可以改成 false 运行看看 __isStock: true, // 工具提示 tooltip: {xDateFormat: '%Y-%m-%d %H:%M:%S, %A'}, // 标题 title : { text : '差价分析图'}, // 范围选择器 rangeSelector: { buttons: [{type: 'hour',count: 1, text: '1h'}, {type: 'hour',count: 3, text: '3h'}, {type: 'hour', count: 8, text: '8h'}, {type: 'all',text: 'All'}], selected: 0, inputEnabled: false }, // 横坐标轴(即 x 轴),当前设置的类型为时间 xAxis: { type: 'datetime'}, // 纵坐标轴(即 y 轴),默认数值随数据大小自动调整 yAxis : { // 标题 title: {text: '差价'}, // 是否启用右侧纵轴 opposite: false }, // 数据系列,该属性保存各个数据系列(折线、K 线图、标签等) series : [ // 索引为 0,data 数组内存放的是该索引系列的数据 {name : "line1", id : "线1,buy1Price", data : []}, // 索引为 1,设置了 dashStyle: 'shortdash',即设置为虚线 {name : "line2", id : "线2,lastPrice", dashStyle : 'shortdash', data : []} ] } function main(){ // 调用 Chart 函数,初始化图表 var ObjChart = Chart(chart) // 清空 ObjChart.reset() while(true){ // 判断是否成功连接期货公司前置机。股票、证券无需使用 exchange.IO("status") 判断连接状态 if (!exchange.IO("status")) { Sleep(1000) continue } exchange.SetContractType("rb888") // 获取本次轮询的时间戳(毫秒级),用于确定写入图表的 X 轴位置 var nowTime = new Date().getTime() // 获取行情数据 var ticker = _C(exchange.GetTicker) // 从行情数据的返回值中取得买一价 var buy1Price = ticker.Buy // 取得最新成交价,为了使两条线不重合,这里加 1 var lastPrice = ticker.Last + 1 // 以时间戳作为 X 值、买一价作为 Y 值,传入索引 0 的数据序列 ObjChart.add(0, [nowTime, buy1Price]) // 同上 ObjChart.add(1, [nowTime, lastPrice]) Sleep(2000) } }
    python
    import time chart = { "__isStock" : True, "tooltip" : {"xDateFormat" : "%Y-%m-%d %H:%M:%S, %A"}, "title" : {"text" : "差价分析图"}, "rangeSelector" : { "buttons" : [{"type": "count", "count": 1, "text": "1h"}, {"type": "hour", "count": 3, "text": "3h"}, {"type": "hour", "count": 8, "text": "8h"}, {"type": "all", "text": "All"}], "selected": 0, "inputEnabled": False }, "xAxis": {"type": "datetime"}, "yAxis": { "title": {"text": "差价"}, "opposite": False }, "series": [{ "name": "line1", "id": "线1,buy1Price", "data": [] }, { "name": "line2", "id": "线2,lastPrice", "dashStyle": "shortdash", "data": [] }] } def main(): ObjChart = Chart(chart) ObjChart.reset() while True: if not exchange.IO("status"): Sleep(1000) continue exchange.SetContractType("rb888") nowTime = time.time() * 1000 ticker = exchange.GetTicker() buy1Price = ticker["Buy"] lastPrice = ticker["Last"] + 1 ObjChart.add(0, [nowTime, buy1Price]) ObjChart.add(1, [nowTime, lastPrice]) Sleep(2000)
    rust
    fn main() { // 在 Rust 中图表配置为 JSON 字符串,在使用 Chart::new 之前先定义配置内容 let chart = r#"{ "__isStock": true, "tooltip": {"xDateFormat": "%Y-%m-%d %H:%M:%S, %A"}, "title": {"text": "差价分析图"}, "rangeSelector": { "buttons": [{"type": "hour", "count": 1, "text": "1h"}, {"type": "hour", "count": 3, "text": "3h"}, {"type": "hour", "count": 8, "text": "8h"}, {"type": "all", "text": "All"}], "selected": 0, "inputEnabled": false }, "xAxis": {"type": "datetime"}, "yAxis": { "title": {"text": "差价"}, "opposite": false }, "series": [{ "name": "line1", "id": "线1,buy1Price", "data": [] }, { "name": "line2", "id": "线2,lastPrice", "dashStyle": "shortdash", "data": [] }] }"#; // 调用 Chart::new 函数,初始化图表 let obj_chart = Chart::new(chart); // 清空 obj_chart.reset(0); loop { // 判断是否成功连接期货公司前置机。股票、证券无需使用 exchange.IO("status") 判断连接状态 if !exchange.IO("status").is_ok_and(|v| v.as_i64() == Some(1)) { Sleep(1000); continue; } let _ = exchange.SetContractType("rb888"); // 获取本次轮询的时间戳(毫秒级),用于确定写入图表的 X 轴位置 let now_time = Unix() * 1000; // 获取行情数据 let ticker = _C!(exchange.GetTicker(None)); // 从行情数据的返回值中取得买一价 let buy1_price = ticker.Buy; // 取得最新成交价,为了使两条线不重合,这里加 1 let last_price = ticker.Last + 1.0; // 以时间戳作为 X 值、买一价作为 Y 值,传入索引 0 的数据序列 obj_chart.add(0, &format!("[{}, {}]", now_time, buy1_price), -1); // 同上 obj_chart.add(1, &format!("[{}, {}]", now_time, last_price), -1); Sleep(2000); } }
  • 三角函数曲线绘图示例:

    javascript
    // 用于初始化图表的配置对象 var chart = { // 图表标题 title: {text: "line数值触发 plotLines 值"}, // Y 轴相关设置 yAxis: { // 垂直于 Y 轴的水平线,用作触发线;这是一个结构数组,可以设置多条触发线 plotLines: [{ // 触发线的值,设置为多少,该触发线就显示在对应的数值位置 value: 0, // 设置触发线的颜色 color: 'red', // 宽度 width: 2, // 显示的标签 label: { // 标签文本 text: '触发值', // 标签位置居中 align: 'center' } }] }, // X 轴相关设置,此处将类型设置为时间轴 xAxis: {type: "datetime"}, series: [ {name: "sin", type: "spline", data: []}, // 这是较为重要的数据系列,可以设置多个数据系列,通过数组索引进行控制 {name: "cos", type: "spline", data: []} ] } function main(){ // 圆周率 var pi = 3.1415926535897 // 用于记录时间戳的变量 var time = 0 // 角度 var angle = 0 // 坐标 y 值,用于接收正弦值或余弦值 var y = 0 // 调用 API 接口,使用 chart 对象初始化图表 var objChart = Chart(chart) // 初始化时清空图表 objChart.reset() // 将触发线的值设置为 1 chart.yAxis.plotLines[0].value = 1 // 循环 while(true){ // 获取当前时刻的时间戳 time = new Date().getTime() // 每 5 秒将角度 angle 增加 5 度,并计算正弦值 y = Math.sin(angle * 2 * pi / 360) // 将计算得到的 y 值写入图表中对应索引的数据系列;add 函数的第一个参数为指定的数据系列索引 objChart.add(0, [time, y]) // 计算余弦值 y = Math.cos(angle * 2 * pi / 360) objChart.add(1, [time, y]) // 角度增加 5 度 angle += 5 // 暂停 5 秒,避免绘图过于频繁、数据增长过快 Sleep(5000) } }
    python
    import math import time chart = { "title": {"text": "line数值触发 plotLines 值"}, "yAxis": { "plotLines": [{ "value": 0, "color": "red", "width": 2, "label": { "text": "触发值", "align": "center" } }] }, "xAxis": {"type": "datetime"}, "series": [{"name": "sin", "type": "spline", "data": []}, {"name": "cos", "type": "spline", "data": []}] } def main(): pi = 3.1415926535897 ts = 0 angle = 0 y = 0 objChart = Chart(chart) objChart.reset() chart["yAxis"]["plotLines"][0]["value"] = 1 while True: ts = time.time() * 1000 y = math.sin(angle * 2 * pi / 360) objChart.add(0, [ts, y]) y = math.cos(angle * 2 * pi / 360) objChart.add(1, [ts, y]) angle += 5 Sleep(5000)
    rust
    fn main() { // 用于初始化图表的 JSON 配置字符串,触发线的值在配置中直接设置为 1 let chart = r#"{ "title": {"text": "line数值触发 plotLines 值"}, "yAxis": { "plotLines": [{ "value": 1, "color": "red", "width": 2, "label": { "text": "触发值", "align": "center" } }] }, "xAxis": {"type": "datetime"}, "series": [{"name": "sin", "type": "spline", "data": []}, {"name": "cos", "type": "spline", "data": []}] }"#; // 圆周率 let pi = 3.1415926535897_f64; // 角度 let mut angle = 0.0_f64; // 调用 API 接口,使用 chart 配置初始化图表 let obj_chart = Chart::new(chart); // 初始化时清空图表 obj_chart.reset(0); // 循环 loop { // 获取当前时刻的毫秒时间戳 let ts = Unix() * 1000; // 每 5 秒将角度 angle 增加 5 度,并计算正弦值 let mut y = (angle * 2.0 * pi / 360.0).sin(); // 将计算得到的 y 值写入图表中对应索引的数据系列;add 函数的第一个参数为指定的数据系列索引 obj_chart.add(0, &format!("[{}, {}]", ts, y), -1); // 计算余弦值 y = (angle * 2.0 * pi / 360.0).cos(); obj_chart.add(1, &format!("[{}, {}]", ts, y), -1); // 角度增加 5 度 angle += 5.0; // 暂停 5 秒,避免绘图过于频繁、数据增长过快 Sleep(5000); } }
  • 使用混合图表的复杂示例:

    javascript
    var chartCfg = { subtitle: { text: "subtitle", }, yAxis: [{ height: "40%", lineWidth: 2, title: { text: 'PnL', }, tickPixelInterval: 20, minorGridLineWidth: 1, minorTickWidth: 0, opposite: true, labels: { align: "right", x: -3, } }, { title: { text: 'Profit', }, top: "42%", height: "18%", offset: 0, lineWidth: 2 }, { title: { text: 'Vol', }, top: '62%', height: '18%', offset: 0, lineWidth: 2 }, { title: { text: 'Asset', }, top: '82%', height: '18%', offset: 0, lineWidth: 2 }], series: [{ name: 'PnL', data: [], id: 'primary', tooltip: { xDateFormat: '%Y-%m-%d %H:%M:%S' }, yAxis: 0 }, { type: 'column', lineWidth: 2, name: 'Profit', data: [], yAxis: 1, }, { type: 'column', name: 'Trade', data: [], yAxis: 2 }, { type: 'area', step: true, lineWidth: 0, name: 'Long', data: [], yAxis: 2 }, { type: 'area', step: true, lineWidth: 0, name: 'Short', data: [], yAxis: 2 }, { type: 'line', step: true, color: '#5b4b00', name: 'Asset', data: [], yAxis: 3 }, { type: 'pie', innerSize: '70%', name: 'Random', data: [], center: ['3%', '6%'], size: '15%', dataLabels: { enabled: false }, startAngle: -90, endAngle: 90, }], }; function main() { let c = Chart(chartCfg); let preTicker = null; while (true) { if (!exchange.IO("status")) { Sleep(1000) continue } exchange.SetContractType("rb888") let t = exchange.GetTicker(); c.add(0, [t.Time, t.Last]); // PnL c.add(1, [t.Time, preTicker ? t.Last - preTicker.Last : 0]); // profit let r = Math.random(); var pos = parseInt(t.Time/86400); c.add(2, [t.Time, pos/2]); // Vol c.add(3, [t.Time, r > 0.8 ? pos : null]); // Long c.add(4, [t.Time, r < 0.8 ? -pos : null]); // Short c.add(5, [t.Time, Math.random() * 100]); // Asset // update pie chartCfg.series[chartCfg.series.length-1].data = [ ["A", Math.random()*100], ["B", Math.random()*100], ]; c.update(chartCfg) preTicker = t; } }
    python
    import random chartCfg = { "subtitle": { "text": "subtitle" }, "yAxis": [{ "height": "40%", "lineWidth": 2, "title": { "text": 'PnL' }, "tickPixelInterval": 20, "minorGridLineWidth": 1, "minorTickWidth": 0, "opposite": True, "labels": { "align": "right", "x": -3 } }, { "title": { "text": 'Profit' }, "top": "42%", "height": "18%", "offset": 0, "lineWidth": 2 }, { "title": { "text": 'Vol' }, "top": '62%', "height": '18%', "offset": 0, "lineWidth": 2 }, { "title": { "text": 'Asset' }, "top": '82%', "height": '18%', "offset": 0, "lineWidth": 2 }], "series": [{ "name": 'PnL', "data": [], "id": 'primary', "tooltip": { "xDateFormat": '%Y-%m-%d %H:%M:%S' }, "yAxis": 0 }, { "type": 'column', "lineWidth": 2, "name": 'Profit', "data": [], "yAxis": 1 }, { "type": 'column', "name": 'Trade', "data": [], "yAxis": 2 }, { "type": 'area', "step": True, "lineWidth": 0, "name": 'Long', "data": [], "yAxis": 2 }, { "type": 'area', "step": True, "lineWidth": 0, "name": 'Short', "data": [], "yAxis": 2 }, { "type": 'line', "step": True, "color": '#5b4b00', "name": 'Asset', "data": [], "yAxis": 3 }, { "type": 'pie', "innerSize": '70%', "name": 'Random', "data": [], "center": ['3%', '6%'], "size": '15%', "dataLabels": { "enabled": False }, "startAngle": -90, "endAngle": 90 }] } def main(): c = Chart(chartCfg) preTicker = None while True: if not exchange.IO("status"): Sleep(1000) continue exchange.SetContractType("rb888") t = exchange.GetTicker() c.add(0, [t["Time"], t["Last"]]) profit = t["Last"] - preTicker["Last"] if preTicker else 0 c.add(1, [t["Time"], profit]) r = random.random() pos = t["Time"] / 86400 c.add(2, [t["Time"], pos / 2]) long = pos if r > 0.8 else None c.add(3, [t["Time"], long]) short = -pos if r < 0.8 else None c.add(4, [t["Time"], short]) c.add(5, [t["Time"], random.random() * 100]) # update pie chartCfg["series"][len(chartCfg["series"]) - 1]["data"] = [ ["A", random.random() * 100], ["B", random.random() * 100] ] c.update(chartCfg) preTicker = t
    rust
    fn main() { // 在 Rust 中,图表配置为 JSON 字符串;饼图数据使用占位符 __PIE_DATA__ 表示,更新时替换该占位符后重建配置 let chart_cfg_tpl = r##"{ "subtitle": {"text": "subtitle"}, "yAxis": [{ "height": "40%", "lineWidth": 2, "title": {"text": "PnL"}, "tickPixelInterval": 20, "minorGridLineWidth": 1, "minorTickWidth": 0, "opposite": true, "labels": {"align": "right", "x": -3} }, { "title": {"text": "Profit"}, "top": "42%", "height": "18%", "offset": 0, "lineWidth": 2 }, { "title": {"text": "Vol"}, "top": "62%", "height": "18%", "offset": 0, "lineWidth": 2 }, { "title": {"text": "Asset"}, "top": "82%", "height": "18%", "offset": 0, "lineWidth": 2 }], "series": [{ "name": "PnL", "data": [], "id": "primary", "tooltip": {"xDateFormat": "%Y-%m-%d %H:%M:%S"}, "yAxis": 0 }, { "type": "column", "lineWidth": 2, "name": "Profit", "data": [], "yAxis": 1 }, { "type": "column", "name": "Trade", "data": [], "yAxis": 2 }, { "type": "area", "step": true, "lineWidth": 0, "name": "Long", "data": [], "yAxis": 2 }, { "type": "area", "step": true, "lineWidth": 0, "name": "Short", "data": [], "yAxis": 2 }, { "type": "line", "step": true, "color": "#5b4b00", "name": "Asset", "data": [], "yAxis": 3 }, { "type": "pie", "innerSize": "70%", "name": "Random", "data": __PIE_DATA__, "center": ["3%", "6%"], "size": "15%", "dataLabels": {"enabled": false}, "startAngle": -90, "endAngle": 90 }] }"##; let c = Chart::new(&chart_cfg_tpl.replace("__PIE_DATA__", "[]")); let mut pre_ticker: Option<Ticker> = None; loop { if !exchange.IO("status").is_ok_and(|v| v.as_i64() == Some(1)) { Sleep(1000); continue; } let _ = exchange.SetContractType("rb888"); let t = exchange.GetTicker(None).unwrap(); c.add(0, &format!("[{}, {}]", t.Time, t.Last), -1); // PnL let profit = if let Some(p) = &pre_ticker { t.Last - p.Last } else { 0.0 }; c.add(1, &format!("[{}, {}]", t.Time, profit), -1); // profit let r = (UnixNano() % 100) as f64 / 100.0; // 使用时间戳模拟随机数 let pos = (t.Time / 86400) as f64; c.add(2, &format!("[{}, {}]", t.Time, pos / 2.0), -1); // Vol c.add(3, &format!("[{}, {}]", t.Time, if r > 0.8 { pos.to_string() } else { "null".to_string() }), -1); // Long c.add(4, &format!("[{}, {}]", t.Time, if r < 0.8 { (-pos).to_string() } else { "null".to_string() }), -1); // Short c.add(5, &format!("[{}, {}]", t.Time, (UnixNano() % 10000) as f64 / 100.0), -1); // Asset // update pie let pie = format!(r#"[["A", {}], ["B", {}]]"#, (UnixNano() % 100) as f64, (UnixNano() % 100) as f64); c.update(&chart_cfg_tpl.replace("__PIE_DATA__", &pie)); pre_ticker = Some(t); } }
  • 图表中 pie 类型的图表没有时间轴,更新数据时需要直接更新图表配置。例如上述范例中的代码,更新数据后调用 c.update(chartCfg) 更新图表,如下所示:

    javascript
    // update pie chartCfg.series[chartCfg.series.length-1].data = [ ["A", Math.random()*100], ["B", Math.random()*100], ]; c.update(chartCfg)
    python
    # update pie chartCfg["series"][len(chartCfg["series"]) - 1]["data"] = [ ["A", random.random() * 100], ["B", random.random() * 100] ] c.update(chartCfg)
    rust
    // update pie // Rust 中图表配置为 JSON 字符串,重建包含新数据的配置后调用 update 更新图表 let pie = format!(r#"[["A", {}], ["B", {}]]"#, (UnixNano() % 100) as f64, (UnixNano() % 100) as f64); c.update(&chart_cfg_tpl.replace("__PIE_DATA__", &pie));

返回值

类型描述

object

图表对象。

参数

名称类型必填描述

options

object / object数组

是

图表配置:可以JSON序列化的Highcharts.StockChart参数(见HighStocks图表库),另加__isStock属性:为真值(默认)时使用Highstocks图表,为假值(例如false)时使用普通的Highcharts图表。

参考

备注

Chart()函数返回一个图表对象,该对象包含4个方法:add()、reset()、update()、del()。

  • 1、update()方法:
    update()方法用于更新图表配置信息,其参数为Chart图表配置对象(JSON)。
  • 2、del()方法:
    del()方法可根据传入的series参数,删除指定索引的数据系列。
  • 3、add()方法:
    add()方法用于向图表中写入数据,参数依次为:
    • series:用于设置数据系列索引,为整数。
    • data:用于设置写入的具体数据,为一个数组。
    • index(可选):用于设置数据索引,为整数,指定要修改数据的具体索引位置,支持使用负数表示,设置为-1表示数据集的最后一个数据。
      例如画线时,若要修改线上最后一个点的数据:chart.add(0, [1574993606000, 13.5], -1),即更改图表series[0].data中倒数第一个点的数据。不设置index参数则表示向当前数据系列(series)末尾添加数据。
  • 4、reset()方法:
    reset()方法用于清空图表数据,该方法可传入一个参数remain,用于指定保留数据的条数。不传入remain参数则表示清除全部数据。