lightweight-charts-onesixth v2.8.1 → v3.1.1 更新总览

lightweight-charts-onesixth v2.8.1 → v3.1.1 更新总览

Python 调用 TradingView 级别交互式图表,不写一行 JS。


🚀 新功能总览

过去 22 个版本(v2.8.1 → v3.1.1)新增了以下核心能力:

类别 新增内容
新 Series 类型 AreaSeries(面积图)、OHLCBarSeries(美国线)、BaselineSeries(基准线)
绘图系统 Pane Primitive 架构、ToolBox on_change 多回调、跨 Pane 绘图
图表 API TimeScaleApi(14 方法)、PriceScaleApi(6 方法)、chart.show(wait=N)
数据模型 chart_model 子包(声明式纯数据模型,与渲染层解耦)
Volume/OI 独立化升级,一等公民
CandleSeries 独立 K 线系列,任意 Pane 绘制
同步机制 sync_id 组同步
时间轴 秒级时间显示支持

📊 新增 Series 类型

AreaSeries --- 面积图

折线 + 渐变填充,适合展示 MACD、成交量差等指标。

python 复制代码
# 创建
area = chart.create_area(
    name="MACD",
    color="#FF9800",
    width=2,
    top_color="#FF9800",      # 渐变上色
    bottom_color="#FF980000",  # 渐变下色(带透明度)
    relative_gradient=True,     # 相对渐变(沿图表高度)
    invert_filled_area=False,   # 是否反转填充区域
)

# 数据输入 --- 统一 time + value 列
area.set(df)

# 更新
area.update_bars(df)
area.update_ticks(df)

OHLCBarSeries --- 美国线

传统 OHLC 柱状图,open 左 close 右,适合习惯美线风格的交易者。

python 复制代码
# 创建
ohlc = chart.create_ohlc_bar(
    name="K线",
    up_color="#26a69a",
    down_color="#ef5350",
    open_visible=True,    # 是否显示左侧 open 横线
    thin_bars=False,      # 细线模式
)

# 数据输入 --- 与 Candle 完全一致(time + open + high + low + close)
ohlc.set(df)

# 样式配置 --- 注意用 bar_style() 不是 candle_style()
ohlc.bar_style(up_color="#26a69a", down_color="#ef5350")
# ohlc.candle_style()  ← 会抛 AttributeError,提示用 bar_style()

BaselineSeries --- 基准线

以基准值(如 0 轴)为界上下分色,适合展示乖离率、RSI 等。

python 复制代码
# 创建
bsl = chart.create_baseline(
    name="乖离率",
    base_value=0,                    # 基准值
    top_fill_color1="#26a69a80",     # 线上填充色
    top_fill_color2="#26a69a40",
    top_line_color="#26a69a",        # 线上线条色
    bottom_fill_color1="#ef535080",  # 线下填充色
    bottom_fill_color2="#ef535040",
    bottom_line_color="#ef5350",     # 线下线条色
    line_width=2,
    relative_gradient=True,
)

# 数据输入 --- time + value
bsl.set(df)

🎨 绘图系统(Drawing/ToolBox)

架构升级:ISeriesPrimitive → IPanePrimitive

:画线附着到 Series,依赖 Series 数据状态,空 Series 不能画线。

:画线直接附着到 Pane,不依赖任何 Series 数据,跨 Pane 稳定。

python 复制代码
# 5 种画线类型
chart.horizontal_line(price=3600, color="#FF9800", text="阻力位", pane_index=0)
chart.vertical_line(time="2022-02-01", color="#26a69a")
chart.trend_line(start=("2022-02-01", 3500), end=("2022-02-03", 3800))
chart.ray_line(start=("2022-02-01", 3400), angle=45)
chart.box(top_left=("2022-02-01", 3900), bottom_right=("2022-02-03", 3400))

ToolBox 回调系统

save_drawings_under(widget) 单回调,绑定持久化控件。

