wickchart 0.4.0 → 1.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.
@@ -1,10 +1,10 @@
1
1
  /* ==========================================================================
2
- * <hab-feed> — declarative data feeds for <hab-chart>.
2
+ * <wick-feed> — declarative data feeds for <wick-chart>.
3
3
  *
4
- * <script type="module" src="https://unpkg.com/hab-view/feed"></script>
4
+ * <script type="module" src="https://unpkg.com/wickchart/feed"></script>
5
5
  *
6
- * <hab-feed for="chart" binance="BTCUSDT" tf="1h"></hab-feed>
7
- * <hab-chart id="chart" indicators="sma:20 volume"></hab-chart>
6
+ * <wick-feed for="chart" binance="BTCUSDT" tf="1h"></wick-feed>
7
+ * <wick-chart id="chart" indicators="sma:20 volume"></wick-chart>
8
8
  *
9
9
  * A fully live chart with zero JavaScript written. Sources:
10
10
  * binance="SYMBOL" live via WebSocket (REST klines + backfill; falls back
@@ -17,11 +17,12 @@
17
17
  * Attributes: for (chart id; auto-pairs with the first chart otherwise),
18
18
  * tf (1m…1w), limit (initial bars, default 500), live="false" to disable
19
19
  * streaming. Status is reflected in the `status` attribute and via
20
- * `hab-feed:status` events (loading / live / polling / fallback / loaded /
21
- * waiting / idle). `hab-feed:fallback` fires when a live source degrades.
20
+ * `wick-feed:status` events (loading / live / polling / fallback / loaded /
21
+ * waiting / idle). `wick-feed:fallback` fires when a live source degrades.
22
+ * (The 0.x event names `hab-feed:*` still fire as deprecated aliases.)
22
23
  * ========================================================================== */
23
24
 
