@quantlife/qlchart 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (321) hide show
  1. package/.idea/QLChart.iml +12 -0
  2. package/.idea/modules.xml +8 -0
  3. package/.idea/vcs.xml +6 -0
  4. package/README.md +75 -0
  5. package/demo/App.css +213 -0
  6. package/demo/App.tsx +46 -0
  7. package/demo/components/ControlPanel.tsx +13 -0
  8. package/demo/components/DemoNav.tsx +27 -0
  9. package/demo/index.html +16 -0
  10. package/demo/main.tsx +10 -0
  11. package/demo/pages/BasicChartDemo.tsx +61 -0
  12. package/demo/pages/DrawingDemo.tsx +22 -0
  13. package/demo/pages/IndicatorDemo.tsx +22 -0
  14. package/demo/pages/LayoutDemo.tsx +35 -0
  15. package/demo/pages/MultiPeriodDemo.tsx +31 -0
  16. package/demo/pages/ReplayDemo.tsx +195 -0
  17. package/demo/pages/SaveDemo.tsx +27 -0
  18. package/demo/pages/ThemeDemo.tsx +29 -0
  19. package/demo/standalone-demo.html +597 -0
  20. package/demo/vite.config.demo.ts +17 -0
  21. package/dist/index.d.ts +1973 -0
  22. package/dist/qlchart.js +23169 -0
  23. package/dist/style.css +1 -0
  24. package/doc/api/indicator-data-processor.md +35 -0
  25. package/doc/api-reference/.nojekyll +1 -0
  26. package/doc/api-reference/assets/hierarchy.js +1 -0
  27. package/doc/api-reference/assets/highlight.css +43 -0
  28. package/doc/api-reference/assets/icons.js +18 -0
  29. package/doc/api-reference/assets/icons.svg +1 -0
  30. package/doc/api-reference/assets/main.js +60 -0
  31. package/doc/api-reference/assets/navigation.js +1 -0
  32. package/doc/api-reference/assets/search.js +1 -0
  33. package/doc/api-reference/assets/style.css +1611 -0
  34. package/doc/api-reference/classes/ChartManager.html +16 -0
  35. package/doc/api-reference/classes/DataManager.html +13 -0
  36. package/doc/api-reference/classes/DrawingAdapter.html +64 -0
  37. package/doc/api-reference/classes/DrawingPersistence.html +21 -0
  38. package/doc/api-reference/classes/EventManager.html +12 -0
  39. package/doc/api-reference/classes/HollowCandlestickSeries.html +22 -0
  40. package/doc/api-reference/classes/IndicatorRenderer.html +20 -0
  41. package/doc/api-reference/classes/KlineReplay.html +31 -0
  42. package/doc/api-reference/classes/MockDataService.html +13 -0
  43. package/doc/api-reference/classes/MockIndicatorService.html +4 -0
  44. package/doc/api-reference/classes/OverlayIndicator.html +11 -0
  45. package/doc/api-reference/classes/PaneIndicator.html +16 -0
  46. package/doc/api-reference/classes/PaneManager.html +24 -0
  47. package/doc/api-reference/classes/RealtimeDataFeed.html +22 -0
  48. package/doc/api-reference/classes/RenkoSeries.html +22 -0
  49. package/doc/api-reference/classes/ScreenshotUtil.html +10 -0
  50. package/doc/api-reference/classes/SeriesManager.html +30 -0
  51. package/doc/api-reference/classes/ThemeManager.html +18 -0
  52. package/doc/api-reference/enums/ChartEvent.html +12 -0
  53. package/doc/api-reference/enums/IndicatorType.html +4 -0
  54. package/doc/api-reference/enums/SeriesType.html +13 -0
  55. package/doc/api-reference/functions/ChartFunctionMenu.html +1 -0
  56. package/doc/api-reference/functions/DrawingModule.html +8 -0
  57. package/doc/api-reference/functions/IndicatorPanel.html +2 -0
  58. package/doc/api-reference/functions/IndicatorTag.html +2 -0
  59. package/doc/api-reference/functions/KlineTypeSelector.html +1 -0
  60. package/doc/api-reference/functions/LayoutSwitcher.html +1 -0
  61. package/doc/api-reference/functions/PeriodSelector.html +1 -0
  62. package/doc/api-reference/functions/QLChartLayout.html +1 -0
  63. package/doc/api-reference/functions/QLChartPanel.html +10 -0
  64. package/doc/api-reference/functions/QLChartProvider.html +2 -0
  65. package/doc/api-reference/functions/QLToolbar.html +1 -0
  66. package/doc/api-reference/functions/ReplayController.html +1 -0
  67. package/doc/api-reference/functions/TimeBarModule.html +4 -0
  68. package/doc/api-reference/functions/TimeRangeSelector.html +1 -0
  69. package/doc/api-reference/functions/createIndicatorConfig.html +2 -0
  70. package/doc/api-reference/functions/getToolConfig.html +2 -0
  71. package/doc/api-reference/functions/getToolsByCategory.html +2 -0
  72. package/doc/api-reference/functions/getToolsByPriority.html +2 -0
  73. package/doc/api-reference/functions/mapLibTypeToOurs.html +2 -0
  74. package/doc/api-reference/functions/mapToolTypeToLib.html +3 -0
  75. package/doc/api-reference/functions/transformCandlestickData.html +3 -0
  76. package/doc/api-reference/functions/transformIndicatorData.html +2 -0
  77. package/doc/api-reference/functions/transformVolumeData.html +3 -0
  78. package/doc/api-reference/functions/useChart.html +4 -0
  79. package/doc/api-reference/functions/useChartStore.html +8 -0
  80. package/doc/api-reference/functions/useCrosshairSync.html +8 -0
  81. package/doc/api-reference/functions/useDrawingModule.html +1 -0
  82. package/doc/api-reference/functions/useDrawingStore.html +8 -0
  83. package/doc/api-reference/functions/useIndicatorStore.html +8 -0
  84. package/doc/api-reference/functions/useQLChartConfig.html +2 -0
  85. package/doc/api-reference/functions/useReplayStore.html +8 -0
  86. package/doc/api-reference/functions/useTheme.html +2 -0
  87. package/doc/api-reference/functions/useTimeBarStore.html +8 -0
  88. package/doc/api-reference/index.html +1 -0
  89. package/doc/api-reference/interfaces/CandlestickData.html +7 -0
  90. package/doc/api-reference/interfaces/CandlestickRawData.html +8 -0
  91. package/doc/api-reference/interfaces/ChartFunctionMenuProps.html +2 -0
  92. package/doc/api-reference/interfaces/ChartManagerCreateOptions.html +4 -0
  93. package/doc/api-reference/interfaces/ChartOptions.html +8 -0
  94. package/doc/api-reference/interfaces/ChartRequestParams.html +8 -0
  95. package/doc/api-reference/interfaces/ChartResponse.html +5 -0
  96. package/doc/api-reference/interfaces/ChartState.html +24 -0
  97. package/doc/api-reference/interfaces/ChartThemeOptions.html +5 -0
  98. package/doc/api-reference/interfaces/CrosshairData.html +5 -0
  99. package/doc/api-reference/interfaces/DrawingModuleProps.html +5 -0
  100. package/doc/api-reference/interfaces/DrawingState.html +48 -0
  101. package/doc/api-reference/interfaces/HistogramData.html +5 -0
  102. package/doc/api-reference/interfaces/HollowCandlestickData.html +14 -0
  103. package/doc/api-reference/interfaces/IndicatorConfig.html +11 -0
  104. package/doc/api-reference/interfaces/IndicatorDataPoint.html +4 -0
  105. package/doc/api-reference/interfaces/IndicatorDataResponse.html +5 -0
  106. package/doc/api-reference/interfaces/IndicatorDefinition.html +9 -0
  107. package/doc/api-reference/interfaces/IndicatorPanelProps.html +3 -0
  108. package/doc/api-reference/interfaces/IndicatorParamDef.html +8 -0
  109. package/doc/api-reference/interfaces/IndicatorRawData.html +4 -0
  110. package/doc/api-reference/interfaces/IndicatorState.html +19 -0
  111. package/doc/api-reference/interfaces/IndicatorTagProps.html +2 -0
  112. package/doc/api-reference/interfaces/KlineReplayOptions.html +4 -0
  113. package/doc/api-reference/interfaces/LayoutSwitcherProps.html +3 -0
  114. package/doc/api-reference/interfaces/LineData.html +4 -0
  115. package/doc/api-reference/interfaces/MockDataConfig.html +8 -0
  116. package/doc/api-reference/interfaces/MockIndicatorConfig.html +5 -0
  117. package/doc/api-reference/interfaces/PairInfo.html +6 -0
  118. package/doc/api-reference/interfaces/PaneInfo.html +6 -0
  119. package/doc/api-reference/interfaces/PanelConfig.html +9 -0
  120. package/doc/api-reference/interfaces/PersistenceConfig.html +12 -0
  121. package/doc/api-reference/interfaces/QLChartConfig.html +18 -0
  122. package/doc/api-reference/interfaces/QLChartLayoutProps.html +9 -0
  123. package/doc/api-reference/interfaces/QLChartPanelProps.html +13 -0
  124. package/doc/api-reference/interfaces/QLChartPanelRef.html +14 -0
  125. package/doc/api-reference/interfaces/QLToolbarProps.html +7 -0
  126. package/doc/api-reference/interfaces/RealtimeCandle.html +9 -0
  127. package/doc/api-reference/interfaces/RealtimeSubscribeFn.html +2 -0
  128. package/doc/api-reference/interfaces/RenkoData.html +16 -0
  129. package/doc/api-reference/interfaces/ReplayControllerProps.html +2 -0
  130. package/doc/api-reference/interfaces/ReplayState.html +19 -0
  131. package/doc/api-reference/interfaces/ThemeConfig.html +14 -0
  132. package/doc/api-reference/interfaces/TimeBarModuleProps.html +5 -0
  133. package/doc/api-reference/interfaces/TimeBarState.html +13 -0
  134. package/doc/api-reference/interfaces/UseChartReturn.html +4 -0
  135. package/doc/api-reference/interfaces/UseDrawingModuleOptions.html +11 -0
  136. package/doc/api-reference/interfaces/UseDrawingModuleReturn.html +6 -0
  137. package/doc/api-reference/interfaces/UseThemeReturn.html +5 -0
  138. package/doc/api-reference/types/EventHandler.html +2 -0
  139. package/doc/api-reference/types/FetchFn.html +2 -0
  140. package/doc/api-reference/types/LayoutMode.html +2 -0
  141. package/doc/api-reference/types/MarketTrend.html +2 -0
  142. package/doc/api-reference/types/ThemePreset.html +2 -0
  143. package/doc/api-reference/variables/BUILTIN_INDICATORS.html +2 -0
  144. package/doc/api-reference/variables/CATEGORY_LABELS.html +2 -0
  145. package/doc/api-reference/variables/DRAWING_TOOLS.html +3 -0
  146. package/doc/api-reference/variables/MARKET_PRESETS.html +1 -0
  147. package/doc/api-reference/variables/PAIR_PRESETS.html +1 -0
  148. package/doc/api-reference/variables/darkPreset.html +1 -0
  149. package/doc/api-reference/variables/lightPreset.html +1 -0
  150. package/doc/components/drawing-module.md +24 -0
  151. package/doc/components/indicator-list-panel.md +24 -0
  152. package/doc/components/indicator-panel.md +17 -0
  153. package/doc/components/pane-divider.md +25 -0
  154. package/doc/components/qlchart-layout.md +30 -0
  155. package/doc/components/qlchart-panel.md +93 -0
  156. package/doc/components/qlchart-provider.md +73 -0
  157. package/doc/components/qltoolbar.md +17 -0
  158. package/doc/components/replay-controller.md +23 -0
  159. package/doc/components/timebar-module.md +13 -0
  160. package/doc/core/chart-manager.md +14 -0
  161. package/doc/core/data-manager.md +33 -0
  162. package/doc/core/event-manager.md +26 -0
  163. package/doc/core/pane-manager.md +13 -0
  164. package/doc/core/series-manager.md +19 -0
  165. package/doc/core/theme-manager.md +21 -0
  166. package/doc/examples/basic-chart.md +24 -0
  167. package/doc/examples/data-format-guide.md +119 -0
  168. package/doc/examples/drawing-tools.md +30 -0
  169. package/doc/examples/indicator-properties.md +34 -0
  170. package/doc/examples/multi-pane.md +24 -0
  171. package/doc/examples/multi-panel.md +23 -0
  172. package/doc/examples/realtime-data.md +147 -0
  173. package/doc/examples/standalone-js.md +333 -0
  174. package/doc/guide/architecture.md +87 -0
  175. package/doc/guide/data-flow.md +310 -0
  176. package/doc/guide/deployment.md +59 -0
  177. package/doc/guide/drawing-properties.md +40 -0
  178. package/doc/guide/getting-started.md +94 -0
  179. package/doc/guide/pane-system.md +47 -0
  180. package/doc/guide/theme-switching.md +58 -0
  181. package/doc/hooks/use-chart.md +20 -0
  182. package/doc/hooks/use-crosshair-sync.md +14 -0
  183. package/doc/hooks/use-drawing-module.md +43 -0
  184. package/doc/hooks/use-theme.md +15 -0
  185. package/doc/index.md +33 -0
  186. package/doc/plugins/drawing/overview.md +36 -0
  187. package/doc/plugins/drawing/persistence.md +42 -0
  188. package/doc/plugins/drawing/tool-registry.md +29 -0
  189. package/doc/plugins/hollow-candlestick.md +18 -0
  190. package/doc/plugins/indicators.md +28 -0
  191. package/doc/plugins/renko.md +17 -0
  192. package/doc/plugins/replay.md +21 -0
  193. package/doc/plugins/screenshot.md +20 -0
  194. package/docs/api.md +94 -0
  195. package/package.json +54 -0
  196. package/python/qlchart/__init__.py +9 -0
  197. package/python/qlchart/__pycache__/__init__.cpython-311.pyc +0 -0
  198. package/python/qlchart/__pycache__/chart.cpython-311.pyc +0 -0
  199. package/python/qlchart/chart.py +333 -0
  200. package/python/qlchart/templates/chart_template.html +304 -0
  201. package/python/requirements.txt +1 -0
  202. package/python/setup.py +18 -0
  203. package/python/tests/__init__.py +1 -0
  204. package/python/tests/__pycache__/__init__.cpython-311.pyc +0 -0
  205. package/python/tests/__pycache__/test_chart.cpython-311-pytest-8.3.3.pyc +0 -0
  206. package/python/tests/test_chart.py +114 -0
  207. package/quantlife-qlchart-0.0.1.tgz +0 -0
  208. package/src/api/chartApi.ts +30 -0
  209. package/src/api/indicatorApi.ts +27 -0
  210. package/src/components/ChartFunctionMenu.tsx +64 -0
  211. package/src/components/PaneChartPanel.tsx +116 -0
  212. package/src/components/PaneDivider.tsx +66 -0
  213. package/src/components/QLChartLayout.tsx +151 -0
  214. package/src/components/QLChartPanel.tsx +560 -0
  215. package/src/components/QLChartProvider.tsx +90 -0
  216. package/src/components/context-menu/ChartContextMenu.tsx +139 -0
  217. package/src/components/context-menu/index.ts +2 -0
  218. package/src/components/drawing/DrawingModule.tsx +36 -0
  219. package/src/components/drawing/DrawingPropertyPanel.tsx +347 -0
  220. package/src/components/drawing/DrawingToolbar.tsx +305 -0
  221. package/src/components/drawing/index.ts +5 -0
  222. package/src/components/index.ts +43 -0
  223. package/src/components/indicator/IndicatorListPanel.tsx +94 -0
  224. package/src/components/indicator/IndicatorModal.tsx +171 -0
  225. package/src/components/indicator/IndicatorPanel.tsx +9 -0
  226. package/src/components/indicator/IndicatorPropertyPanel.tsx +130 -0
  227. package/src/components/indicator/IndicatorTag.tsx +173 -0
  228. package/src/components/indicator/index.ts +4 -0
  229. package/src/components/replay/ReplayController.css +97 -0
  230. package/src/components/replay/ReplayController.tsx +138 -0
  231. package/src/components/timebar/TimeBarModule.tsx +30 -0
  232. package/src/components/timebar/TimeRangeSelector.tsx +96 -0
  233. package/src/components/timebar/index.ts +3 -0
  234. package/src/components/toolbar/GlobalToolbar.tsx +58 -0
  235. package/src/components/toolbar/KlineTypeSelector.tsx +123 -0
  236. package/src/components/toolbar/LayoutSwitcher.tsx +45 -0
  237. package/src/components/toolbar/PeriodSelector.tsx +35 -0
  238. package/src/components/toolbar/QLToolbar.tsx +71 -0
  239. package/src/components/toolbar/TimeRangeSelector.tsx +89 -0
  240. package/src/components/ui/Modal.tsx +67 -0
  241. package/src/core/ChartManager.ts +95 -0
  242. package/src/core/DataManager.ts +427 -0
  243. package/src/core/EventManager.ts +63 -0
  244. package/src/core/IndicatorDataProcessor.ts +104 -0
  245. package/src/core/PaneManager.ts +121 -0
  246. package/src/core/RealtimeDataFeed.ts +110 -0
  247. package/src/core/SeriesManager.ts +210 -0
  248. package/src/core/ThemeManager.ts +59 -0
  249. package/src/core/index.ts +10 -0
  250. package/src/css.d.ts +4 -0
  251. package/src/hooks/useChart.ts +62 -0
  252. package/src/hooks/useCrosshairSync.ts +109 -0
  253. package/src/hooks/useDrawingModule.ts +475 -0
  254. package/src/hooks/useTheme.ts +31 -0
  255. package/src/index.ts +170 -0
  256. package/src/mock/MockDataService.ts +102 -0
  257. package/src/mock/MockIndicatorService.ts +40 -0
  258. package/src/mock/index.ts +5 -0
  259. package/src/mock/presets.ts +16 -0
  260. package/src/plugins/drawing/DrawingAdapter.ts +1762 -0
  261. package/src/plugins/drawing/DrawingPersistence.ts +273 -0
  262. package/src/plugins/drawing/DrawingPropertyTemplates.ts +327 -0
  263. package/src/plugins/drawing/DrawingSharedService.ts +125 -0
  264. package/src/plugins/drawing/DrawingToolRegistry.ts +684 -0
  265. package/src/plugins/drawing/TextLabelOverlay.ts +101 -0
  266. package/src/plugins/drawing/colorUtils.ts +53 -0
  267. package/src/plugins/drawing/index.ts +10 -0
  268. package/src/plugins/drawing/lineStyleMap.ts +46 -0
  269. package/src/plugins/drawing/migration.ts +105 -0
  270. package/src/plugins/drawing/patterns/PatternDefinitions.ts +57 -0
  271. package/src/plugins/drawing/patterns/index.ts +2 -0
  272. package/src/plugins/drawing/periodUtils.ts +51 -0
  273. package/src/plugins/indicators/AutoIndicatorRenderer.ts +204 -0
  274. package/src/plugins/indicators/IndicatorRenderer.ts +350 -0
  275. package/src/plugins/indicators/OverlayIndicator.ts +114 -0
  276. package/src/plugins/indicators/PaneIndicator.ts +137 -0
  277. package/src/plugins/indicators/index.ts +4 -0
  278. package/src/plugins/replay/KlineReplay.ts +163 -0
  279. package/src/plugins/replay/index.ts +2 -0
  280. package/src/plugins/screenshot/ScreenshotUtil.ts +123 -0
  281. package/src/plugins/screenshot/index.ts +1 -0
  282. package/src/plugins/series/HollowCandlestickSeries.ts +111 -0
  283. package/src/plugins/series/RenkoSeries.ts +104 -0
  284. package/src/plugins/series/VolumeCandlestickSeries.ts +127 -0
  285. package/src/plugins/series/index.ts +6 -0
  286. package/src/standalone.ts +386 -0
  287. package/src/store/useChartStore.ts +101 -0
  288. package/src/store/useDrawingStore.ts +135 -0
  289. package/src/store/useIndicatorStore.ts +100 -0
  290. package/src/store/usePanelRegistry.ts +50 -0
  291. package/src/store/useReplayStore.ts +42 -0
  292. package/src/store/useTimeBarStore.ts +34 -0
  293. package/src/styles/chart.css +312 -0
  294. package/src/styles/components.css +184 -0
  295. package/src/styles/context-menu.css +60 -0
  296. package/src/styles/drawing.css +524 -0
  297. package/src/styles/indicator-modal.css +216 -0
  298. package/src/styles/indicator-tag.css +210 -0
  299. package/src/styles/pane-chart.css +9 -0
  300. package/src/styles/responsive.css +71 -0
  301. package/src/styles/themes/dark.css +63 -0
  302. package/src/styles/themes/light.css +61 -0
  303. package/src/styles/toolbar.css +129 -0
  304. package/src/types/api.ts +36 -0
  305. package/src/types/chart.ts +44 -0
  306. package/src/types/drawing.ts +265 -0
  307. package/src/types/index.ts +40 -0
  308. package/src/types/indicator.ts +344 -0
  309. package/src/types/series.ts +53 -0
  310. package/src/types/theme.ts +48 -0
  311. package/src/utils/dataTransformer.ts +63 -0
  312. package/src/utils/heikinAshi.ts +41 -0
  313. package/src/utils/index.ts +3 -0
  314. package/src/utils/lineBreak.ts +88 -0
  315. package/src/utils/themePresets.ts +69 -0
  316. package/src/utils/timeFormatter.ts +29 -0
  317. package/src/utils/timeScaleUtils.ts +68 -0
  318. package/tsconfig.json +21 -0
  319. package/typedoc.json +10 -0
  320. package/vite.config.standalone.ts +31 -0
  321. package/vite.config.ts +24 -0