on_change += func 支持多回调注册/卸载。

python 复制代码
# 新方式
def on_drawings_changed(drawings: list[DrawingInfo]):
    save_to_db(drawings)  # 自行实现持久化

chart.toolbox.on_change += on_drawings_changed

# 卸载
chart.toolbox.on_change -= on_drawings_changed

# DrawingInfo 包含完整信息
for d in chart.toolbox.drawings_list:
    print(d.id, d.type, d.points, d.pane_index, d.options)

迁移指南

旧 API 新 API
toolbox.save_drawings_under(w) on_change 回调自行实现持久化
toolbox.load_drawings(tag) on_change 回调自行实现
toolbox.import_drawings(path) on_change 回调自行实现
toolbox.export_drawings(path) on_change 回调自行实现
内置 Ctrl+Z 撤销 已移除,需自行实现

⏰ 时间轴 / 价格轴 API

时间轴 --- TimeScaleApi

:只有 chart.fit()chart.set_visible_range() 两个方法。

chart.time_scale_api() 返回 TimeScaleApi 实例,覆盖 14 个方法。

python 复制代码
api = chart.time_scale_api()

# 滚动控制
api.scroll_position()              # 获取当前滚动位置
api.scroll_to_position(0.5)       # 滚动到 50% 位置
api.scroll_to_real_time()          # 滚动到实时数据

# 范围管理
api.get_visible_range()            # 获取可见时间范围
api.set_visible_range({'from': "2022-02-01", 'to': "2022-02-03"})
api.get_visible_logical_range()
api.set_visible_logical_range({'from': 0, 'to': 100})

# 视图控制
api.fit_content()                  # 自适应所有数据

# 事件订阅
api.subscribe_visible_logical_range_change(callback)
api.subscribe_visible_time_range_change(callback)
api.subscribe_size_change(callback)

# 尺寸获取
api.width()

价格轴 --- PriceScaleApi

chart.price_scale_api(scale_id) 支持左右价格轴。

python 复制代码
# 右侧价格轴
api = chart.price_scale_api('right')
api.set_auto_scale(True)
api.get_visible_range()
api.set_visible_range({'from': 3000, 'to': 4000})
api.apply_options(scale_margin_top=0.3, scale_margin_bottom=0.2)
api.width()

📐 Volume / OpenInterest 独立化

:Volume 和 OI 是 Candle 的附属品,通过 candle.attach_volume(df) 挂载,生命周期绑定。

python 复制代码
# ❌ 旧方式(已移除)
candle.attach_volume(df)               # 已移除
candle.attach_open_interest(df)         # 已移除
candle.volume_config(color="#26a69a")   # 已移除
candle.open_interest_config(color="#FF9800")  # 已移除

:Volume 和 OI 由 AbstractChart 直接管理,独立生命周期。

python 复制代码
# ✅ 新方式 --- 图表自动创建,各自独立
chart.volume.set(df)           # 独立设置数据
chart.oi.set(df)               # 独立设置数据
chart.set(df)                  # 自动转发 candle/volume/oi

# 独立配置
chart.volume.price_scale(price_format={'type': 'volume'})
chart.volume.price_scale_id = 'left'

# 独立删除/重置
chart.volume.delete()          # 只删 volume,不影响 candle 和 oi
chart.oi.clear_data()          # 只清 OI 数据

迁移指南

旧 API 新 API
candle.attach_volume(df) 不需要,chart.volume 自动创建
candle.attach_open_interest(df) 不需要,chart.oi 自动创建
candle.volume_config(...) chart.volume.config(...)
candle.open_interest_config(...) chart.oi.config(...)
candle.set(df) 自动联动 volume/OI 不变,仍自动转发

🧩 CandleSeries --- 独立 K 线系列

:任意 Pane 上绘制独立 K 线,无 volume/OI 绑定,适合参考 K 线、对比 K 线。

