37 lines
1.7 KiB
Markdown
37 lines
1.7 KiB
Markdown
# useLightweightChart
|
||
|
||
**路径**:`src/composables/useLightweightChart.ts`
|
||
|
||
## 功能用途
|
||
|
||
[TradingView Lightweight Charts](https://tradingview.github.io/lightweight-charts/) 工具函数,用于将项目内 `[timestamp_ms, value][]` 格式转为图表所需格式,并提供创建折线/面积图的便捷方法。
|
||
|
||
## 核心能力
|
||
|
||
- `toLwcData`:将 `[timestamp_ms, value][]` 转为 `{ time: UTCTimestamp, value: number }[]`,输入为毫秒(>=1e12)时自动除以 1000 转为秒,按时间升序排序并去重(同时间戳保留最新价格),时间轴显示用户当地时间
|
||
- `toLwcPoint`:将单点 `[timestamp_ms, value]` 转为 `{ time, value }`,用于 `series.update()` 增量更新
|
||
- `createLineChart`:创建基础折线图实例(`attributionLogo: false` 隐藏 TradingView 图标)
|
||
- `addLineSeries`:添加折线系列(支持 percent/price 格式)
|
||
- `addAreaSeries`:添加面积系列(带渐变)
|
||
|
||
## 使用方式
|
||
|
||
```typescript
|
||
import { toLwcData, toLwcPoint, createLineChart, addLineSeries } from '@/composables/useLightweightChart'
|
||
|
||
const points: [number, number][] = [[Date.now() - 3600000, 50], [Date.now(), 55]]
|
||
const lwcData = toLwcData(points)
|
||
|
||
const chart = createLineChart(containerEl, { width: 400, height: 320 })
|
||
const series = addLineSeries(chart, { color: '#2563eb', priceFormat: { type: 'percent', precision: 1 } })
|
||
series.setData(lwcData)
|
||
|
||
// 实时追加/更新单点时,使用 update() 替代 setData() 以获得更平滑的过渡效果
|
||
series.update(toLwcPoint([Date.now(), 52]))
|
||
```
|
||
|
||
## 扩展方式
|
||
|
||
- 新增图表类型:参考 `addAreaSeries` 使用 `AreaSeries`、`CandlestickSeries` 等
|
||
- 自定义主题:修改 `createLineChart` 的 `layout`、`grid`、`rightPriceScale` 等配置
|