24
- import './hab-chart.js';
25
+ import './wick-chart.js';
25
26
  import {
26
27
  genSynthetic,
27
28
  makeSynthStream,
@@ -35,7 +36,7 @@ const LIVE_TICK_MS = 650;
35
36
 
36
37
  const HTMLElementBase = typeof HTMLElement !== 'undefined' ? HTMLElement : class {};
37
38
 
38
- class HabFeed extends HTMLElementBase {
39
+ class WickFeed extends HTMLElementBase {
39
40
  static get observedAttributes() {
40
41
  return ['for', 'binance', 'demo', 'url', 'tf', 'limit', 'poll', 'live'];
41
42
  }
@@ -86,17 +87,24 @@ class HabFeed extends HTMLElementBase {
86
87
  _setStatus(status, detail) {
87
88
  if (!this.isConnected) return;
88
89
  this.setAttribute('status', status);
89
- this.dispatchEvent(new CustomEvent('hab-feed:status', { detail: { status, ...detail } }));
90
+ this._fire('status', { status, ...detail });
90
91
  }
91
92
 
92
- /** Resolve the target chart (by `for` id, else the first <hab-chart>). */
93
+ /** Dispatch `wick-feed:name` plus the deprecated `hab-feed:name` alias. */
94
+ _fire(name, detail) {
95
+ this.dispatchEvent(new CustomEvent('wick-feed:' + name, { detail }));
96
+ this.dispatchEvent(new CustomEvent('hab-feed:' + name, { detail }));
97
+ }
98
+
99
+ /** Resolve the target chart (by `for` id, else the first chart element —
100
+ * <wick-chart> or the deprecated <hab-chart>). */
93
101
  _resolveChart() {
94
102
  const id = this.getAttribute('for');
95
103
  if (id) {
96
104
  const el = document.getElementById(id);
97
- return el && el.tagName === 'HAB-CHART' ? el : null;
105
+ return el && (el.tagName === 'WICK-CHART' || el.tagName === 'HAB-CHART') ? el : null;
98
106
  }
99
- return document.querySelector('hab-chart');
107
+ return document.querySelector('wick-chart') || document.querySelector('hab-chart');
100
108
  }
101
109
 
102
110
  _restart() {
@@ -105,7 +113,7 @@ class HabFeed extends HTMLElementBase {
105
113
  if (!chart || typeof chart.setData !== 'function') {
106
114
  // chart not in the DOM yet (or not upgraded) — watch for it
107
115
  this._setStatus('waiting');
108
- customElements.whenDefined('hab-chart').then(() => {
116
+ customElements.whenDefined('wick-chart').then(() => {
109
117
  if (!this.isConnected) return;
110
118
  this._observer = this._observer || new MutationObserver(() => {
111
119
  const c = this._resolveChart();
@@ -208,9 +216,7 @@ class HabFeed extends HTMLElementBase {
208
216
  }
209
217
 
210
218
  _degrade(gen, chart, sym, tfId, limit, live, err) {
211
- this.dispatchEvent(
212
- new CustomEvent('hab-feed:fallback', { detail: { reason: err && err.message } })
213
- );
219
+ this._fire('fallback', { reason: err && err.message });
214
220
  this._synthetic(gen, chart, sym, tfId, limit, live, 'fallback');
215
221
  }
216
222
 
@@ -248,8 +254,17 @@ class HabFeed extends HTMLElementBase {
248
254
  }
249
255
  }
250
256
 
251
- if (typeof customElements !== 'undefined' && !customElements.get('hab-feed')) {
252
- customElements.define('hab-feed', HabFeed);
257
+ if (typeof customElements !== 'undefined') {
258
+ if (!customElements.get('wick-feed')) {
259
+ customElements.define('wick-feed', WickFeed);
260
+ }
261
+ // 0.x alias: same element under its old tag name (deprecated, removed in 2.0)
262
+ if (!customElements.get('hab-feed')) {
263
+ /** @deprecated use <wick-feed> */
264
+ class HabFeed extends WickFeed {}
265
+ customElements.define('hab-feed', HabFeed);
266
+ }
253
267
  }
254
268
 
255
- export default HabFeed;
269
+ export default WickFeed;
270
+ export { WickFeed };
package/types/core.d.ts CHANGED
@@ -512,7 +512,7 @@ export declare const BUILTIN_INDICATORS: Map<string, {
512
512
  /**
513
513
  * Parse an `indicators` attribute string against a registry.
514
514
  * Token: `name[:param[/param…]][@color]`, the `volume` keyword, and
515
- * HabScript blobs `expr:{…}` (overlay) / `pexpr:{…}` (separate pane).
515
+ * WickScript blobs `expr:{…}` (overlay) / `pexpr:{…}` (separate pane).
516
516
  * @param {string|null|undefined} str
517
517
  * @param {Map<string, IndicatorDef>} registry
518
518
  * @returns {{overlays: IndicatorEntry[], panes: IndicatorEntry[], volume: boolean, unknown: string[]}}
@@ -533,7 +533,7 @@ export declare function parseIndicators(str: string | null | undefined, registry
533
533
  */
534
534
  export declare function splitIndicatorTokens(str: string | null | undefined): string[];
535
535
  /**
536
- * Compile a HabScript expression. Throws a descriptive error on any syntax
536
+ * Compile a WickScript expression. Throws a descriptive error on any syntax
537
537
  * or semantic problem — never evaluates strings at runtime.
538
538
  * @param {string} src
539
539
  * @returns {{src: string, ast: object}}
@@ -553,7 +553,7 @@ export declare function evalScript(compiled: {
553
553
  ast: object;
554
554
  } | string, bars: Bar[]): number[];
555
555
  /**
556
- * Build an indicator definition from a HabScript expression — used inline by
556
+ * Build an indicator definition from a WickScript expression — used inline by
557
557
  * `indicators="expr:{…}"` / `pexpr:{…}"`, or register it under a name:
558
558
  * `HabChart.registerIndicator('myspread', scriptIndicator('close - ema(close,21)'))`.
559
559
  * @param {string} src
@@ -585,6 +585,28 @@ export declare function checkAlertCross(alert: {
585
585
  price: number;
586
586
  direction?: 'above' | 'below' | 'cross';
587
587
  }, prevPrice: number, price: number): boolean;
588
+ /**
589
+ * Boolean truth series for a WickScript predicate: any numeric expression
590
+ * where nonzero & finite counts as true (NaN / 0 / ±Infinity → false).
591
+ * Powers scripted alerts — `addAlert({ when: 'crossup(close, sma(close,50))' })`.
592
+ * @param {object|string} compiled compiled predicate (or raw source)
593
+ * @param {Bar[]} bars
594
+ * @returns {boolean[]}
595
+ */
596
+ export declare function predicateTrueSeries(compiled: object | string, bars: Bar[]): boolean[];
597
+ /**
598
+ * Edge-triggered step for a scripted alert. `armed` starts true; a rising
599
+ * edge (false → true) fires once and disarms; a true → false transition
600
+ * re-arms, so `once: false` alerts can fire again on the next edge while
601
+ * `once: true` alerts are removed after their first fire.
602
+ * @param {boolean} armed
603
+ * @param {boolean} curTrue
604
+ * @returns {{ fire: boolean, armed: boolean }}
605
+ */
606
+ export declare function scriptAlertStep(armed: boolean, curTrue: boolean): {
607
+ fire: boolean;
608
+ armed: boolean;
609
+ };
588
610
  /**
589
611
  * Statistics over a visible slice of bars.
590
612
  * @param {Bar[]} bars
@@ -648,6 +670,83 @@ export declare function parseVolShading(val: string | null | undefined): {
648
670
  p2: number;
649
671
  period: number;
650
672
  };
673
+ /**
674
+ * Index of the last bar whose time is <= `t` (binary search). Clamps to
675
+ * [0, n-1]: a time before the first bar → 0, past the last bar → n-1.
676
+ * Empty bars or a non-numeric time → null.
677
+ * @param {object[]} bars normalized bar objects
678
+ * @param {number} t timestamp in ms or s
679
+ * @returns {number|null}
680
+ */
681
+ export declare function barIndexForTime(bars: object[], t: number): number | null;
682
+ /**
683
+ * Validate & normalize server-side overlay definitions. Overlays are data
684
+ * from an API, so invalid entries are silently dropped — never thrown.
685
+ *
686
+ * zone: { type:'zone', from?: time|null, to?: time|null, priceFrom, priceTo,
687
+ * color?, alpha?, border?, label?, id? } — a time×price rectangle.
688
+ * `from`/`to` omitted (or null) anchor to the left/right chart edge;
689
+ * a zone with no `to` extends into future space past the last bar.
690
+ * level: { type:'level', price, from?, to?, color?, width?, dash?, label?, id? }
691
+ * — a horizontal price line, full width by default.
692
+ *
693
+ * Colors go through safeColor(); `alpha` clamps to [0.02, 0.8] (default 0.22).
694
+ * @param {any} list
695
+ * @returns {object[]} normalized overlays (possibly empty)
696
+ */
697
+ export declare function normalizeOverlays(list: any): object[];
698
+ /**
699
+ * Resolve an overlay color against the active palette: 'up'/'down'/'accent'
700
+ * map to theme colors, anything else passes through safeColor(), and invalid
701
+ * or missing values fall back to the accent color.
702
+ * @param {any} raw
703
+ * @param {object} pal active theme palette
704
+ * @returns {string} a concrete CSS color
705
+ */
706
+ export declare function resolveOverlayColor(raw: any, pal: object): string;
707
+ /**
708
+ * σ-cone projection from realized per-bar volatility: price bands widening
709
+ * with √h (GBM-style, exp(±z·σ·√h)) over `horizon` future bars.
710
+ * @param {number} lastClose anchor price (bar 0)
711
+ * @param {number} volPerBar per-bar stddev of log returns (from calcRealizedVol)
712
+ * @param {number} horizon future bars (clamped 1–500, default 48)
713
+ * @param {number[]} [levels] σ multipliers, e.g. [1, 2] (each clamped to 0–5)
714
+ * @returns {{horizon: number, levels: number[], bands: Record<string, {up: number[], down: number[]}>}}
715
+ * bands[z].up/.down are arrays indexed by h = 0…horizon ([0] === lastClose)
716
+ */
717
+ export declare function calcVolCone(lastClose: number, volPerBar: number, horizon: number, levels?: number[]): {
718
+ horizon: number;
719
+ levels: number[];
720
+ bands: Record<string, {
721
+ up: number[];
722
+ down: number[];
723
+ }>;
724
+ };
725
+ /**
726
+ * Validate a scenario spec: a ghost path of future prices (bars or API data)
727
+ * plus optional cone settings. Invalid entries are dropped, never thrown.
728
+ *
729
+ * { path: [64000, 65500, {price: 68000}], // future bars 1..N
730
+ * horizon: 48, // alternative/additional: cone-only projection
731
+ * cone: true, // σ-bands from realized vol (default true)
732
+ * levels: [1, 2], // σ multipliers (default [1, 2])
733
+ * color?, label? } // palette keys up|down|accent or safe CSS colors
734
+ *
735
+ * @param {any} spec
736
+ * @returns {null|{path: {h:number, price:number}[], horizon: number,
737
+ * cone: boolean, levels: number[], color: string|null, label: string}}
738
+ */
739
+ export declare function normalizeScenario(spec: any): null | {
740
+ path: {
741
+ h: number;
742
+ price: number;
743
+ }[];
744
+ horizon: number;
745
+ cone: boolean;
746
+ levels: number[];
747
+ color: string | null;
748
+ label: string;
749
+ };
651
750
  export declare const tfLabelOf: (dtMs: any) => string;
652
751
  /**
653
752
  * Compact, LLM-friendly summary of a bar window: structured fields plus a
@@ -677,3 +776,110 @@ export declare function encodeStateQuery(state: ChartState | null): string;
677
776
  * @returns {ChartState}
678
777
  */
679
778
  export declare function decodeStateQuery(str: string): ChartState;
779
+ /**
780
+ * Tool manifest for LLM/agent control of a chart. Tools map 1:1 onto the
781
+ * public element API; every op through applyChartOps is validated before it
782
+ * touches the chart (LLM output is untrusted input).
783
+ */
784
+ export declare const AI_TOOLS: ({
785
+ tool: string;
786
+ description: string;
787
+ args: {
788
+ indicators?: undefined;
789
+ overlays?: undefined;
790
+ from?: undefined;
791
+ to?: undefined;
792
+ type?: undefined;
793
+ enabled?: undefined;
794
+ low?: undefined;
795
+ high?: undefined;
796
+ };
797
+ } | {
798
+ tool: string;
799
+ description: string;
800
+ args: {
801
+ indicators: string;
802
+ overlays?: undefined;
803
+ from?: undefined;
804
+ to?: undefined;
805
+ type?: undefined;
806
+ enabled?: undefined;
807
+ low?: undefined;
808
+ high?: undefined;
809
+ };
810
+ } | {
811
+ tool: string;
812
+ description: string;
813
+ args: {
814
+ indicators?: undefined;
815
+ overlays: string;
816
+ from?: undefined;
817
+ to?: undefined;
818
+ type?: undefined;
819
+ enabled?: undefined;
820
+ low?: undefined;
821
+ high?: undefined;
822
+ };
823
+ } | {
824
+ tool: string;
825
+ description: string;
826
+ args: {
827
+ indicators?: undefined;
828
+ overlays?: undefined;
829
+ from: string;
830
+ to: string;
831
+ type?: undefined;
832
+ enabled?: undefined;
833
+ low?: undefined;
834
+ high?: undefined;
835
+ };
836
+ } | {
837
+ tool: string;
838
+ description: string;
839
+ args: {
840
+ indicators?: undefined;
841
+ overlays?: undefined;
842
+ from?: undefined;
843
+ to?: undefined;
844
+ type: string;
845
+ enabled?: undefined;
846
+ low?: undefined;
847
+ high?: undefined;
848
+ };
849
+ } | {
850
+ tool: string;
851
+ description: string;
852
+ args: {
853
+ indicators?: undefined;
854
+ overlays?: undefined;
855
+ from?: undefined;
856
+ to?: undefined;
857
+ type?: undefined;
858
+ enabled: string;
859
+ low: string;
860
+ high: string;
861
+ };
862
+ })[];
863
+ /**
864
+ * Compact system prompt for agent control: paste into any LLM alongside the
865
+ * tool manifest. The model answers with a JSON array of {tool, args} ops.
866
+ * @returns {string}
867
+ */
868
+ export declare function aiPromptText(): string;
869
+ /**
870
+ * Validate + apply a list of {tool, args} ops (typically LLM output) to a
871
+ * chart-like target. Ops are whitelisted and their args validated — an op
872
+ * never throws; it returns {ok: false, error} instead so the agent can
873
+ * self-correct. Target contract: getDataWindow(), setAttribute(k, v),
874
+ * setOverlays(list), clearOverlays(), addAlert(a), setVisibleRange(r),
875
+ * fit(), and (static) _registry() for indicator name checks.
876
+ * @param {object} target chart element (or test double)
877
+ * @param {any} ops
878
+ * @returns {Array<{ok: boolean, tool?: string, result?: any, error?: string}>}
879
+ */
880
+ export declare function applyChartOps(target: object, ops: any): Array<{
881
+ ok: boolean;
882
+ tool?: string;
883
+ result?: any;
884
+ error?: string;
885
+ }>;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Map an event shorthand to the dispatched event name.
3
+ * "range" / "wick:range" → "wick:range" (the 0.x "hab:" prefix is no longer emitted).
4
+ * @param {string} name
5
+ * @returns {string}
6
+ */
7
+ export declare const toWickEventName: (name: string) => string;
8
+ /**
9
+ * camelCase prop name → kebab-case attribute name ("volShading" → "vol-shading").
10
+ * @param {string} key
11
+ * @returns {string}
12
+ */
13
+ export declare const toAttrName: (key: string) => string;
14
+ /**
15
+ * Split React props into chart attrs / event handlers / DOM passthrough /
16
+ * the data array / the overlays array.
17
+ * @param {object} props
18
+ * @returns {{ attrs: object, events: Record<string, Function>, dom: object, data: any, overlays: any }}
19
+ */
20
+ export declare function splitChartProps(props: object): {
21
+ attrs: object;
22
+ events: Record<string, Function>;
23
+ dom: object;
24
+ data: any;
25
+ overlays: any;
26
+ };
27
+ /**
28
+ * Apply split props to a chart element. Every write is guarded so re-running
29
+ * with identical values is a no-op (attributes compared as strings, `data`
30
+ * and `overlays` compared by identity — passing a fresh array is what
31
+ * triggers a redraw).
32
+ * @param {HTMLElement} el
33
+ * @param {{ attrs?: object, data?: any, overlays?: any }} split
34
+ */
35
+ export declare function applyChartProps(el: HTMLElement, split: {
36
+ attrs?: object;
37
+ data?: any;
38
+ overlays?: any;
39
+ }): void;
40
+ /**
41
+ * Full control hook: renders nothing — attach the returned ref to your own
42
+ * <wick-chart> element and pass the same options you would give the component.
43
+ *
44
+ * const { ref, chart } = useWickChart({ data: bars, indicators: 'sma:20', onRange });
45
+ * return <wick-chart ref={ref} style={{ height: 420 }} />;
46
+ * // chart.getDataWindow() etc. once mounted
47
+ *
48
+ * @param {object} [options] any <wick-chart> attribute, plus `data`, `events`
49
+ * and `onXxx`-style handlers (see splitChartProps).
50
+ * @returns {{ ref: (node: any) => void, chart: any }} `chart` is the element
51
+ * instance (or null before mount) for the imperative API.
52
+ */
53
+ export declare function useWickChart(options?: object): {
54
+ ref: (node: any) => void;
55
+ chart: any;
56
+ };
57
+ /**
58
+ * Drop-in React component for <wick-chart>. Attributes ride through
59
+ * createElement (so they exist at first paint and in SSR output) while the
60
+ * hook keeps them in sync on updates; `data` and event handlers never touch
61
+ * React's prop pipeline. Works the same on React 16.8 → 19.
62
+ */
63
+ export declare const WickChart: import("react").ForwardRefExoticComponent<import("react").RefAttributes<any>>;
64
+ export default WickChart;
@@ -0,0 +1,3 @@
1
+ import './wick-chart.js';
2
+ export { WickChart, useWickChart, splitChartProps, applyChartProps, toWickEventName, toAttrName, } from './react-core.js';
3
+ export { default } from './react-core.js';