python 复制代码
# 主图 K 线
chart.set(main_df)

# 参考 K 线(独立 Pane)
ref = chart.create_candle_series(name="BTC Ref", pane_index=2)
ref.set(btc_df)

# 所有更新方法都支持
ref.update_bars(new_df)
ref.update_ticks(tick_df)
ref.marker(time="2022-02-01", position='below', shape='arrow_up', text='买入')

🔗 同步机制:sync_id

sync=chart.id,依赖 chart 的 ID 配对,多图表时需要先拿到对方的 ID。

python 复制代码
# ❌ 旧方式(已移除)
chart1 = Chart()
chart2 = Chart(sync=chart1.id)          # 依赖 chart1.id,不直观

sync_id='组名',基于组名的解耦同步。

python 复制代码
# ✅ 新方式
Chart(sync_id='group1')                          # 组内全同步
Chart(sync_id='group1', sync_crosshair_only=True) # 仅同步十字光标
Chart(sync_id=None)                               # 不同步

# 任意多图表同组
chart1 = Chart(sync_id='group1')
chart2 = Chart(sync_id='group1')
chart3 = Chart(sync_id='group1')  # 三个图表联动

迁移指南

旧 API 新 API
sync=chart.id sync_id='组名'
sync=True sync_id='True'
sync=False / sync=None sync_id=None(不同步)

🎨 统一输入契约

:各 Series 数据格式不一致,normal_df 自动转小写/重命名列,容易隐藏问题。

:所有 Series 统一 time + value 列,列名必须精确匹配。

python 复制代码
# ✅ 新方式 --- 所有 Series 共用
line.set(df)           # 列: time, value
area.set(df)           # 列: time, value
baseline.set(df)       # 列: time, value
histogram.set(df)      # 列: time, value
candle.set(df)         # 列: time, open, high, low, close

# 列名必须精确
# ❌ 错误的列名:date, val, price
# ✅ 正确的列名:time, value, open, high, low, close

迁移指南

旧行为 新行为
date 列自动改为 time 必须手动 df.rename(columns={'date': 'time'})
列名自动转小写 列名必须精确匹配
set() 自动联动 _lines LineSeries/HistogramSeries 需要各自 line.set(df)

📦 chart_model 子包 --- 纯数据图表模型

:声明式、扁平化、引用式的数据模型,与渲染层解耦。适合构建复杂的多图表、多窗口仪表盘。

python 复制代码
from lightweight_charts.chart_model import Model, Window, Chart, Series, Adapter

# 声明式定义
model = Model(
    windows=[Window(name="main", tile=(2, 1))],
    charts=[
        Chart(name="price", window="main", tile_index=0),
        Chart(name="indicator", window="main", tile_index=1),
    ],
    series=[
        Series(name="candle", chart="price", type="candle", data=candle_df),
        Series(name="sma20", chart="price", type="line", data=sma_df, color="#FF9800"),
        Series(name="volume", chart="price", type="volume", data=vol_df),
        Series(name="rsi", chart="indicator", type="line", data=rsi_df, color="#9C27B0"),
    ],
)

# 构建 + 渲染
layout = model.build()
chart = Adapter.render(layout)

# 链式数据操作
model['candle'].set(new_df)
model['volume'].append(new_row)

# 画线管理
model.drawing.add(type='horizontal_line', price=3600, color='#FF9800')

# 实时同步(自动)
model.live_start(df_dict)  # 启动同步线程

支持 8 种 Series 类型 + 5 种画线 + 增量同步。

⚠️ 当前定位:参考原型,API 尚未定型,建议参考使用。


🧹 其他淘汰与替换

类名重命名

旧类名 新类名
Line LineSeries
Histogram HistogramSeries

方法名重命名