@@ -0,0 +1,333 @@
1
+ """QLChartHTML - Python HTML 生成器
2
+
3
+ 生成独立HTML文件,内嵌 lightweight-charts standalone + 数据JSON。
4
+ 支持蜡烛图、折线图、直方图、标记等,可设置主题和图表选项。
5
+ """
6
+
7
+ import json
8
+ import os
9
+
10
+ from jinja2 import Environment, FileSystemLoader
11
+
12
+
13
+ class QLChartHTML:
14
+ """生成独立HTML文件,内嵌 lightweight-charts standalone + 数据JSON"""
15
+
16
+ def __init__(self, title: str = "QLChart"):
17
+ self._title = title
18
+ self._theme = "dark"
19
+ self._width: str = "100%"
20
+ self._height: str = "600px"
21
+ self._series_list: list = []
22
+ self._markers: list = []
23
+ self._options: dict = {}
24
+ self._lwc_version = "5.2.0"
25
+ self._js_mode = "cdn"
26
+ self._local_js_path = None
27
+ self._drawing_enabled = False
28
+ self._drawing_pair_id = ""
29
+ self._drawing_product = ""
30
+
31
+ def add_candlestick(self, data: list) -> "QLChartHTML":
32
+ """添加蜡烛图数据
33
+
34
+ Args:
35
+ data: K线数据列表,每条包含 time(秒或毫秒时间戳), open, high, low, close
36
+ """
37
+ transformed = self._transform_ohlc(data)
38
+ self._series_list.append({"type": "candlestick", "data": transformed})
39
+ return self
40
+
41
+ def add_line(self, data: list, color: str = "#2962FF",
42
+ name: str = "") -> "QLChartHTML":
43
+ """添加折线图
44
+
45
+ Args:
46
+ data: 数据列表,每条包含 time(秒或毫秒时间戳), value
47
+ color: 线条颜色
48
+ name: 序列名称
49
+ """
50
+ transformed = self._transform_line(data)
51
+ self._series_list.append({
52
+ "type": "line",
53
+ "data": transformed,
54
+ "color": color,
55
+ "name": name,
56
+ })
57
+ return self
58
+
59
+ def add_histogram(self, data: list, color: str = "#26a69a",
60
+ name: str = "Volume") -> "QLChartHTML":
61
+ """添加直方图
62
+
63
+ Args:
64
+ data: 数据列表,每条包含 time(秒或毫秒时间戳), value, color(可选)
65
+ color: 默认颜色
66
+ name: 序列名称
67
+ """
68
+ transformed = self._transform_line(data)
69
+ self._series_list.append({
70
+ "type": "histogram",
71
+ "data": transformed,
72
+ "color": color,
73
+ "name": name,
74
+ })
75
+ return self
76
+
77
+ def add_area(self, data: list, top_color: str = "rgba(41, 98, 255, 0.4)",
78
+ bottom_color: str = "rgba(41, 98, 255, 0.0)",
79
+ line_color: str = "#2962FF",
80
+ name: str = "") -> "QLChartHTML":
81
+ """添加面积图
82
+
83
+ Args:
84
+ data: 数据列表,每条包含 time(秒或毫秒时间戳), value
85
+ top_color: 面积顶部颜色
86
+ bottom_color: 面积底部颜色
87
+ line_color: 边线颜色
88
+ name: 序列名称
89
+ """
90
+ transformed = self._transform_line(data)
91
+ self._series_list.append({
92
+ "type": "area",
93
+ "data": transformed,
94
+ "topColor": top_color,
95
+ "bottomColor": bottom_color,
96
+ "lineColor": line_color,
97
+ "name": name,
98
+ })
99
+ return self
100
+
101
+ def add_markers(self, markers: list) -> "QLChartHTML":
102
+ """添加标记(买卖信号等)
103
+
104
+ Args:
105
+ markers: 标记列表,每条包含 time, position(aboveBelow), shape, text, color
106
+ """
107
+ self._markers = markers
108
+ return self
109
+
110
+ def set_theme(self, theme: str = "dark") -> "QLChartHTML":
111
+ """设置主题
112
+
113
+ Args:
114
+ theme: "dark" 或 "light"
115
+ """
116
+ self._theme = theme
117
+ return self
118
+
119
+ def set_size(self, width: str = "100%", height: str = "600px") -> "QLChartHTML":
120
+ """设置图表尺寸
121
+
122
+ Args:
123
+ width: 宽度,如 "100%", "800px"
124
+ height: 高度,如 "600px", "100%"
125
+ """
126
+ self._width = width
127
+ self._height = height
128
+ return self
129
+
130
+ def set_options(self, options: dict) -> "QLChartHTML":
131
+ """设置图表选项
132
+
133
+ Args:
134
+ options: lightweight-charts ChartOptions 的子集
135
+ """
136
+ self._options = options
137
+ return self
138
+
139
+ def add_ma(self, data: list, period: int = 20, color: str = "#2962FF",
140
+ name: str = "MA") -> "QLChartHTML":
141
+ """快速添加移动平均线
142
+
143
+ Args:
144
+ data: K线数据列表(与add_candlestick相同格式)
145
+ period: MA周期
146
+ color: 线条颜色
147
+ name: 线条名称
148
+ """
149
+ ma_data = self._calculate_ma(data, period)
150
+ return self.add_line(ma_data, color=color, name=f"{name}{period}")
151
+
152
+ @staticmethod
153
+ def _calculate_ma(data: list, period: int) -> list:
154
+ """计算移动平均线"""
155
+ result = []
156
+ closes = [item.get("close", 0) for item in data]
157
+ for i, item in enumerate(data):
158
+ if i < period - 1:
159
+ continue
160
+ ma_value = sum(closes[i - period + 1:i + 1]) / period
161
+ result.append({
162
+ "time": item.get("time", 0),
163
+ "value": round(ma_value, 6),
164
+ })
165
+ return result
166
+
167
+ def add_boll(self, data: list, period: int = 20, std_dev: float = 2.0,
168
+ color: str = "#FF6D00", name: str = "BOLL") -> "QLChartHTML":
169
+ """快速添加布林带(上轨+中轨+下轨)
170
+
171
+ Args:
172
+ data: K线数据列表
173
+ period: 周期
174
+ std_dev: 标准差倍数
175
+ color: 线条颜色
176
+ name: 名称前缀
177
+ """
178
+ upper, middle, lower = self._calculate_boll(data, period, std_dev)
179
+ self.add_line(upper, color=color, name=f"{name}Upper")
180
+ self.add_line(middle, color="#FF6D00", name=f"{name}Mid")
181
+ self.add_line(lower, color=color, name=f"{name}Lower")
182
+ return self
183
+
184
+ @staticmethod
185
+ def _calculate_boll(data: list, period: int, std_dev: float):
186
+ """计算布林带"""
187
+ closes = [item.get("close", 0) for item in data]
188
+ upper, middle, lower = [], [], []
189
+ for i in range(period - 1, len(data)):
190
+ window = closes[i - period + 1:i + 1]
191
+ ma = sum(window) / period
192
+ std = (sum((x - ma) ** 2 for x in window) / period) ** 0.5
193
+ time_val = data[i].get("time", 0)
194
+ middle.append({"time": time_val, "value": round(ma, 6)})
195
+ upper.append({"time": time_val, "value": round(ma + std_dev * std, 6)})
196
+ lower.append({"time": time_val, "value": round(ma - std_dev * std, 6)})
197
+ return upper, middle, lower
198
+
199
+ def add_signals(self, signals: list) -> "QLChartHTML":
200
+ """快速添加买卖信号标记
201
+
202
+ Args:
203
+ signals: 信号列表,每条包含 time, type("buy"/"sell"), text(可选)
204
+ """
205
+ markers = []
206
+ for signal in signals:
207
+ marker = {
208
+ "time": signal.get("time", 0),
209
+ "position": "belowBar" if signal.get("type") == "buy" else "aboveBar",
210
+ "color": "#26a69a" if signal.get("type") == "buy" else "#ef5350",
211
+ "shape": "arrowUp" if signal.get("type") == "buy" else "arrowDown",
212
+ "text": signal.get("text", "B" if signal.get("type") == "buy" else "S"),
213
+ }
214
+ markers.append(marker)
215
+ return self.add_markers(markers)
216
+
217
+ def add_volume_colored(self, data: list, name: str = "Volume") -> "QLChartHTML":
218
+ """添加带涨跌色的成交量直方图
219
+
220
+ Args:
221
+ data: K线数据列表,需要包含 open/close 字段来判断涨跌
222
+ name: 序列名称
223
+ """
224
+ volume_data = []
225
+ for item in data:
226
+ color = "#26a69a" if item.get("close", 0) >= item.get("open", 0) else "#ef5350"
227
+ volume_data.append({
228
+ "time": item.get("time", 0),
229
+ "value": item.get("volume", 0),
230
+ "color": color,
231
+ })
232
+ self._series_list.append({
233
+ "type": "histogram",
234
+ "data": volume_data,
235
+ "name": name,
236
+ })
237
+ return self
238
+
239
+ def set_js_mode(self, mode: str, local_path: str = None) -> "QLChartHTML":
240
+ """设置JS加载模式
241
+
242
+ Args:
243
+ mode: "cdn" | "inline" | "local"
244
+ local_path: 本地JS文件路径(mode="local"时使用)
245
+ """
246
+ self._js_mode = mode
247
+ self._local_js_path = local_path
248
+ return self
249
+
250
+ def enable_drawing(self, pair_id: str, product: str = "BTC") -> "QLChartHTML":
251
+ """启用绘图工具栏和LocalStorage持久化
252
+
253
+ Args:
254
+ pair_id: 交易对ID(用于LocalStorage Key生成)
255
+ product: 产品类型
256
+ """
257
+ self._drawing_enabled = True
258
+ self._drawing_pair_id = pair_id
259
+ self._drawing_product = product
260
+ return self
261
+
262
+ def to_html(self) -> str:
263
+ """生成完整HTML字符串"""
264
+ template_dir = os.path.join(os.path.dirname(__file__), "templates")
265
+ env = Environment(loader=FileSystemLoader(template_dir))
266
+ template = env.get_template("chart_template.html")
267
+
268
+ # inline模式:读取standalone.js文件内容
269
+ inline_js = ""
270
+ js_mode = self._js_mode
271
+ if js_mode == "inline":
272
+ standalone_path = os.path.join(os.path.dirname(__file__), "standalone.js")
273
+ if os.path.exists(standalone_path):
274
+ with open(standalone_path, "r", encoding="utf-8") as f:
275
+ inline_js = f.read()
276
+ else:
277
+ # fallback到CDN模式
278
+ js_mode = "cdn"
279
+
280
+ return template.render(
281
+ title=self._title,
282
+ theme=self._theme,
283
+ width=self._width,
284
+ height=self._height,
285
+ series=json.dumps(self._series_list, default=str),
286
+ markers=json.dumps(self._markers, default=str),
287
+ options=json.dumps(self._options, default=str),
288
+ lwc_version=self._lwc_version,
289
+ js_mode=js_mode,
290
+ inline_js=inline_js,
291
+ local_js_path=self._local_js_path or "",
292
+ drawing_enabled=self._drawing_enabled,
293
+ drawing_pair_id=self._drawing_pair_id,
294
+ drawing_product=self._drawing_product,
295
+ )
296
+
297
+ def save(self, filepath: str) -> None:
298
+ """保存为HTML文件
299
+
300
+ Args:
301
+ filepath: 保存路径
302
+ """
303
+ html = self.to_html()
304
+ dir_path = os.path.dirname(filepath)
305
+ if dir_path and not os.path.exists(dir_path):
306
+ os.makedirs(dir_path, exist_ok=True)
307
+ with open(filepath, "w", encoding="utf-8") as f:
308
+ f.write(html)
309
+
310
+ @staticmethod
311
+ def _transform_ohlc(data: list) -> list:
312
+ """转换OHLC数据:毫秒时间戳→秒"""
313
+ result = []
314
+ for item in data:
315
+ d = dict(item)
316
+ t = d.get("time", 0)
317
+ # 毫秒时间戳→秒
318
+ if isinstance(t, (int, float)) and t > 1e10:
319
+ d["time"] = int(t / 1000)
320
+ result.append(d)
321
+ return result
322
+
323
+ @staticmethod
324
+ def _transform_line(data: list) -> list:
325
+ """转换Line/Histogram数据:毫秒时间戳→秒"""
326
+ result = []
327
+ for item in data:
328
+ d = dict(item)
329
+ t = d.get("time", 0)
330
+ if isinstance(t, (int, float)) and t > 1e10:
331
+ d["time"] = int(t / 1000)
332
+ result.append(d)
333
+ return result
@@ -0,0 +1,304 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>{{ title }}</title>
7
+ {% if js_mode == 'cdn' %}
8
+ <script src="https://unpkg.com/lightweight-charts@{{ lwc_version }}/dist/lightweight-charts.standalone.production.js"></script>
9
+ {% elif js_mode == 'inline' %}
10
+ <script>{{ inline_js | safe }}</script>
11
+ {% elif js_mode == 'local' %}
12
+ <script src="{{ local_js_path }}"></script>
13
+ {% endif %}
14
+ {% if drawing_enabled %}
15
+ <script src="https://unpkg.com/lightweight-charts-drawing/dist/lwc-drawing.standalone.production.js"></script>
16
+ {% endif %}
17
+ <style>
18
+ * { margin: 0; padding: 0; box-sizing: border-box; }
19
+ body {
20
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
21
+ background: {% if theme == 'dark' %}#1e1e1e{% else %}#ffffff{% endif %};
22
+ color: {% if theme == 'dark' %}#d1d4dc{% else %}#131722{% endif %};
23
+ }
24
+ .chart-header {
25
+ padding: 12px 16px;
26
+ display: flex;
27
+ align-items: center;
28
+ justify-content: space-between;
29
+ border-bottom: 1px solid {% if theme == 'dark' %}#2a2e39{% else %}#e0e3eb{% endif %};
30
+ }
31
+ .chart-header h2 {
32
+ font-size: 16px;
33
+ font-weight: 600;
34
+ }
35
+ .chart-container {
36
+ width: {{ width }};
37
+ height: {{ height }};
38
+ position: relative;
39
+ }
40
+ {% if drawing_enabled %}
41
+ #drawing-toolbar {
42
+ position: absolute;
43
+ top: 50px;
44
+ left: 10px;
45
+ z-index: 100;
46
+ display: flex;
47
+ flex-direction: column;
48
+ gap: 4px;
49
+ background: {% if theme == 'dark' %}#2a2e39{% else %}#f0f3fa{% endif %};
50
+ border-radius: 6px;
51
+ padding: 4px;
52
+ box-shadow: 0 2px 8px rgba(0,0,0,0.15);
53
+ }
54
+ .dw-btn {
55
+ width: 32px;
56
+ height: 32px;
57
+ border: none;
58
+ border-radius: 4px;
59
+ background: transparent;
60
+ cursor: pointer;
61
+ font-size: 16px;
62
+ display: flex;
63
+ align-items: center;
64
+ justify-content: center;
65
+ transition: background 0.15s;
66
+ }
67
+ .dw-btn:hover {
68
+ background: {% if theme == 'dark' %}#3a3f4b{% else %}#e0e3eb{% endif %};
69
+ }
70
+ .dw-btn.active {
71
+ background: #2962FF;
72
+ color: #fff;
73
+ }
74
+ {% endif %}
75
+ </style>
76
+ </head>
77
+ <body>
78
+ <div class="chart-header">
79
+ <h2>{{ title }}</h2>
80
+ </div>
81
+ <div id="qlchart-container" class="chart-container"></div>
82
+
83
+ {% if drawing_enabled %}
84
+ <div id="drawing-toolbar" style="display:none;">
85
+ <button data-tool="cursor" class="dw-btn active" title="光标">🖱️</button>
86
+ <button data-tool="trend-line" class="dw-btn" title="趋势线">📈</button>
87
+ <button data-tool="horizontal-line" class="dw-btn" title="水平线">➖</button>
88
+ <button data-tool="rectangle" class="dw-btn" title="矩形">⬜</button>
89
+ <button data-tool="fib-retracement" class="dw-btn" title="斐波那契回撤">📐</button>
90
+ </div>
91
+ {% endif %}
92
+
93
+ <script>
94
+ (function() {
95
+ const theme = {{ theme | tojson }};
96
+ const seriesData = {{ series | safe }};
97
+ const markersData = {{ markers | safe }};
98
+ const customOptions = {{ options | safe }};
99
+
100
+ // 主题配置
101
+ const darkTheme = {
102
+ layout: {
103
+ background: { color: '#1e1e1e' },
104
+ textColor: '#d1d4dc',
105
+ },
106
+ grid: {
107
+ vertLines: { color: '#2a2e39' },
108
+ horzLines: { color: '#2a2e39' },
109
+ },
110
+ crosshair: {
111
+ vertLine: { color: '#758696', width: 1, style: 3 },
112
+ horzLine: { color: '#758696', width: 1, style: 3 },
113
+ },
114
+ timeScale: {
115
+ borderColor: '#2a2e39',
116
+ timeVisible: true,
117
+ secondsVisible: false,
118
+ },
119
+ rightPriceScale: {
120
+ borderColor: '#2a2e39',
121
+ },
122
+ };
123
+
124
+ const lightTheme = {
125
+ layout: {
126
+ background: { color: '#ffffff' },
127
+ textColor: '#131722',
128
+ },
129
+ grid: {
130
+ vertLines: { color: '#e0e3eb' },
131
+ horzLines: { color: '#e0e3eb' },
132
+ },
133
+ crosshair: {
134
+ vertLine: { color: '#758696', width: 1, style: 3 },
135
+ horzLine: { color: '#758696', width: 1, style: 3 },
136
+ },
137
+ timeScale: {
138
+ borderColor: '#e0e3eb',
139
+ timeVisible: true,
140
+ secondsVisible: false,
141
+ },
142
+ rightPriceScale: {
143
+ borderColor: '#e0e3eb',
144
+ },
145
+ };
146
+
147
+ const themeOptions = theme === 'dark' ? darkTheme : lightTheme;
148
+
149
+ // 合并自定义选项
150
+ const chartOptions = { ...themeOptions, ...customOptions };
151
+
152
+ // 创建图表
153
+ const container = document.getElementById('qlchart-container');
154
+ const chart = LightweightCharts.createChart(container, chartOptions);
155
+
156
+ // 自适应尺寸
157
+ function resizeChart() {
158
+ const rect = container.getBoundingClientRect();
159
+ chart.applyOptions({ width: rect.width, height: rect.height });
160
+ }
161
+ window.addEventListener('resize', resizeChart);
162
+ resizeChart();
163
+
164
+ // Series类型映射(lightweight-charts v5.2 standalone)
165
+ const seriesCreators = {
166
+ candlestick: (opts) => chart.addCandlestickSeries(opts),
167
+ line: (opts) => chart.addLineSeries(opts),
168
+ histogram: (opts) => chart.addHistogramSeries(opts),
169
+ area: (opts) => chart.addAreaSeries(opts),
170
+ bar: (opts) => chart.addBarSeries(opts),
171
+ baseline: (opts) => chart.addBaselineSeries(opts),
172
+ };
173
+
174
+ let mainSeries = null;
175
+
176
+ // 创建所有序列
177
+ seriesData.forEach(function(item) {
178
+ const opts = {};
179
+ if (item.color) opts.color = item.color;
180
+ if (item.name) opts.title = item.name;
181
+ if (item.topColor) opts.topColor = item.topColor;
182
+ if (item.bottomColor) opts.bottomColor = item.bottomColor;
183
+ if (item.lineColor) opts.lineColor = item.lineColor;
184
+
185
+ const seriesType = item.type || 'candlestick';
186
+ const creator = seriesCreators[seriesType];
187
+
188
+ if (creator) {
189
+ const series = creator(opts);
190
+ series.setData(item.data || []);
191
+
192
+ // 第一个序列作为主序列
193
+ if (!mainSeries) {
194
+ mainSeries = series;
195
+
196
+ // 添加标记
197
+ if (seriesType === 'candlestick' && markersData && markersData.length > 0) {
198
+ series.setMarkers(markersData);
199
+ }
200
+ }
201
+ }
202
+ });
203
+
204
+ // 自动缩放到数据范围
205
+ chart.timeScale().fitContent();
206
+
207
+ // ══════════════════════════════════════════════
208
+ // 绘图功能(仅 enable_drawing 启用时)
209
+ // ══════════════════════════════════════════════
210
+ {% if drawing_enabled %}
211
+ (function() {
212
+ const STORAGE_PREFIX = 'qlchart_dw_';
213
+ const STORAGE_VERSION = 1;
214
+ const pairId = '{{ drawing_pair_id }}';
215
+ const product = '{{ drawing_product }}';
216
+
217
+ // 生成存储Key(仅使用 pairId + product)
218
+ function simpleHash(str) {
219
+ let hash = 0;
220
+ for (let i = 0; i < str.length; i++) {
221
+ const char = str.charCodeAt(i);
222
+ hash = ((hash << 5) - hash) + char;
223
+ hash |= 0;
224
+ }
225
+ return Math.abs(hash).toString(36);
226
+ }
227
+ const STORAGE_KEY = STORAGE_PREFIX + simpleHash(pairId + '_' + product);
228
+
229
+ // 显示工具栏
230
+ const toolbar = document.getElementById('drawing-toolbar');
231
+ if (toolbar) toolbar.style.display = 'flex';
232
+
233
+ // DrawingManager 初始化
234
+ let drawingManager = null;
235
+ if (typeof DrawingManager !== 'undefined') {
236
+ drawingManager = new DrawingManager();
237
+ drawingManager.attach(chart, mainSeries, container);
238
+ } else if (typeof window.lwc !== 'undefined' && window.lwc.DrawingManager) {
239
+ drawingManager = new window.lwc.DrawingManager();
240
+ drawingManager.attach(chart, mainSeries, container);
241
+ }
242
+
243
+ if (!drawingManager) {
244
+ console.warn('[QLChart] DrawingManager not available. Drawing toolbar disabled.');
245
+ return;
246
+ }
247
+
248
+ // 加载已保存的绘图
249
+ function loadDrawings() {
250
+ const json = localStorage.getItem(STORAGE_KEY);
251
+ if (!json) return;
252
+ try {
253
+ const envelope = JSON.parse(json);
254
+ if (envelope.drawings) {
255
+ drawingManager.importDrawings(envelope.drawings);
256
+ }
257
+ } catch (e) {
258
+ console.error('[QLChart] Failed to load drawings:', e);
259
+ }
260
+ }
261
+
262
+ // 保存绘图(debounce)
263
+ let saveTimer = null;
264
+ function saveDrawings() {
265
+ if (saveTimer) clearTimeout(saveTimer);
266
+ saveTimer = setTimeout(function() {
267
+ const drawings = drawingManager.exportDrawings();
268
+ const envelope = {
269
+ version: STORAGE_VERSION,
270
+ drawings: drawings,
271
+ updatedAt: Date.now(),
272
+ };
273
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(envelope));
274
+ }, 300);
275
+ }
276
+
277
+ // 工具栏事件
278
+ document.querySelectorAll('.dw-btn').forEach(function(btn) {
279
+ btn.addEventListener('click', function() {
280
+ document.querySelectorAll('.dw-btn').forEach(function(b) {
281
+ b.classList.remove('active');
282
+ });
283
+ btn.classList.add('active');
284
+ var tool = btn.dataset.tool;
285
+ drawingManager.setActiveTool(tool === 'cursor' ? null : tool);
286
+ });
287
+ });
288
+
289
+ // 绘图变更自动保存
290
+ if (drawingManager.on) {
291
+ drawingManager.on('drawingCreated', saveDrawings);
292
+ drawingManager.on('drawingRemoved', saveDrawings);
293
+ drawingManager.on('drawingModified', saveDrawings);
294
+ }
295
+
296
+ // 初始加载
297
+ loadDrawings();
298
+ })();
299
+ {% endif %}
300
+
301
+ })();
302
+ </script>
303
+ </body>
304
+ </html>
@@ -0,0 +1 @@
1
+ Jinja2>=3.0
@@ -0,0 +1,18 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name="qlchart",
5
+ version="0.1.0",
6
+ description="QLChart Python HTML Generator - 生成基于 lightweight-charts 的独立HTML图表",
7
+ author="QuantLife",
8
+ author_email="dev@quantlife.ai",
9
+ packages=find_packages(),
10
+ include_package_data=True,
11
+ package_data={
12
+ "qlchart": ["templates/*.html"],
13
+ },
14
+ install_requires=[
15
+ "Jinja2>=3.0",
16
+ ],
17
+ python_requires=">=3.9",
18
+ )
@@ -0,0 +1 @@
1
+ # empty file