react-klinecharts-ui 0.1.0 → 0.2.0

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.
package/README.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  **react-klinecharts-ui** is a headless React library for building financial trading terminals on top of [klinecharts](https://github.com/liihuu/KLineChart). It provides a state provider, a set of hooks, and overlay templates. No UI components are included — use any UI framework you prefer.
4
4
 
5
+ ### Acknowledgments
6
+
7
+ Many features in this library — including 11 TradingView-style indicators, 9 drawing overlays, the TA math library, undo/redo, layout manager, and script editor — were ported from the [QUANTIX Extended Edition](https://github.com/dsavenk0/KLineChart-Pro) fork of KLineChart-Pro by [@dsavenk0](https://github.com/dsavenk0). The original fork implements these as a tightly-coupled Vue 3 application; this library re-implements them as headless React hooks following the composable, framework-agnostic architecture.
8
+
5
9
  ---
6
10
 
7
11
  ## Table of Contents
@@ -27,13 +31,18 @@
27
31
  - [useScreenshot](#usescreenshot)
28
32
  - [useFullscreen](#usefullscreen)
29
33
  - [useOrderLines](#useorderlines)
34
+ - [useUndoRedo](#useundoredo)
35
+ - [useLayoutManager](#uselayoutmanager)
36
+ - [useScriptEditor](#usescripteditor)
30
37
  6. [Utilities](#utilities)
31
38
  - [createDataLoader](#createdataloader)
39
+ - [TA (Technical Analysis)](#ta-technical-analysis)
32
40
  7. [Data & Constants](#data--constants)
33
- 8. [Drawing Overlays](#drawing-overlays)
34
- 9. [Extensions](#extensions)
35
- 10. [State Callbacks](#state-callbacks)
36
- 11. [Full Export List](#full-export-list)
41
+ 8. [Custom Indicator Templates](#custom-indicator-templates)
42
+ 9. [Drawing Overlays](#drawing-overlays)
43
+ 10. [Extensions](#extensions)
44
+ 11. [State Callbacks](#state-callbacks)
45
+ 12. [Full Export List](#full-export-list)
37
46
 
38
47
  ---
39
48
 
@@ -737,6 +746,169 @@ removeOrderLine(id!);
737
746
 
738
747
  ---
739
748
 
749
+ ### useUndoRedo
750
+
751
+ Undo/redo history for drawing overlays and indicator toggles. Automatically connected to `useDrawingTools` and `useIndicators` via a shared context ref — actions are recorded without manual wiring.
752
+
753
+ **Keyboard shortcuts:** `Ctrl+Z` (undo), `Ctrl+Y` / `Ctrl+Shift+Z` (redo).
754
+
755
+ ```typescript
756
+ import { useUndoRedo } from "react-klinecharts-ui";
757
+
758
+ const { canUndo, canRedo, undo, redo, pushAction, clear } = useUndoRedo();
759
+ ```
760
+
761
+ #### Return type: `UseUndoRedoReturn`
762
+
763
+ | Property | Type | Description |
764
+ |----------|------|-------------|
765
+ | `canUndo` | `boolean` | Whether there are actions to undo |
766
+ | `canRedo` | `boolean` | Whether there are actions to redo |
767
+ | `undo` | `() => void` | Undo the last action |
768
+ | `redo` | `() => void` | Redo the last undone action |
769
+ | `pushAction` | `(action: UndoRedoAction) => void` | Push a new action onto the undo stack (clears redo) |
770
+ | `clear` | `() => void` | Clear all undo/redo history |
771
+
772
+ #### Action types
773
+
774
+ | Type | Trigger | Undo behaviour | Redo behaviour |
775
+ |------|---------|----------------|----------------|
776
+ | `overlay_added` | User completes a drawing | Removes the overlay | Re-creates the overlay |
777
+ | `overlays_removed` | `removeAllDrawings()` | Restores all removed overlays | Re-removes them |
778
+ | `indicator_toggled` | Add/remove indicator | Reverses the toggle | Re-applies the toggle |
779
+
780
+ #### Cross-hook communication
781
+
782
+ `useUndoRedo` registers a `pushAction` callback on `undoRedoListenerRef` (shared via provider context). When `useDrawingTools` finishes a drawing or `useIndicators` toggles an indicator, they call the ref to record the action — no prop drilling required.
783
+
784
+ ---
785
+
786
+ ### useLayoutManager
787
+
788
+ Save, load, rename, and delete named chart layouts via `localStorage`. Captures indicators, drawings, symbol, and period. Optional auto-save with 5-second debounce.
789
+
790
+ ```typescript
791
+ import { useLayoutManager } from "react-klinecharts-ui";
792
+
793
+ const {
794
+ layouts,
795
+ saveLayout,
796
+ loadLayout,
797
+ deleteLayout,
798
+ renameLayout,
799
+ refreshLayouts,
800
+ autoSaveEnabled,
801
+ setAutoSaveEnabled,
802
+ } = useLayoutManager();
803
+ ```
804
+
805
+ #### Return type: `UseLayoutManagerReturn`
806
+
807
+ | Property | Type | Description |
808
+ |----------|------|-------------|
809
+ | `layouts` | `LayoutEntry[]` | List of saved layout entries |
810
+ | `saveLayout` | `(name: string) => string \| null` | Save current chart state; returns layout ID |
811
+ | `loadLayout` | `(id: string) => boolean` | Load and apply a layout by ID |
812
+ | `deleteLayout` | `(id: string) => void` | Delete a layout |
813
+ | `renameLayout` | `(id: string, name: string) => boolean` | Rename a layout |
814
+ | `refreshLayouts` | `() => void` | Refresh the list from localStorage |
815
+ | `autoSaveEnabled` | `boolean` | Whether auto-save is enabled |
816
+ | `setAutoSaveEnabled` | `(enabled: boolean) => void` | Toggle auto-save |
817
+
818
+ #### LayoutEntry
819
+
820
+ ```typescript
821
+ interface LayoutEntry {
822
+ id: string;
823
+ name: string;
824
+ symbol: string;
825
+ period: string;
826
+ timestamp: number;
827
+ lastModified: number;
828
+ state: ChartLayoutState;
829
+ }
830
+ ```
831
+
832
+ #### ChartLayoutState
833
+
834
+ ```typescript
835
+ interface ChartLayoutState {
836
+ version: string;
837
+ meta: { symbol: string; period: string; timestamp: number; lastModified: number };
838
+ indicators: Array<{ paneId: string; name: string; calcParams: any[]; visible: boolean }>;
839
+ drawings: Array<{ name: string; points: any[]; styles?: any; extendData?: any }>;
840
+ }
841
+ ```
842
+
843
+ ---
844
+
845
+ ### useScriptEditor
846
+
847
+ Pine Script-style custom indicator editor. Users write plain JavaScript function bodies that receive `TA`, `dataList` (array of `KLineData`), and `params` (parsed from a comma-separated string). The script must return an array of objects — one per candle, each key becomes a chart series.
848
+
849
+ Scripts execute inside a sandboxed `new Function()` with dangerous globals shadowed: `fetch`, `XMLHttpRequest`, `WebSocket`, `Worker`, `SharedWorker`, `importScripts`, `self`, `caches`, `indexedDB`.
850
+
851
+ ```typescript
852
+ import { useScriptEditor } from "react-klinecharts-ui";
853
+
854
+ const {
855
+ code, setCode,
856
+ scriptName, setScriptName,
857
+ params, setParams,
858
+ placement, setPlacement,
859
+ error, status, isRunning, hasActiveScript,
860
+ runScript, removeScript, resetCode,
861
+ exportScript, importScript,
862
+ defaultScript,
863
+ } = useScriptEditor();
864
+ ```
865
+
866
+ #### Return type: `UseScriptEditorReturn`
867
+
868
+ | Property | Type | Description |
869
+ |----------|------|-------------|
870
+ | `code` | `string` | Current script source code |
871
+ | `setCode` | `(code: string) => void` | Update the source code |
872
+ | `scriptName` | `string` | Display name of the script |
873
+ | `setScriptName` | `(name: string) => void` | Update the name |
874
+ | `params` | `string` | Comma-separated numeric params (e.g. `"14, 26, 9"`) |
875
+ | `setParams` | `(params: string) => void` | Update params |
876
+ | `placement` | `ScriptPlacement` | `"main"` or `"sub"` |
877
+ | `setPlacement` | `(p: ScriptPlacement) => void` | Set placement |
878
+ | `error` | `string` | Last error message (empty = no error) |
879
+ | `status` | `string` | Last status message |
880
+ | `isRunning` | `boolean` | Whether the script is currently executing |
881
+ | `hasActiveScript` | `boolean` | Whether a script indicator is on the chart |
882
+ | `runScript` | `() => void` | Execute the script and register the indicator |
883
+ | `removeScript` | `() => void` | Remove the current script indicator from the chart |
884
+ | `resetCode` | `() => void` | Reset code to the default template |
885
+ | `exportScript` | `() => void` | Download the code as a `.js` file |
886
+ | `importScript` | `(file: File) => void` | Load a script from a file |
887
+ | `defaultScript` | `string` | The default template code |
888
+
889
+ #### Example script
890
+
891
+ ```javascript
892
+ // Available: TA, dataList, params
893
+ const period = params[0] ?? 14;
894
+ const closes = dataList.map(d => d.close);
895
+ const highs = dataList.map(d => d.high);
896
+ const lows = dataList.map(d => d.low);
897
+
898
+ const rsi = TA.rsi(closes, period);
899
+ const boll = TA.bollinger(closes, period, 2);
900
+
901
+ // Return one object per candle — each key = one line on the chart
902
+ return rsi.map((v, i) => ({
903
+ rsi: v,
904
+ upper: boll.upper[i],
905
+ mid: boll.mid[i],
906
+ lower: boll.lower[i],
907
+ }));
908
+ ```
909
+
910
+ ---
911
+
740
912
  ## Utilities
741
913
 
742
914
  ### createDataLoader
@@ -787,6 +959,33 @@ function ChartView() {
787
959
 
788
960
  ---
789
961
 
962
+ ### TA (Technical Analysis)
963
+
964
+ A standalone math library for computing common technical indicators. Used internally by indicator templates and available to custom scripts via `useScriptEditor`.
965
+
966
+ ```typescript
967
+ import { TA } from "react-klinecharts-ui";
968
+ ```
969
+
970
+ | Function | Signature | Returns |
971
+ |----------|-----------|---------|
972
+ | `TA.sma` | `(data: number[], period: number)` | `number[]` — Simple Moving Average |
973
+ | `TA.ema` | `(data: number[], period: number)` | `number[]` — Exponential Moving Average |
974
+ | `TA.rma` | `(data: number[], period: number)` | `number[]` — Running (Wilder's) Moving Average |
975
+ | `TA.wma` | `(data: number[], period: number)` | `number[]` — Weighted Moving Average |
976
+ | `TA.hma` | `(data: number[], period: number)` | `number[]` — Hull Moving Average |
977
+ | `TA.stdev` | `(data: number[], period: number)` | `number[]` — Standard Deviation |
978
+ | `TA.rsi` | `(data: number[], period: number)` | `(number \| null)[]` — Relative Strength Index |
979
+ | `TA.macd` | `(data: number[], fast?: number, slow?: number, signal?: number)` | `{ dif, dea, macd }` — each `(number \| null)[]` |
980
+ | `TA.bollinger` | `(data: number[], period?: number, mult?: number)` | `{ upper, mid, lower }` — each `(number \| null)[]` |
981
+ | `TA.tr` | `(highs: number[], lows: number[], closes: number[])` | `number[]` — True Range |
982
+ | `TA.atr` | `(highs: number[], lows: number[], closes: number[], period: number)` | `number[]` — Average True Range |
983
+ | `TA.vwap` | `(highs: number[], lows: number[], closes: number[], volumes: number[])` | `number[]` — Volume Weighted Average Price |
984
+ | `TA.cci` | `(highs: number[], lows: number[], closes: number[], period: number)` | `number[]` — Commodity Channel Index |
985
+ | `TA.stoch` | `(highs: number[], lows: number[], closes: number[], kPeriod?, kSmooth?, dPeriod?)` | `{ k, d }` — each `(number \| null)[]` |
986
+
987
+ ---
988
+
790
989
  ## Data & Constants
791
990
 
792
991
  All constants are exported from the root `index.ts`:
@@ -856,6 +1055,38 @@ type PriceAxisType = "normal" | "percentage" | "log";
856
1055
 
857
1056
  ---
858
1057
 
1058
+ ## Custom Indicator Templates
1059
+
1060
+ 11 TradingView-style indicator templates ported from [QUANTIX Extended Edition](https://github.com/dsavenk0/KLineChart-Pro). All are registered automatically via `registerExtensions`. Each template uses the `TA` library for calculations and includes custom `draw` functions for TradingView-like visual styling (gradient fills, dashed level lines, multi-color histograms).
1061
+
1062
+ ```typescript
1063
+ import { indicators } from "react-klinecharts-ui";
1064
+ // indicators === [bollTv, cci, hma, ichimoku, maRibbon, macdTv, pivotPoints, rsiTv, stochastic, superTrend, vwap]
1065
+ ```
1066
+
1067
+ ### Main chart indicators
1068
+
1069
+ | Template | Name | Default params | Description |
1070
+ |----------|------|----------------|-------------|
1071
+ | `bollTv` | `BOLL_TV` | `[20, 2]` | Bollinger Bands — TradingView style with filled band area, SMA midline, and upper/lower bands |
1072
+ | `hma` | `HMA` | `[9]` | Hull Moving Average — high smoothing with minimal lag via `TA.hma()` |
1073
+ | `ichimoku` | `ICHIMOKU` | `[9, 26, 52, 26]` | Ichimoku Cloud — Tenkan-sen, Kijun-sen, Senkou Span A/B (filled cloud), Chikou Span |
1074
+ | `maRibbon` | `MA_RIBBON` | `[5, 10, 20, 30, 50, 100]` | Moving Average Ribbon — 6 EMAs with distinct colors for trend visualization |
1075
+ | `pivotPoints` | `PIVOT_POINTS` | `[1]` | Standard pivot with Pivot, R1, R2, S1, S2 levels as dashed horizontal lines |
1076
+ | `superTrend` | `SUPERTREND` | `[10, 3]` | ATR-based trend — dynamic green (up) / red (down) line coloring |
1077
+ | `vwap` | `VWAP` | `[]` | Volume Weighted Average Price — single blue line via `TA.vwap()` |
1078
+
1079
+ ### Sub-pane indicators
1080
+
1081
+ | Template | Name | Default params | Description |
1082
+ |----------|------|----------------|-------------|
1083
+ | `macdTv` | `MACD_TV` | `[12, 26, 9]` | 4-color histogram: growing-positive (#26A69A), shrinking-positive (#B2DFDB), growing-negative (#FFCDD2), shrinking-negative (#EF5350). MACD line (#2962FF), Signal line (#FF6D00) |
1084
+ | `rsiTv` | `RSI_TV` | `[14, 14]` | RSI + MA line. Dashed levels at 70/50/30. Gradient fills in overbought (>70, red) and oversold (<30, green) zones |
1085
+ | `cci` | `CCI` | `[20]` | Commodity Channel Index via `TA.cci()` with dashed +100/0/-100 reference lines |
1086
+ | `stochastic` | `STOCHASTIC` | `[14, 1, 3]` | %K (#2962FF) and %D (#FF6D00) lines. Dashed 80/50/20 levels. Gradient fills in overbought/oversold zones |
1087
+
1088
+ ---
1089
+
859
1090
  ## Drawing Overlays
860
1091
 
861
1092
  `OverlayTemplate` instances for drawing tools. Automatically registered when `registerExtensions: true` (default).
@@ -881,6 +1112,15 @@ type PriceAxisType = "normal" | "percentage" | "log";
881
1112
  | `anyWaves` | `"anyWaves"` | Custom wave pattern |
882
1113
  | `abcd` | `"abcd"` | ABCD pattern |
883
1114
  | `xabcd` | `"xabcd"` | XABCD pattern |
1115
+ | `elliottWave` | `"elliottWave"` | Elliott Wave (5-wave cycle with numbered vertices) |
1116
+ | `gannFan` | `"gannFan"` | Gann Fan (1x1, 1x2, etc.) |
1117
+ | `fibRetracement` | `"fibRetracement"` | Fibonacci retracement levels |
1118
+ | `parallelChannel` | `"parallelChannel"` | Parallel channel (two parallel lines) |
1119
+ | `longPosition` | `"longPosition"` | Long position risk/reward (TP/SL with % labels) |
1120
+ | `shortPosition` | `"shortPosition"` | Short position risk/reward (TP/SL with % labels) |
1121
+ | `measure` | `"measure"` | Measure tool (price %, bar count, time delta) |
1122
+ | `brush` | `"brush"` | Freehand brush drawing (Bezier smoothing) |
1123
+ | `ray` | `"ray"` | Infinite ray from a point |
884
1124
 
885
1125
  ---
886
1126
 
@@ -974,7 +1214,7 @@ Array of all built-in drawing overlays — for direct access to the list:
974
1214
 
975
1215
  ```typescript
976
1216
  import { overlays } from "react-klinecharts-ui";
977
- // overlays === [arrow, circle, rect, triangle, ...] (17 items)
1217
+ // overlays === [arrow, circle, rect, triangle, ...] (26 items)
978
1218
  ```
979
1219
 
980
1220
  ---
@@ -1071,6 +1311,23 @@ export {
1071
1311
  export { useScreenshot, type UseScreenshotReturn };
1072
1312
  export { useFullscreen, type UseFullscreenReturn };
1073
1313
  export { useOrderLines, type UseOrderLinesReturn, type OrderLineOptions };
1314
+ export {
1315
+ useUndoRedo,
1316
+ type UseUndoRedoReturn,
1317
+ type UndoRedoAction,
1318
+ type UndoRedoActionType,
1319
+ };
1320
+ export {
1321
+ useLayoutManager,
1322
+ type UseLayoutManagerReturn,
1323
+ type LayoutEntry,
1324
+ type ChartLayoutState,
1325
+ };
1326
+ export {
1327
+ useScriptEditor,
1328
+ type UseScriptEditorReturn,
1329
+ type ScriptPlacement,
1330
+ };
1074
1331
 
1075
1332
  // Data
1076
1333
  export { DEFAULT_PERIODS, type TerminalPeriod };
@@ -1091,36 +1348,39 @@ export {
1091
1348
  export {
1092
1349
  CANDLE_TYPES,
1093
1350
  PRICE_AXIS_TYPES,
1351
+ YAXIS_POSITIONS,
1352
+ COMPARE_RULES,
1353
+ TOOLTIP_SHOW_RULES,
1094
1354
  type CandleTypeOption,
1095
1355
  type PriceAxisType,
1356
+ type YAxisPosition,
1357
+ type CompareRule,
1358
+ type TooltipShowRule,
1096
1359
  };
1097
1360
 
1098
1361
  // Utilities
1099
1362
  export { createDataLoader };
1363
+ export { default as TA } from "./utils/TA";
1100
1364
 
1101
- // Drawing overlays (all 17)
1365
+ // Drawing overlays (all 26)
1102
1366
  export {
1103
- arrow,
1104
- circle,
1105
- rect,
1106
- triangle,
1107
- parallelogram,
1108
- fibonacciCircle,
1109
- fibonacciSegment,
1110
- fibonacciSpiral,
1111
- fibonacciSpeedResistanceFan,
1112
- fibonacciExtension,
1113
- gannBox,
1114
- threeWaves,
1115
- fiveWaves,
1116
- eightWaves,
1117
- anyWaves,
1118
- abcd,
1119
- xabcd,
1367
+ arrow, circle, rect, triangle, parallelogram,
1368
+ fibonacciCircle, fibonacciSegment, fibonacciSpiral,
1369
+ fibonacciSpeedResistanceFan, fibonacciExtension,
1370
+ fibRetracement,
1371
+ gannBox, gannFan,
1372
+ threeWaves, fiveWaves, eightWaves, anyWaves, elliottWave,
1373
+ abcd, xabcd,
1374
+ parallelChannel, ray,
1375
+ longPosition, shortPosition,
1376
+ measure, brush,
1120
1377
  };
1121
1378
 
1379
+ // Custom indicator templates (all 11)
1380
+ export * from "./indicators";
1381
+
1122
1382
  // Extensions
1123
- export { registerExtensions, overlays, orderLine };
1383
+ export { registerExtensions, overlays, indicators, orderLine };
1124
1384
  export type {
1125
1385
  OrderLineExtendData,
1126
1386
  OrderLineLineStyle,