旧方法 新方法
series.update(s) series.update_bar(s)
series.update_from_tick(s) series.update_tick(s)
series.update_from_ticks(df) series.update_ticks(df)
chart.update(s) chart.update_bar(s)
chart.update_from_tick(s) chart.update_tick(s)
chart.update_from_ticks(df) chart.update_ticks(df)
chart.cumulative_volume 已移除,无替代

参数变更

旧参数 变化
chart.price_scale(perm_width=N) 已移除(官方 API 不存在此字段)
chart.price_scale() 默认值 从硬编码默认值改为 None,依赖旧默认值需显式传入
chart._drawings(列表) 改为 chart._drawing_series(字典 {pane_index: DrawingSeries}
chart.drawings(属性) 保留兼容性,遍历所有 pane 的 drawing
chart.sync 改为 chart.sync_id

VolumeSeries 着色要求

cumulative_volume 参数,tick 无着色需求。

:VolumeSeries 需要 open/close 列用于涨跌着色,缺失时抛 ValueError

python 复制代码
# ✅ 正确用法
chart.volume.update_ticks(df[['time', 'price', 'volume']])
# 自动从 price 聚合 open/close 用于着色

# 或直接传入带 open/close 的数据
chart.volume.update_bars(df[['time', 'value', 'open', 'close']])

🐞 Bug 修复一览

Bug 影响 修复版本
时间轴只显示日期不显示时分秒 分钟/秒级 K 线无法看时间 v3.1.1
candle_style() 引线渲染为黑色 自定义 K 线颜色时引线异常 v3.1.0
pop() Python 端数据不同步 删除 bar 后 chart.data 不一致 v3.0.1
evaluate_js 卡死消息链路 窗口创建后无法更新数据 v2.6.1
消息循环异常终止 多并发消息丢失 v2.6.1
CandleSeries 标记不显示 marker 在独立 K 线系列上不显示 v2.6.1
Volume/OI 更新不转发 独立 series 收不到数据更新 v2.7.2
ToolBox 删除顺序错误 多图表时误杀其他 handler v2.8.3
HtmlTabChart 多 tab 不可见 切换 tab 后 candle/legend 消失 v2.8.6
ReflexChart _html 内存泄漏 无限增长直到 OOM v2.8.6

⚡ 快速上手

bash 复制代码
pip install lightweight-charts-onesixth
python 复制代码
from lightweight_charts import Chart

# 5 行代码一个交互式图表
chart = Chart()
chart.set(df)           # pandas DataFrame
chart.show(block=True)  # 弹出窗口

支持:Windows / macOS / Linux,Python 3.8+


lightweight-charts-python --- 开源项目,由 community 驱动的 TradingView Lightweight Charts JS 库的 Python 封装。

项目地址:One-sixth/lightweight-charts-python

相关推荐
恋猫de小郭1 小时前
Flutter material/cupertino 解耦最新进展,已经在做新样式了
android·前端·flutter
YUS云生1 小时前
Python学习笔记·第29天:Git进阶——分支操作与合并冲突
笔记·python·学习
weedsfly1 小时前
纯函数与副作用——前端开发中最容易被忽视的质量保证
前端·javascript·面试
SimonKing1 小时前
一文终结 SpringBoot 国际化!从 0 到 1 完整案例(中/英/日)
java·后端·程序员
杖雍皓1 小时前
没有服务器如何构建现代 Web 应用:平台选型与组合策略
运维·服务器·前端·react.js·github·netlify·vercel
ByWalker_1 小时前
web应用技术—MyBatis入门
java·数据库·mybatis·lombok
TrisighT1 小时前
鸿蒙 ArkWeb 混合开发全攻略:JSBridge 双向通信 + 实战登录注入
前端·harmonyos·arkts
sun_weitao1 小时前
微前端框架之qiankun 怎么用?vue3+vite+qiankun 和 react + qiankun
前端·react.js·前端框架
在书中成长1 小时前
HarmonyOS 小游戏《对战五子棋》开发第17篇 - AI的两种评估策略
android·java·javascript