@supersolutions/super-chart-core 0.0.0 → 0.1.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.
@@ -0,0 +1,2299 @@
1
+ /**
2
+ * The TA core: pure series math shared by SuperScript and Super Chart's own
3
+ * indicators. Series in, series out; no klinecharts, no DOM.
4
+ *
5
+ * One documented convention, TradingView's:
6
+ * - EMA starts from the average of its first `len` values and is null before
7
+ * that (it used to start from the first value in SuperScript).
8
+ * - RMA (Wilder) starts the same way; RSI is Wilder's, 100 when the average
9
+ * loss is 0 and 0 when the average gain is 0.
10
+ * - Standard deviation is the population one.
11
+ * - MACD is { dif, dea, hist } with hist = dif - dea (TradingView), not
12
+ * klinecharts' (dif - dea) * 2; `histMultiplier: 2` gives the latter.
13
+ *
14
+ * Nulls: a windowed kernel (sum, sma, wma, stdev, dev, highest, lowest,
15
+ * linreg, correlation) outputs a value only when its whole window holds no
16
+ * null, so a null restarts the window. Recursive kernels (ema, rma) skip nulls.
17
+ * A length that is not a positive integer yields an all-null series.
18
+ *
19
+ * Every windowed kernel is O(n): no per-bar slice, spread or allocation. Sums
20
+ * are compensated (Neumaier) and re-seeded from the window every `len` bars,
21
+ * stdev is a sliding Welford re-seeded the same way, and highest/lowest use a
22
+ * monotonic deque. A window that holds NaN or an infinity is computed exactly
23
+ * the way the old per-window code did, so those values do not poison the
24
+ * running state.
25
+ *
26
+ * Part of Super Chart.
27
+ */
28
+ export type Series = Array<number | null>;
29
+ declare function isLength(len: number): boolean;
30
+ declare function sum(src: Series, len: number): Series;
31
+ declare function sma(src: Series, len: number): Series;
32
+ declare function wma(src: Series, len: number): Series;
33
+ declare function hma(src: Series, len: number): Series;
34
+ declare function vwma(src: Series, volume: Series, len: number): Series;
35
+ declare function ema(src: Series, len: number): Series;
36
+ declare function rma(src: Series, len: number): Series;
37
+ declare function rsi(src: Series, len: number): Series;
38
+ export interface MacdResult {
39
+ dif: Series;
40
+ dea: Series;
41
+ hist: Series;
42
+ }
43
+ declare function macd(src: Series, fast?: number, slow?: number, signal?: number, options?: {
44
+ histMultiplier?: number;
45
+ }): MacdResult;
46
+ declare function stdev(src: Series, len: number): Series;
47
+ declare function dev(src: Series, len: number): Series;
48
+ declare function bollinger(src: Series, len: number, mult?: number): {
49
+ basis: Series;
50
+ upper: Series;
51
+ lower: Series;
52
+ };
53
+ declare function highest(src: Series, len: number): Series;
54
+ declare function lowest(src: Series, len: number): Series;
55
+ declare function linreg(src: Series, len: number, offset?: number): Series;
56
+ declare function correlation(a: Series, b: Series, len: number): Series;
57
+ declare function change(src: Series, len?: number): Series;
58
+ declare function mom(src: Series, len: number): Series;
59
+ declare function roc(src: Series, len: number): Series;
60
+ declare function crossover(a: Series, b: Series): Series;
61
+ declare function crossunder(a: Series, b: Series): Series;
62
+ declare function cross(a: Series, b: Series): Series;
63
+ declare function cum(src: Series): Series;
64
+ declare function barssince(cond: Series): Series;
65
+ declare function valuewhen(cond: Series, src: Series, occurrence?: number): Series;
66
+ declare function pivot(src: Series, left: number, right: number, kind: "high" | "low"): Series;
67
+ declare function trueRange(high: Series, low: Series, close: Series): Series;
68
+ declare function atr(high: Series, low: Series, close: Series, len: number): Series;
69
+ declare function obv(close: Series, volume: Series): Series;
70
+ declare function vwap(high: Series, low: Series, close: Series, volume: Series): Series;
71
+ declare function cci(high: Series, low: Series, close: Series, len: number): Series;
72
+ declare function mfi(high: Series, low: Series, close: Series, volume: Series, len: number): Series;
73
+ declare function stochK(high: Series, low: Series, close: Series, len: number): Series;
74
+ declare function sar(high: Series, low: Series, start?: number, inc?: number, max?: number): Series;
75
+ declare function stoch(src: Series, len: number): Series;
76
+ declare function stochRsi(src: Series, rsiLen: number, stochLen: number, kLen: number, dLen: number): {
77
+ k: Series;
78
+ d: Series;
79
+ };
80
+ declare function bbPercent(src: Series, len: number, mult?: number): Series;
81
+ export interface Bands {
82
+ basis: Series;
83
+ upper: Series;
84
+ lower: Series;
85
+ }
86
+ declare function keltner(high: Series, low: Series, close: Series, len?: number, mult?: number, atrLen?: number): Bands;
87
+ declare function donchian(high: Series, low: Series, len?: number): Bands;
88
+ declare function atrBands(high: Series, low: Series, close: Series, len?: number, mult?: number): Bands;
89
+ export interface SupertrendResult {
90
+ /** The SuperTrend line: the lower band in an uptrend, the upper band in a downtrend. */
91
+ line: Series;
92
+ /** 1 in an uptrend, -1 in a downtrend (TradingView's `direction` has the opposite sign). */
93
+ trend: Series;
94
+ }
95
+ declare function supertrend(high: Series, low: Series, close: Series, len?: number, factor?: number): SupertrendResult;
96
+ export interface IchimokuResult {
97
+ /** Tenkan-sen: the midpoint of the last `conversion` bars' range. */
98
+ conversion: Series;
99
+ /** Kijun-sen: the midpoint of the last `base` bars' range. */
100
+ base: Series;
101
+ /** Senkou span A at each bar: (conversion + base) / 2 of `displacement - 1` bars earlier. */
102
+ spanA: Series;
103
+ /** Senkou span B at each bar: the `spanB`-bar midpoint of `displacement - 1` bars earlier. */
104
+ spanB: Series;
105
+ /** Chikou span at each bar: the close of `displacement - 1` bars later (null for the last ones). */
106
+ lagging: Series;
107
+ /** Span A and B for the `displacement - 1` bars after the last one (the projected cloud). */
108
+ futureA: Series;
109
+ futureB: Series;
110
+ }
111
+ declare function ichimoku(high: Series, low: Series, close: Series, conversion?: number, base?: number, spanBLen?: number, displacement?: number): IchimokuResult;
112
+ export interface AnchoredVwapResult {
113
+ vwap: Series;
114
+ /** The volume-weighted standard deviation of hlc3 around the VWAP, for the bands. */
115
+ stdev: Series;
116
+ }
117
+ declare function anchoredVwap(high: Series, low: Series, close: Series, volume: Series, periods: ReadonlyArray<number | null>, skipFirst?: boolean): AnchoredVwapResult;
118
+ /** Platform-neutral chart data. Extracted for Web and React Native, 2026-10-29. */
119
+ export interface MarketBar {
120
+ timestamp: number;
121
+ open: number;
122
+ high: number;
123
+ low: number;
124
+ close: number;
125
+ volume?: number;
126
+ turnover?: number;
127
+ /** Preserve the Web feed extension-field contract; OHLCV fields stay numeric. */
128
+ [key: string]: any;
129
+ }
130
+ /** Nearest timestamp in ascending unique bars; ties select the earlier candle. */
131
+ export declare function nearestBarIndex(bars: ReadonlyArray<Pick<MarketBar, "timestamp">>, timestamp: number): number | null;
132
+ /** Read only the field an indicator needs; no unused OHLCV arrays. */
133
+ export declare function priceSeries(bars: readonly MarketBar[], field: "open" | "high" | "low" | "close" | "volume"): Series;
134
+ /** 1: timestamps are milliseconds. 1000: they are seconds (multiply by 1000). */
135
+ export type TimeUnit = 1 | 1000;
136
+ /** What normalizeBars had to fix, so the caller can warn once per kind. */
137
+ export interface BarIssues {
138
+ /** The input was not an array (it is treated as []). */
139
+ notArray: boolean;
140
+ /** Bars dropped for a missing or non-finite timestamp, open, high, low or close. */
141
+ dropped: number;
142
+ /** Bars dropped because a later bar had the same timestamp (the last one wins). */
143
+ duplicates: number;
144
+ /** The input was not in ascending order. */
145
+ unsorted: boolean;
146
+ /** Timestamps were seconds and were converted to milliseconds. */
147
+ seconds: boolean;
148
+ /** A value was a numeric string (or other non-number) and was converted. */
149
+ coerced: boolean;
150
+ }
151
+ export interface NormalizedBars {
152
+ bars: MarketBar[];
153
+ unit: TimeUnit;
154
+ issues: BarIssues;
155
+ }
156
+ /** True when normalizeBars changed anything. */
157
+ export declare function hasIssues(issues: BarIssues): boolean;
158
+ /**
159
+ * The unit a batch's timestamps are in, from its largest finite timestamp.
160
+ * Undefined for a batch with no usable timestamp.
161
+ */
162
+ export declare function decideUnit(list: unknown): TimeUnit | undefined;
163
+ /**
164
+ * One bar made safe to draw, or null when it cannot be (a required field is
165
+ * missing or not a finite number). Extra fields are kept. volume and turnover
166
+ * are optional: undefined and null stay as they are, other non-finite values
167
+ * become undefined; a bar is never dropped for its volume.
168
+ */
169
+ export declare function normalizeBar(bar: unknown, unit: TimeUnit, issues?: BarIssues): MarketBar | null;
170
+ /**
171
+ * Bars safe to hand to klinecharts: strictly ascending millisecond timestamps
172
+ * (a later duplicate replaces an earlier one), finite OHLC (numeric strings
173
+ * are converted), optional volume/turnover.
174
+ *
175
+ * `unit` is the time unit decided earlier for this chart (the first history
176
+ * batch decides it, and later pages and ticks reuse it, so a seconds feed
177
+ * whose ticks are also seconds keeps working). Without it, the unit is decided
178
+ * from this batch.
179
+ *
180
+ * Input that needs no change is returned as the same array.
181
+ */
182
+ export declare function normalizeBars(list: unknown, unit?: TimeUnit): NormalizedBars;
183
+ /**
184
+ * A scroll-back page reduced to what fits before the loaded data: bars
185
+ * strictly older than `firstTs` (the chart's first bar). Feeds that ignore the
186
+ * requested range, or treat `to` as inclusive, would otherwise prepend copies.
187
+ * Expects normalized (ascending, unique) bars.
188
+ */
189
+ export declare function olderThan(bars: readonly MarketBar[], firstTs: number | undefined): MarketBar[];
190
+ /** Anything with the four OHLC fields (KLineData satisfies this). */
191
+ export interface OhlcLike {
192
+ open: number;
193
+ high: number;
194
+ low: number;
195
+ close: number;
196
+ }
197
+ /**
198
+ * A precision from `bars`' own OHLC range: `ceil(-log10(minPositive)) + 3`
199
+ * (BONK's ~0.00002 gives 8, 0.64 gives 4, 64000 gives 2), clamped to [2, 10],
200
+ * then raised while the full high/low range is still narrower than one tick
201
+ * at that precision. 2 for no bars, or none with a finite positive OHLC value
202
+ * (an empty or all-zero series).
203
+ */
204
+ export declare function derivePrecision(bars: readonly OhlcLike[]): number;
205
+ /**
206
+ * What to pass klinecharts' setPriceVolumePrecision: `symbolPrecision` as
207
+ * given when it is a number (an explicit value always wins over the data);
208
+ * `derivePrecision(bars)` when it is 'auto' or omitted.
209
+ */
210
+ export declare function resolvePricePrecision(symbolPrecision: number | "auto" | undefined, bars: readonly OhlcLike[]): number;
211
+ /** Timers the coalescer uses; injected in tests. */
212
+ export interface FrameScheduler {
213
+ now: () => number;
214
+ setTimeout: (fn: () => void, ms: number) => unknown;
215
+ clearTimeout: (handle: unknown) => void;
216
+ /** Undefined where there is no requestAnimationFrame (then timeouts are used). */
217
+ requestFrame?: (fn: () => void) => unknown;
218
+ cancelFrame?: (handle: unknown) => void;
219
+ /** True while the page is hidden: frames do not fire then, so timeouts are used. */
220
+ hidden: () => boolean;
221
+ }
222
+ export declare class TickCoalescer {
223
+ private readonly _apply;
224
+ private readonly _sched;
225
+ private readonly _throttleMs;
226
+ private _pending;
227
+ private _frame;
228
+ private _timer;
229
+ private _lastFlush;
230
+ /**
231
+ * @param apply called with the pending bars, oldest first, once per flush
232
+ * @param throttleMs 0: once per frame. More: at most once per that many ms
233
+ * (adds up to that much latency).
234
+ */
235
+ constructor(_apply: (bars: MarketBar[]) => void, _sched: FrameScheduler, _throttleMs?: number);
236
+ /** The newest pending bar's timestamp, if any. */
237
+ lastTs(): number | undefined;
238
+ get size(): number;
239
+ /**
240
+ * Queue a bar. The same timestamp as the newest pending bar replaces it; an
241
+ * older one is dropped (klinecharts would ignore it too) and false returned.
242
+ */
243
+ push(bar: MarketBar): boolean;
244
+ /** Apply what is pending now. */
245
+ flush(): void;
246
+ /** Drop what is pending without applying it. */
247
+ cancel(): void;
248
+ /**
249
+ * The page was hidden or shown. A frame requested while visible never fires
250
+ * once the page is hidden, so a pending flush moves to a timeout (and back).
251
+ */
252
+ visibilityChanged(): void;
253
+ private _schedule;
254
+ private _cancelHandles;
255
+ }
256
+ /** Extracted from SupWallet Mobile model.ts at de693554a; renderer/gesture independent. */
257
+ /** Pure measured-dp chart geometry, scaling and hit testing. Hosts own feeds. */
258
+ export type ChartX = string | number;
259
+ export type ChartAxis = "left" | "right";
260
+ export interface FinancialSeries {
261
+ id: string;
262
+ name: string;
263
+ type: "line" | "area" | "bar" | "scatter";
264
+ points: ReadonlyArray<readonly [
265
+ ChartX,
266
+ number
267
+ ]>;
268
+ color?: string;
269
+ axis?: ChartAxis;
270
+ }
271
+ export interface FinancialCandle {
272
+ t: ChartX;
273
+ o: number;
274
+ h: number;
275
+ l: number;
276
+ c: number;
277
+ v?: number;
278
+ }
279
+ export interface FinancialAnnotation {
280
+ id: string;
281
+ type: "hline" | "vline" | "band" | "marker";
282
+ value: ChartX;
283
+ to?: ChartX;
284
+ label?: string;
285
+ color?: string;
286
+ axis?: ChartAxis;
287
+ }
288
+ export interface FinancialChartData {
289
+ xType: "category" | "number" | "time";
290
+ series?: readonly FinancialSeries[];
291
+ candles?: readonly FinancialCandle[];
292
+ annotations?: readonly FinancialAnnotation[];
293
+ scale?: "auto" | "zero" | "tight";
294
+ stacked?: boolean;
295
+ }
296
+ export interface FinancialViewport {
297
+ start: number;
298
+ end: number;
299
+ }
300
+ export interface FinancialGeometry {
301
+ width: number;
302
+ height: number;
303
+ left: number;
304
+ right: number;
305
+ top: number;
306
+ bottom: number;
307
+ plotWidth: number;
308
+ plotHeight: number;
309
+ }
310
+ export interface ChartPoint {
311
+ x: number;
312
+ y: number;
313
+ value: number;
314
+ key: ChartX;
315
+ index: number;
316
+ }
317
+ export type ChartCandlePoint = FinancialCandle & {
318
+ x: number;
319
+ bodyTop: number;
320
+ bodyBottom: number;
321
+ wickTop: number;
322
+ wickBottom: number;
323
+ index: number;
324
+ };
325
+ export interface FinancialChartModel {
326
+ geometry: FinancialGeometry;
327
+ min: number;
328
+ max: number;
329
+ yTicks: number[];
330
+ rightMin: number;
331
+ rightMax: number;
332
+ rightTicks: number[];
333
+ hasRightAxis: boolean;
334
+ xKeys: ChartX[];
335
+ allKeys: ChartX[];
336
+ start: number;
337
+ end: number;
338
+ xPositions: number[];
339
+ xTickIndices: number[];
340
+ plottedSeries: Array<{
341
+ source: FinancialSeries;
342
+ points: ChartPoint[];
343
+ }>;
344
+ plottedCandles: ChartCandlePoint[];
345
+ x: (key: ChartX, index: number) => number;
346
+ y: (value: number, axis?: ChartAxis) => number;
347
+ }
348
+ /**
349
+ * What the x axis IS, when the caller did not say.
350
+ *
351
+ * Both adapters guessed, and they guessed differently. `ChartCard` read
352
+ * `xKind ?? (bar ? 'category' : 'number')`; `ChartCardView` sniffed the points
353
+ * for a string. A legacy line chart carrying category labels (`'Mon'`) and
354
+ * no `xKind` therefore resolved to `'number'` — and `chartKeys` drops every
355
+ * key whose `numericX` is not finite, so the card rendered "No chart data"
356
+ * over a complete series. One resolver, so the two cannot drift again.
357
+ *
358
+ * The order is what the data can actually prove:
359
+ *
360
+ * 1. A DECLARED type always wins — it is the only statement of intent here.
361
+ * 2. Candles are stamped in time.
362
+ * 3. A string x is a label. Not "a string that fails to parse as a number":
363
+ * `Date.parse` is generous enough to turn some labels into a timestamp, and
364
+ * a plot placed by an accidental date is worse than one placed by order.
365
+ * 4. All-bar series have no continuum to sit on, so they sit in slots.
366
+ * 5. Otherwise the keys are numbers and belong on a numeric line.
367
+ */
368
+ export declare function resolveXType(declared: FinancialChartData["xType"] | undefined, source: {
369
+ candles?: readonly unknown[];
370
+ series?: ReadonlyArray<{
371
+ type?: string;
372
+ points: ReadonlyArray<readonly [
373
+ ChartX,
374
+ number
375
+ ]>;
376
+ }>;
377
+ }): FinancialChartData["xType"];
378
+ export declare function financialGeometry(width: number, height: number, axisGutter?: number, rightGutter?: number): FinancialGeometry;
379
+ export declare function chartKeys(data: FinancialChartData): ChartX[];
380
+ export declare function buildFinancialChartModel(data: FinancialChartData, width: number, height: number, axisGutter?: number, viewport?: FinancialViewport, rightGutter?: number): FinancialChartModel;
381
+ export declare function nearestChartIndex(model: FinancialChartModel, touchX: number): number | null;
382
+ export declare function valueAtChartIndex(series: FinancialSeries, data: FinancialChartData, model: FinancialChartModel, index: number): number | null;
383
+ /** Extracted native viewport state transitions; no React Native, DOM or gestures. */
384
+ export interface Viewport {
385
+ i0: number;
386
+ i1: number;
387
+ }
388
+ export declare const MIN_BARS = 12;
389
+ /** Optional host limits. Native callers retain the historical 12-to-history range. */
390
+ export interface ViewportLimits {
391
+ minBars?: number;
392
+ maxBars?: number;
393
+ rightPaddingBars?: number;
394
+ }
395
+ export declare function resolveViewportLimits(limits?: ViewportLimits): Required<ViewportLimits>;
396
+ /**
397
+ * The opening window.
398
+ *
399
+ * At 200 bars in a 340pt plot a candle body is 1.1pt wide however tall the
400
+ * viewer is — the reason the old chart read as a smear. At 90 it is ~2.5pt and
401
+ * has a body you can see. The rail shows there is more to the left.
402
+ */
403
+ export declare const DEFAULT_BARS = 90;
404
+ /** A phone opens with distinct candle bodies; a tablet can show more. */
405
+ export declare const openingBars: (plotWidth: number) => number;
406
+ export declare function fullViewport(n: number): Viewport;
407
+ export declare function defaultViewport(n: number, want?: number, limits?: ViewportLimits): Viewport;
408
+ export declare function clampViewport(v: Viewport, n: number, limits?: ViewportLimits): Viewport;
409
+ export declare function viewportSpan(v: Viewport): number;
410
+ /**
411
+ * Zoom about a fraction of the current window.
412
+ *
413
+ * `factor > 1` zooms IN (fewer bars). The bar under `anchorFrac` stays under it,
414
+ * which is what makes a pinch feel attached to the finger rather than to the
415
+ * chart's centre.
416
+ */
417
+ export declare function zoomViewport(v: Viewport, n: number, factor: number, anchorFrac: number, limits?: ViewportLimits): Viewport;
418
+ /** Shift the window by whole bars. At either end this is a no-op, by design. */
419
+ export declare function panViewport(v: Viewport, n: number, deltaBars: number, limits?: ViewportLimits): Viewport;
420
+ /** Horizontal drag distance, in bars of the current window. */
421
+ export declare function pxToBars(dxPx: number, v: Viewport, g: {
422
+ plotW: number;
423
+ }): number;
424
+ /** The filled part of the range rail: where this window sits in the whole series. */
425
+ export declare function railSegment(v: Viewport, n: number, width: number): {
426
+ x: number;
427
+ w: number;
428
+ };
429
+ /** Responsive host bounds in CSS pixels; never changes data or a view by itself. */
430
+ export declare function viewportLimitsForWidth(plotWidth: number, options?: ViewportLimits & {
431
+ minCandleSpacing?: number;
432
+ maxCandleSpacing?: number;
433
+ }): Required<ViewportLimits>;
434
+ export type NativeCandle = FinancialCandle;
435
+ declare function indicatorSeries(candles: readonly NativeCandle[], indicators?: string[]): {
436
+ values: Array<number | null>;
437
+ dash?: string | undefined;
438
+ tag: string;
439
+ }[];
440
+ /** Small renderer-owned data sink. The core owns no canvas or native view. */
441
+ export interface ChartDataPort<Bar = MarketBar> {
442
+ applyNewData: (data: Bar[], more?: boolean) => void;
443
+ /** Already-normalized input; the sink must still validate and take ownership. */
444
+ applyNormalizedData?: (data: Bar[], more?: boolean) => void;
445
+ /** Remove a visible replay suffix only when the expected current head matches. */
446
+ truncateData?: (length: number, expectedLength: number, expectedLastTimestamp: number) => boolean;
447
+ applyMoreData: (data: Bar[], more?: boolean) => void;
448
+ updateData: (data: Bar) => void;
449
+ /** Optional ordered tail batch; equivalent to updateData in order, with one render notification. */
450
+ updateDataBatch?: (data: Bar[], more?: boolean) => void;
451
+ getDataList: () => Bar[];
452
+ /** Optional O(1) tail read so feed routing need not request a full history snapshot per tick. */
453
+ getLastTimestamp?: () => number | undefined;
454
+ /** Release a host's older-page lock when the loader cancels that page or retry. */
455
+ cancelHistoryLoad?: () => void;
456
+ loadMore?: (callback: (timestamp: number | null) => void) => void;
457
+ setLoadDataCallback?: (callback: (request: HistoryLoadRequest<Bar>) => void) => void;
458
+ }
459
+ export interface HistoryLoadRequest<Bar = MarketBar> {
460
+ type: string;
461
+ data: Bar | null;
462
+ callback: (data: Bar[], more?: boolean) => void;
463
+ }
464
+ export type Timespan = "second" | "minute" | "hour" | "day" | "week" | "month" | "year" | (string & {});
465
+ export interface SymbolInfo {
466
+ ticker: string;
467
+ name?: string;
468
+ shortName?: string;
469
+ exchange?: string;
470
+ market?: string;
471
+ /**
472
+ * Decimals of prices on the axis, legend and marks. A number is used as
473
+ * given. 'auto', or leaving it out, derives it from the loaded prices
474
+ * (about four significant digits: 64000 gets 2, 0.64 gets 4, 0.00002 gets
475
+ * 8), once per symbol. `getPricePrecision()` returns the value in use.
476
+ */
477
+ pricePrecision?: number | "auto";
478
+ volumePrecision?: number;
479
+ priceCurrency?: string;
480
+ type?: string;
481
+ logo?: string;
482
+ /**
483
+ * The IANA zone in which this symbol's bars of a day or longer open: their
484
+ * dates are read in it (a daily bar at 00:00 UTC is that UTC date wherever
485
+ * the viewer is, as on TradingView). Default 'UTC', which matches feeds
486
+ * whose daily bars open at 00:00 UTC (Binance, most crypto) and US equities
487
+ * at 13:30 UTC. A feed whose daily bars open at midnight elsewhere (OKX's
488
+ * UTC+8 bars) sets it, e.g. 'Asia/Shanghai'. Intraday bars follow the
489
+ * chart's timezone.
490
+ */
491
+ timezone?: string;
492
+ }
493
+ export interface Period {
494
+ multiplier: number;
495
+ timespan: Timespan;
496
+ text: string;
497
+ }
498
+ /**
499
+ * What subscribe() hands the datafeed. Call it with the latest bar, or with an
500
+ * array of bars (oldest first), for example the previous bar's final values
501
+ * and the new bar when one closes. Bars are snapshots: each replaces the bar
502
+ * with the same timestamp, and nothing is merged. A bar older than the chart's
503
+ * newest bar is ignored (klinecharts cannot change an older bar in place).
504
+ */
505
+ export type DatafeedSubscribeCallback = (data: MarketBar | MarketBar[]) => void;
506
+ /**
507
+ * The fifth argument of getHistoryKLineData: what the chart is asking for, so
508
+ * a datafeed does not have to guess it from `from`/`to`.
509
+ */
510
+ export interface HistoryRequest {
511
+ /**
512
+ * Aborted when the answer is no longer wanted (the symbol or period changed,
513
+ * or the chart was disposed). Pass it to fetch(). The chart ignores what a
514
+ * superseded request resolves or rejects with, AbortError included, so a
515
+ * datafeed that reports its own errors should check `signal.aborted` first.
516
+ */
517
+ signal: AbortSignal;
518
+ /**
519
+ * True for the first request of a series: the initial load, every symbol
520
+ * or period change and reload(). False for scroll-back pages and for the
521
+ * catch-up request after a gap (sleep, reconnect).
522
+ */
523
+ firstDataRequest: boolean;
524
+ /** How many bars the chart wants (a size hint; more or fewer is fine). */
525
+ countBack: number;
526
+ /**
527
+ * Scroll-back only: the timestamp of the chart's oldest bar. Answer with
528
+ * bars strictly older than it (the same instant as `to`). Undefined for
529
+ * the first request and the catch-up request, which want the newest bars.
530
+ */
531
+ before?: number;
532
+ }
533
+ /** What getHistoryKLineData may resolve with instead of a plain array. */
534
+ export interface HistoryResult {
535
+ bars: MarketBar[];
536
+ /**
537
+ * True: there is no history before these bars, so the chart stops asking
538
+ * further back (saves the one empty request a short series costs). With a
539
+ * plain array, an empty page means the same.
540
+ */
541
+ noData?: boolean;
542
+ }
543
+ /** The second argument of searchSymbols. */
544
+ export interface SearchRequest {
545
+ /** Aborted when the user searches again or closes the search. */
546
+ signal: AbortSignal;
547
+ }
548
+ export interface Datafeed {
549
+ /** A rejection (or throw) shows "Search failed" with Retry in the search dialog. */
550
+ searchSymbols(search?: string, request?: SearchRequest): Promise<SymbolInfo[]>;
551
+ /**
552
+ * Resolve a custom interval (one not in the chart's configured `periods`)
553
+ * that a user typed or picked, e.g. from the type-to-change interval box.
554
+ * Implementing this — or the chart's `customPeriods` option — opts into
555
+ * custom intervals; without either, an interval outside the configured
556
+ * list is refused before it ever reaches this datafeed (SC-112). Return
557
+ * null to refuse it anyway (e.g. a resolution the backend cannot serve).
558
+ */
559
+ resolvePeriod?(period: Pick<Period, "multiplier" | "timespan">): Period | null;
560
+ /**
561
+ * Bars with `from <= timestamp < to` (ms), oldest first. The first request
562
+ * has `to` = now; scroll-back requests have `to` = the chart's first bar.
563
+ * Reject (or throw) on a transport error: the chart shows an error state
564
+ * with Retry, and scroll-back retries with a backoff. `[]` means "no
565
+ * (older) history": after `[]`, the chart stops asking further back for
566
+ * this symbol and period. Duplicates, overlap, unsorted bars, second
567
+ * timestamps and numeric strings are tolerated.
568
+ *
569
+ * `request` (optional to read) says which kind of request this is and
570
+ * carries an AbortSignal; see HistoryRequest. Resolve with
571
+ * `{ bars, noData: true }` to say there is nothing older.
572
+ */
573
+ getHistoryKLineData(symbol: SymbolInfo, period: Period, from: number, to: number, request?: HistoryRequest): Promise<MarketBar[] | HistoryResult>;
574
+ /** Start live updates for this pair. The chart calls it once per load, after the history. */
575
+ subscribe: (symbol: SymbolInfo, period: Period, callback: DatafeedSubscribeCallback) => void;
576
+ /**
577
+ * Stop the updates started by the last subscribe(). Calls are strictly
578
+ * paired with subscribe(), and the chart calls it on dispose too.
579
+ */
580
+ unsubscribe: (symbol: SymbolInfo, period: Period) => void;
581
+ }
582
+ export interface EventTargetLike {
583
+ addEventListener: (type: string, fn: () => void) => void;
584
+ removeEventListener: (type: string, fn: () => void) => void;
585
+ }
586
+ export interface LoaderEnv extends FrameScheduler {
587
+ queueMicrotask: (fn: () => void) => void;
588
+ /** Host foreground/background events; optional. */
589
+ visibility?: EventTargetLike & {
590
+ hidden: boolean;
591
+ };
592
+ /** Host reconnect events; optional. */
593
+ connectivity?: EventTargetLike;
594
+ warn: (...args: unknown[]) => void;
595
+ }
596
+ /** Timers work in Node/native hosts; frame and lifecycle hooks belong to each host. */
597
+ export declare function createRuntimeEnvironment(overrides?: Partial<LoaderEnv>): LoaderEnv;
598
+ export interface HistoryCacheOptions {
599
+ /** Entries kept (least recently used dropped first). @default 8 */
600
+ max?: number;
601
+ /** An entry older than this is not painted (the chart waits for the datafeed). @default 600000 (10 min) */
602
+ ttlMs?: number;
603
+ }
604
+ export interface HistoryCacheEntry {
605
+ /** Oldest first, normalized (ms timestamps, sorted, no duplicates). */
606
+ bars: readonly MarketBar[];
607
+ /** More (older) history exists. */
608
+ more: boolean;
609
+ /** When the bars were last current (ms). */
610
+ at: number;
611
+ }
612
+ /** The cache key of a pair. */
613
+ export declare function historyKey(symbol: SymbolInfo, period: Pick<Period, "multiplier" | "timespan">): string;
614
+ export declare class HistoryCache {
615
+ private readonly _max;
616
+ private readonly _ttl;
617
+ private readonly _entries;
618
+ constructor(options?: HistoryCacheOptions);
619
+ get size(): number;
620
+ /** A fresh entry (and mark it most recently used), or undefined. */
621
+ get(key: string, now: number): HistoryCacheEntry | undefined;
622
+ set(key: string, entry: HistoryCacheEntry): void;
623
+ /** Drop one pair, every period of a symbol (`symbol` only), or everything (no arguments). */
624
+ invalidate(symbol?: SymbolInfo, period?: Pick<Period, "multiplier" | "timespan">): void;
625
+ }
626
+ /**
627
+ * How a fresh answer relates to the bars on screen (both oldest first):
628
+ * 'tail' when it reaches back into them and every bar it has up to their
629
+ * last timestamp is one they have (so only bars from that timestamp on are
630
+ * new or changed); 'replace' when it does not line up (a gap after the
631
+ * cached tail, or a feed whose bar times moved, like a series re-anchored to
632
+ * "now" on every call).
633
+ */
634
+ export declare function mergeKind(shown: readonly MarketBar[], fresh: readonly MarketBar[]): "tail" | "replace";
635
+ /** The initial load's state: what the chart shows the user. */
636
+ export type DataState = "idle" | "loading" | "ready" | "empty" | "error";
637
+ /** Which request failed: the initial history, a scroll-back page, or a gap backfill. */
638
+ export type LoadPhase = "initial" | "more" | "sync";
639
+ export interface DataLoadError {
640
+ phase: LoadPhase;
641
+ symbol: SymbolInfo;
642
+ period: Period;
643
+ /** What the datafeed rejected with (or threw), or a timeout Error. */
644
+ error: unknown;
645
+ /** True when the request did not settle in time (the initial load or a gap backfill). */
646
+ timeout: boolean;
647
+ }
648
+ export interface DataStatus {
649
+ state: DataState;
650
+ /** A scroll-back page is being fetched. */
651
+ loadingMore: boolean;
652
+ /** Set in the 'error' state. */
653
+ error: DataLoadError | null;
654
+ }
655
+ /** The part of a klinecharts Chart the loader drives (9.7 has no setLoadDataCallback). */
656
+ export type LoaderChart = ChartDataPort<MarketBar>;
657
+ export type LoadDataRequest = HistoryLoadRequest<MarketBar>;
658
+ export interface LoaderOptions {
659
+ datafeed: Datafeed;
660
+ /** Bars per history request. @default 500 */
661
+ count?: number;
662
+ /** 0 (default): ticks are applied once per frame. More: at most once per that many ms. */
663
+ tickThrottleMs?: number;
664
+ /** An initial load still pending after this long shows the error state. @default 20000 */
665
+ loadTimeoutMs?: number;
666
+ /** Minimum time between two gap backfills. @default 30000 */
667
+ syncMinIntervalMs?: number;
668
+ /**
669
+ * A gap backfill still pending after this long is given up: the live bars it
670
+ * held are applied (with the hole), so a stalled request never stops live
671
+ * updates. @default 10000
672
+ */
673
+ syncTimeoutMs?: number;
674
+ /** Retry delay after a failed scroll-back page, doubled per failure up to the max. */
675
+ moreRetryMs?: {
676
+ base: number;
677
+ max: number;
678
+ };
679
+ /**
680
+ * A per-instance LRU of the bars last shown for a (symbol, period), so
681
+ * switching back (1H -> 4H -> 1H) paints at once from cache while the
682
+ * datafeed is still asked (it is the hosts' own change signal, and its
683
+ * answer is merged in — never skipped). `false` (the default here; a host
684
+ * option turns it on): no cache. See src/data/historyCache.ts.
685
+ */
686
+ historyCache?: HistoryCacheOptions | false;
687
+ env?: Partial<LoaderEnv>;
688
+ }
689
+ export interface LoaderEvents {
690
+ status: DataStatus;
691
+ error: DataLoadError;
692
+ /** True when a replay starts, false when it ends (exit, or a new load cancels it). */
693
+ replay: boolean;
694
+ /**
695
+ * The bars an initial load (a symbol/period change or reload()) is about to
696
+ * apply, fired synchronously just before they are: the one place a host can
697
+ * derive something (e.g. price precision, src/data/precision.ts) from the
698
+ * bars a fresh pair will show before they are drawn. Not fired for
699
+ * scroll-back pages, gap backfills, replay or live ticks.
700
+ */
701
+ bars: {
702
+ bars: readonly MarketBar[];
703
+ symbol: SymbolInfo;
704
+ period: Period;
705
+ };
706
+ }
707
+ export interface Pair {
708
+ symbol: SymbolInfo;
709
+ period: Period;
710
+ }
711
+ /**
712
+ * True when consecutive bars are two or more periods apart somewhere: the feed
713
+ * has holes of its own (a market that closes overnight or at weekends, a thinly
714
+ * traded pair that skips empty bars). A backfill could not close such a hole,
715
+ * so a live bar after one is appended as it is.
716
+ */
717
+ export declare function hasHoles(bars: readonly MarketBar[], period: Pick<Period, "multiplier" | "timespan">): boolean;
718
+ export declare class DataLoader {
719
+ private readonly _env;
720
+ private readonly _datafeed;
721
+ private readonly _count;
722
+ private readonly _timeoutMs;
723
+ private readonly _syncMinMs;
724
+ private readonly _syncTimeoutMs;
725
+ private readonly _moreRetry;
726
+ private readonly _coalescer;
727
+ private readonly _cache;
728
+ private _chart;
729
+ private _reqAbort;
730
+ private _moreAbort;
731
+ private _syncAbort;
732
+ private _disposed;
733
+ private _detach;
734
+ private readonly _listeners;
735
+ private _pending;
736
+ private _scheduled;
737
+ private _current;
738
+ private _reqGen;
739
+ private _shownGen;
740
+ private _shown;
741
+ private _subscribed;
742
+ private _status;
743
+ private _unit;
744
+ private _more;
745
+ private _moreGen;
746
+ private _moreFailures;
747
+ private _moreTimer;
748
+ private _loadUntilBusy;
749
+ private _pendingOlderPage;
750
+ private _syncGen;
751
+ private _syncing;
752
+ private _syncTimer;
753
+ private _held;
754
+ private _lastSyncAt;
755
+ private _hiddenAt;
756
+ /** The pair's history has holes of its own: a live bar after a gap is not backfilled. */
757
+ private _sparse;
758
+ private _replay;
759
+ private readonly _warned;
760
+ constructor(options: LoaderOptions);
761
+ /** Listen to an event; returns the function that stops listening. */
762
+ on<K extends keyof LoaderEvents>(type: K, fn: (value: LoaderEvents[K]) => void): () => void;
763
+ get status(): DataStatus;
764
+ /** The symbol and period whose data is on screen (null before the first load settles). */
765
+ get shown(): Readonly<Pair> | null;
766
+ get disposed(): boolean;
767
+ /**
768
+ * Give the loader its chart: registers the scroll-back callback (9.8's
769
+ * setLoadDataCallback when there is one, loadMore otherwise) and the
770
+ * visibility / online listeners, and starts a request made before mount.
771
+ */
772
+ attach(chart: LoaderChart): void;
773
+ /** Load `symbol` and `period`. Calls in the same tick load the last pair once. */
774
+ request(symbol: SymbolInfo, period: Period): void;
775
+ /** Load the current pair again (a new request, new data). */
776
+ reload(): void;
777
+ /**
778
+ * Catch up on bars missed while the page slept or was offline: one history
779
+ * request from the last bar, merged by timestamp. Rate-limited; skipped
780
+ * during replay and while a load is in flight.
781
+ */
782
+ resync(): void;
783
+ /**
784
+ * Seed the history cache for `symbol`/`period` from bars a host already
785
+ * has, so a later request() (a symbol/period change, not the pair on
786
+ * screen right now) can paint instantly. A no-op when historyCache is off.
787
+ */
788
+ primeHistory(symbol: SymbolInfo, period: Period, bars: readonly MarketBar[]): void;
789
+ /**
790
+ * Drop cached history: one pair (`symbol` and `period`), every period of a
791
+ * symbol (`symbol` only), or everything (no arguments). A no-op when
792
+ * historyCache is off.
793
+ */
794
+ invalidateHistory(symbol?: SymbolInfo, period?: Period): void;
795
+ /**
796
+ * SC-141: page older bars in, directly (not through a klinecharts scroll),
797
+ * until the shown pair's first bar reaches `timestamp` or one of these
798
+ * stops it: an empty (or `noData`) page, `capPages` pages (default 20), the
799
+ * symbol/period changing, or dispose. One call at a time — a second call
800
+ * while one is running resolves `{ covered: false }` at once, rather than
801
+ * race a concurrent one (or a live user scroll) over the same scroll-back
802
+ * bookkeeping (`_moreGen` and klinecharts' own loading flag).
803
+ */
804
+ loadUntil(timestamp: number, capPages?: number): Promise<{
805
+ covered: boolean;
806
+ }>;
807
+ /** One _loadOlder round trip as a promise, bounded by the load timeout so a stolen answer cannot hang loadUntil forever. */
808
+ private _awaitOlderPage;
809
+ /** Stop everything: unsubscribes the active pair, drops pending work, removes listeners. */
810
+ dispose(): void;
811
+ get replaying(): boolean;
812
+ /** True when the replay head is on the newest bar (or there is no replay). */
813
+ get replayAtEnd(): boolean;
814
+ /** The replay head, or null when there is no replay running. */
815
+ get replayInfo(): {
816
+ index: number;
817
+ length: number;
818
+ timestamp: number;
819
+ } | null;
820
+ /**
821
+ * Start a replay of the data on screen. Live ticks and scroll-back pages
822
+ * go into the replay's series until it ends. `at` is a data index into the
823
+ * data currently on screen; the default (60% of the way in) is unchanged.
824
+ * False when there is nothing to replay.
825
+ */
826
+ enterReplay(at?: number): boolean;
827
+ /** Move the replay head `dir` bars (1 forward, -1 back). */
828
+ replayStep(dir: number): void;
829
+ /** End the replay and show every bar, including what arrived during it. */
830
+ exitReplay(): void;
831
+ /** Loader batches are normalized; optional sinks avoid repeating normalization, never validation. */
832
+ private _replaceData;
833
+ private _schedule;
834
+ private _isCurrent;
835
+ /** The datafeed's history promise; a synchronous throw becomes a rejection. */
836
+ private _fetch;
837
+ private _start;
838
+ private _show;
839
+ private _failInitial;
840
+ private _subscribe;
841
+ /** Unsubscribe the active pair (once) and drop all pending work of the old generation. */
842
+ private _retire;
843
+ /** Drop a scroll-back page in flight (or waiting out its backoff): the data it would extend is gone. */
844
+ private _cancelMore;
845
+ /**
846
+ * klinecharts asks for bars older than `timestamp` (its first bar). The
847
+ * request's `to` is that timestamp, exclusive; the page is reduced to bars
848
+ * strictly older than the chart's first bar (feeds that ignore the range or
849
+ * include `to` would otherwise prepend copies), and an empty page ends
850
+ * paging.
851
+ */
852
+ private _loadOlder;
853
+ private _onTick;
854
+ private _routeTick;
855
+ private _applyTicks;
856
+ /** A bar at least two periods after the last one: at least one bar is missing. */
857
+ private _isGap;
858
+ private _canSync;
859
+ /** Hold a tick while a backfill runs (the same timestamp replaces, older is dropped). */
860
+ private _hold;
861
+ /** Stop a backfill in flight; returns the ticks it held. */
862
+ private _abandonSync;
863
+ /**
864
+ * A backfill failed or timed out: apply the ticks it held, with the hole
865
+ * (what happened before backfills existed), and report it.
866
+ */
867
+ private _giveUpSync;
868
+ /**
869
+ * Fetch from the last bar (inclusive: its OHLC is partial) to now, then
870
+ * append in timestamp order: the bars that close the hole, then the held
871
+ * tick(s). If the answer does not reach back to the last bar (the hole is
872
+ * wider than one window), the latest window replaces the data instead.
873
+ * Live ticks are held while it runs, so it gives up after `syncTimeoutMs`.
874
+ */
875
+ private _startSync;
876
+ private _listen;
877
+ private _endReplay;
878
+ private _setStatus;
879
+ private _setLoadingMore;
880
+ private _emit;
881
+ private _emitError;
882
+ private _warnOnce;
883
+ /** One console warning per kind of data fix, per chart. */
884
+ private _report;
885
+ }
886
+ /** Fixed-length timespans, in ms. Month and year are calendar arithmetic. */
887
+ export declare const UNIT_MS: Readonly<Record<string, number>>;
888
+ /**
889
+ * `ts` moved by `n` periods (negative: back). Month and year keep the day and
890
+ * time of day in UTC, and a day past the end of a month rolls into the next
891
+ * one (Jan 31 + 1 month is Mar 3 or 2), which is what a lower bound needs.
892
+ * NaN for an unknown timespan.
893
+ */
894
+ export declare function addPeriods(period: Pick<Period, "multiplier" | "timespan">, ts: number, n: number): number;
895
+ /**
896
+ * The `[from, to]` to ask a datafeed for: `count` bars of `period` ending at
897
+ * `to`. `to` is passed through unchanged (the engine sends the current time on
898
+ * the first load, and the first loaded bar's timestamp, exclusive, when it
899
+ * pages back). `from` is never negative, and `from <= to` always holds.
900
+ *
901
+ * Never throws: an unknown timespan logs one warning and asks for the empty
902
+ * range `[to, to]` (asking from 0 would fetch a feed's whole history).
903
+ */
904
+ export declare function requestRange(period: Pick<Period, "multiplier" | "timespan">, to: number, count: number): [
905
+ number,
906
+ number
907
+ ];
908
+ /** Every field equal (Object.is): nothing to update. */
909
+ export declare function sameSymbol(a: SymbolInfo | undefined, b: SymbolInfo | undefined): boolean;
910
+ /** What identifies the symbol's data: every field except the display-only ones. */
911
+ export declare function symbolKey(symbol: SymbolInfo | undefined): string;
912
+ /** A period's identity: multiplier and timespan (never its display text). */
913
+ export declare function periodKey(period: Pick<Period, "multiplier" | "timespan"> | undefined): string;
914
+ /** Same multiplier and timespan. */
915
+ export declare function samePeriod(a: Pick<Period, "multiplier" | "timespan"> | undefined, b: Pick<Period, "multiplier" | "timespan"> | undefined): boolean;
916
+ /**
917
+ * A period from shorthand. Case-sensitive where it matters: '1m' is one
918
+ * minute and '1M' one month; h/H, d/D, w/W and y/Y are the same. Also takes
919
+ * TradingView resolutions: a bare number of minutes ('60' and '240' are 1 and
920
+ * 4 hours), '1D', 'W', 'M', '1S'. Null when it cannot be read.
921
+ */
922
+ export declare function parsePeriod(input: string): Pick<Period, "multiplier" | "timespan"> | null;
923
+ /**
924
+ * What setPeriod stores for `input`: a Period object as given; a string mapped
925
+ * onto the configured period with the same multiplier and timespan (so '4h'
926
+ * selects the top bar's 4H), or a new period labelled with the string. Null
927
+ * (with a warning) for a string that cannot be read.
928
+ */
929
+ export declare function resolvePeriod(input: Period | string, periods: readonly Period[]): Period | null;
930
+ export interface ReplayState {
931
+ /** Every bar, oldest first: the snapshot plus what arrived since. */
932
+ readonly full: readonly MarketBar[];
933
+ /** Index in `full` of the newest bar shown. */
934
+ readonly idx: number;
935
+ }
936
+ /** What to do to the chart to go from one replay state to the next. */
937
+ export type ReplayApply = {
938
+ kind: "none";
939
+ }
940
+ /** Append one bar (klinecharts updateData): keeps the user's scroll position. */
941
+ | {
942
+ kind: "append";
943
+ bar: MarketBar;
944
+ }
945
+ /** Replace the data (applyNewData) with these bars. */
946
+ | {
947
+ kind: "rebuild";
948
+ bars: MarketBar[];
949
+ };
950
+ /** Fewer bars than this and there is nothing to replay. */
951
+ export declare const MIN_REPLAY_BARS = 3;
952
+ /**
953
+ * `list` with `bar` merged in as klinecharts would (snapshot semantics): the
954
+ * same timestamp as the last bar replaces it, a newer one is appended, an
955
+ * older one is ignored. Returns a new array, or `list` itself when ignored.
956
+ */
957
+ export declare function mergeBar(list: readonly MarketBar[], bar: MarketBar): readonly MarketBar[];
958
+ /** A replay over `bars` starting at `at` (default: 60% of the way in); null if too short. */
959
+ export declare function startReplay(bars: readonly MarketBar[], at?: number): ReplayState | null;
960
+ /** `dir` bars forward (positive) or back (negative), clamped to the series. */
961
+ export declare function stepReplay(state: ReplayState, dir: number): ReplayState;
962
+ /** A live tick during replay: buffered into `full`, never shown until exit. */
963
+ export declare function tickReplay(state: ReplayState, bar: MarketBar): ReplayState;
964
+ /**
965
+ * Older history (a scroll-back page) during replay: prepended to `full`. The
966
+ * index moves with it, so the replay head stays on the same bar.
967
+ */
968
+ export declare function prependReplay(state: ReplayState, older: readonly MarketBar[]): ReplayState;
969
+ /** The bars shown at this state: the series up to and including the head. */
970
+ export declare function replayBars(state: ReplayState): MarketBar[];
971
+ /** True when the head is on the newest bar. */
972
+ export declare function replayAtEnd(state: ReplayState): boolean;
973
+ /**
974
+ * How to show `next` on a chart whose newest bar has timestamp `chartLastTs`,
975
+ * coming from `prev`. One step forward from a chart that shows exactly `prev`
976
+ * is an append (the view keeps its scroll position); anything else (a step
977
+ * back, a jump, a chart in an unexpected state) rebuilds.
978
+ */
979
+ export declare function replayApply(prev: ReplayState, next: ReplayState, chartLastTs: number | undefined): ReplayApply;
980
+ /** The subset of KLineData a Heikin Ashi transform reads and writes; a plain object works for both klinecharts' KLineData and any host's superset of it. */
981
+ export interface OhlcBar {
982
+ timestamp: number;
983
+ open: number;
984
+ high: number;
985
+ low: number;
986
+ close: number;
987
+ volume?: number;
988
+ turnover?: number;
989
+ }
990
+ /**
991
+ * Maps `bars` (ascending by timestamp, as klinecharts requires) to their
992
+ * Heikin Ashi series. Non-finite OHLC values pass through unchanged for that
993
+ * bar and reset the previous-HA state, so the next valid bar restarts the
994
+ * recurrence rather than carrying invalid data forward (normalizeBars drops those
995
+ * before they would ever reach here — this is the defensive fallback for a
996
+ * host that calls toHeikinAshi directly on unvalidated data).
997
+ */
998
+ export declare function toHeikinAshi<T extends OhlcBar>(bars: readonly T[]): T[];
999
+ /** True for candle_solid/candle_stroke/etc. bars whose close >= open (used to colour a Heikin Ashi bar the same way an ordinary candle is). */
1000
+ export declare function isHeikinAshiUp(bar: Pick<OhlcBar, "open" | "close">): boolean;
1001
+ export type CandleMode = "raw" | "heikin-ashi";
1002
+ export interface RealtimeSeriesChange {
1003
+ kind: "reset" | "prepend" | "tail" | "truncate" | "availability";
1004
+ /** First potentially changed index, inclusive. */
1005
+ from: number;
1006
+ length: number;
1007
+ version: number;
1008
+ }
1009
+ /**
1010
+ * Renderer-free sink for DataLoader. MA20 and EMA21 use the native first-close
1011
+ * EMA seed (not the Web SMA seed). Inputs must be normalized, ascending bars.
1012
+ * History changes rebuild; live updates only calculate the changed tail.
1013
+ */
1014
+ export declare class RealtimeSeries implements ChartDataPort {
1015
+ private _bars;
1016
+ private _ha;
1017
+ private _ma;
1018
+ private _ema;
1019
+ private _sum;
1020
+ private _previous;
1021
+ private _sumBeforeLast;
1022
+ private _emaBeforeLast;
1023
+ private _version;
1024
+ private _more;
1025
+ private _loadMore;
1026
+ private readonly _listeners;
1027
+ private readonly _referenceIndicators;
1028
+ /** Hosts with their own indicator registry can omit the native reference MA/EMA. */
1029
+ constructor(options?: {
1030
+ referenceIndicators?: boolean;
1031
+ });
1032
+ get version(): number;
1033
+ get hasMore(): boolean;
1034
+ /** Borrowed current data for the loader: do not mutate or retain as a snapshot. */
1035
+ getDataList(): MarketBar[];
1036
+ getLastTimestamp(): number | undefined;
1037
+ /** Copy only the visible range for React/native render state; end is exclusive. */
1038
+ snapshot(start?: number, end?: number, mode?: CandleMode): {
1039
+ version: number;
1040
+ bars: MarketBar[];
1041
+ ma20: Array<number | null>;
1042
+ ema21: Array<number | null>;
1043
+ };
1044
+ subscribe(listener: (change: RealtimeSeriesChange) => void): () => void;
1045
+ loadMore(callback: (timestamp: number | null) => void): void;
1046
+ /** Host calls this when its own viewport reaches the oldest loaded bar. */
1047
+ requestMore(): void;
1048
+ applyNewData(bars: MarketBar[], more?: boolean): void;
1049
+ /** Drop a replay suffix without cloning the prefix or retaining future prices. */
1050
+ truncateData(length: number, expectedLength: number, expectedLastTimestamp: number): boolean;
1051
+ applyMoreData(bars: MarketBar[], more?: boolean): void;
1052
+ updateData(bar: MarketBar): void;
1053
+ /** One notification per batch. Old ticks are ignored; equal-tail ticks replace. */
1054
+ updateDataBatch(bars: MarketBar[], more?: boolean): void;
1055
+ /** Explicit history correction: use a complete reset, never an identity-based cache. */
1056
+ private _rebuild;
1057
+ private _calculate;
1058
+ /** Validate the owned copy before publishing it; caller mutation cannot change the series. */
1059
+ private _copyValidated;
1060
+ private _validateBar;
1061
+ private _validate;
1062
+ private _emit;
1063
+ }
1064
+ export interface RealtimeViewSnapshot {
1065
+ readonly version: number;
1066
+ readonly viewport: Readonly<Viewport>;
1067
+ /** First sampled candle index for an opt-in fractional viewport. */
1068
+ readonly dataStart?: number;
1069
+ readonly length: number;
1070
+ readonly hasMore: boolean;
1071
+ readonly following: boolean;
1072
+ readonly mode: CandleMode;
1073
+ readonly bars: ReadonlyArray<Readonly<MarketBar>>;
1074
+ /** Indicators always use raw prices, including in Heikin Ashi display mode. */
1075
+ readonly ma20: ReadonlyArray<number | null>;
1076
+ readonly ema21: ReadonlyArray<number | null>;
1077
+ }
1078
+ /**
1079
+ * A cached external-store snapshot for renderer-owned views, with no React or DOM.
1080
+ * Create with the host chart lifetime, and dispose alongside the loader on unmount.
1081
+ * Gestures call pan/zoom; the host still owns event handling and pixel conversion.
1082
+ */
1083
+ export declare class RealtimeView {
1084
+ private readonly _series;
1085
+ private _viewport;
1086
+ private _length;
1087
+ private _following;
1088
+ private _count;
1089
+ private _mode;
1090
+ private _snapshot;
1091
+ private _disposed;
1092
+ private readonly _unsubscribe;
1093
+ private readonly _listeners;
1094
+ private readonly _continuous;
1095
+ private _limits;
1096
+ private readonly _openingCount;
1097
+ private readonly _historyLimit;
1098
+ private readonly _past;
1099
+ private readonly _future;
1100
+ private _navigationStart;
1101
+ constructor(_series: RealtimeSeries, options?: {
1102
+ count?: number;
1103
+ mode?: CandleMode;
1104
+ continuous?: boolean;
1105
+ limits?: ViewportLimits;
1106
+ navigationHistory?: number;
1107
+ });
1108
+ /** Stable function and object identity until the visible state changes. */
1109
+ readonly getSnapshot: () => RealtimeViewSnapshot;
1110
+ readonly subscribe: (listener: () => void) => (() => void);
1111
+ getLimits(): Readonly<Required<ViewportLimits>>;
1112
+ /** Apply host zoom bounds without discarding a pinned viewport or its follow state. */
1113
+ setLimits(limits: ViewportLimits): void;
1114
+ setViewport(viewport: Viewport): void;
1115
+ pan(bars: number): void;
1116
+ zoom(factor: number, anchor?: number): void;
1117
+ followLatest(count?: number): void;
1118
+ /** Return to the host's opening density and follow the newest real candle. */
1119
+ resetViewport(): void;
1120
+ /** Coalesce one drag/wheel/axis gesture into a single bounded history entry. */
1121
+ beginNavigation(): void;
1122
+ endNavigation(): void;
1123
+ getNavigationHistory(): Readonly<{
1124
+ canUndo: boolean;
1125
+ canRedo: boolean;
1126
+ limit: number;
1127
+ }>;
1128
+ clearNavigationHistory(): void;
1129
+ undoNavigation(): boolean;
1130
+ redoNavigation(): boolean;
1131
+ setMode(mode: CandleMode): void;
1132
+ /** Jump to the nearest loaded candle. Does not fetch history outside the loaded range. */
1133
+ seek(timestamp: number, anchor?: number): boolean;
1134
+ requestMore(): void;
1135
+ dispose(): void;
1136
+ private _navigationState;
1137
+ private _recordNavigation;
1138
+ private _restoreNavigation;
1139
+ private _validCount;
1140
+ private _clamp;
1141
+ private _default;
1142
+ private _changed;
1143
+ private _read;
1144
+ private _publish;
1145
+ }
1146
+ export type RealtimeIndicator = "MA20" | "EMA21";
1147
+ export interface RealtimeChartOptions {
1148
+ /** Time spacing preserves market gaps; category spacing gives equal candle widths. */
1149
+ spacing?: "time" | "category";
1150
+ indicators?: readonly RealtimeIndicator[];
1151
+ colors?: Partial<Record<RealtimeIndicator, string>>;
1152
+ axisGutter?: number;
1153
+ }
1154
+ export interface RealtimeInspection {
1155
+ /** Index in the complete loaded series, not in the viewport. */
1156
+ index: number;
1157
+ timestamp: number;
1158
+ mode: CandleMode;
1159
+ /** Synthetic OHLC in HA mode; never interpret it as an executable quote. */
1160
+ displayBar: Readonly<MarketBar>;
1161
+ indicatorBasis: "raw";
1162
+ ma20: number | null;
1163
+ ema21: number | null;
1164
+ }
1165
+ export interface RealtimeChartFrame {
1166
+ readonly snapshot: RealtimeViewSnapshot;
1167
+ /** Geometry indexes are local to this viewport. Use inspect for a global index. */
1168
+ readonly model: FinancialChartModel;
1169
+ inspect: (chartX: number) => RealtimeInspection | null;
1170
+ }
1171
+ /** Apply an opt-in fractional view to an existing visible-only model. */
1172
+ export declare function applyRealtimeViewport(model: FinancialChartModel, snapshot: RealtimeViewSnapshot, spacing: "time" | "category"): void;
1173
+ /**
1174
+ * Build only the visible candles/indicator points. Hosts render this shared geometry
1175
+ * with their own Canvas/SVG/native view. Inspection uses chart-local x, including
1176
+ * the left axis gutter (the same coordinates as model.xPositions).
1177
+ * Create once per snapshot or layout/options change, not on every pointer movement.
1178
+ */
1179
+ export declare function createRealtimeChartFrame(snapshot: RealtimeViewSnapshot, width: number, height: number, options?: RealtimeChartOptions): RealtimeChartFrame;
1180
+ /** Pure reversible value/coordinate scale shared by renderers and drawing tools. */
1181
+ export type PriceScaleMode = "linear" | "log" | "percentage";
1182
+ export interface PriceScaleOptions {
1183
+ mode?: PriceScaleMode;
1184
+ reversed?: boolean;
1185
+ /** Raw price bounds, not log or percentage values. */
1186
+ range?: readonly [
1187
+ number,
1188
+ number
1189
+ ];
1190
+ }
1191
+ export interface PriceScale {
1192
+ min: number;
1193
+ max: number;
1194
+ ticks: number[];
1195
+ y: (price: number) => number;
1196
+ value: (y: number) => number;
1197
+ label: (price: number, precision: number) => string;
1198
+ }
1199
+ export declare function validatePriceScale(options: PriceScaleOptions): void;
1200
+ export declare function createPriceScale(values: readonly number[], top: number, bottom: number, options?: PriceScaleOptions, base?: number): PriceScale;
1201
+ export interface IndicatorFigure {
1202
+ readonly key: string;
1203
+ readonly title: string;
1204
+ readonly color?: string;
1205
+ readonly type: "line" | "bar" | "circle";
1206
+ readonly lineWidth?: number;
1207
+ readonly dash?: readonly number[];
1208
+ /** Histogram origin in indicator units. */
1209
+ readonly base?: number;
1210
+ }
1211
+ export type IndicatorRow = Readonly<Record<string, number | null>>;
1212
+ export type IndicatorPane = "price" | "separate";
1213
+ export interface IndicatorDefinition {
1214
+ readonly name: string;
1215
+ readonly params?: readonly number[];
1216
+ readonly pane: IndicatorPane;
1217
+ readonly figures: readonly IndicatorFigure[];
1218
+ /** Pure calculation: one row per input bar, null for unavailable/warmup values. */
1219
+ readonly calculate: (bars: readonly MarketBar[], params: readonly number[]) => readonly IndicatorRow[];
1220
+ /** Validate a candidate parameter change before an instance is mutated. */
1221
+ readonly validateParams?: (params: readonly number[]) => void;
1222
+ }
1223
+ export interface EngineIndicatorSpec {
1224
+ readonly id?: string;
1225
+ readonly name: string;
1226
+ readonly params?: readonly number[];
1227
+ readonly pane?: IndicatorPane;
1228
+ /** Share a lower pane with another indicator; omitted gives this instance its own pane. */
1229
+ readonly paneId?: string;
1230
+ readonly visible?: boolean;
1231
+ }
1232
+ export interface EngineIndicatorInstance {
1233
+ readonly id: string;
1234
+ readonly name: string;
1235
+ readonly params: readonly number[];
1236
+ readonly pane: IndicatorPane;
1237
+ readonly paneId?: string;
1238
+ readonly visible: boolean;
1239
+ }
1240
+ export interface EngineIndicatorResult {
1241
+ readonly id: string;
1242
+ readonly name: string;
1243
+ readonly pane: IndicatorPane;
1244
+ readonly paneId?: string;
1245
+ readonly figures: readonly IndicatorFigure[];
1246
+ /** Borrowed current rows, indexed against the complete input series. */
1247
+ readonly rows: readonly IndicatorRow[];
1248
+ }
1249
+ /**
1250
+ * Renderer-free indicator registry. Supply normalized, ascending OHLC bars.
1251
+ *
1252
+ * Semantics follow the existing owned TA core: MA is SMA, EMA is SMA-seeded,
1253
+ * BOLL uses population deviation, RSI is Wilder and MACD hist = DIF - DEA.
1254
+ * KDJ uses a full lookback and 50-seeded recursive K/D; it is not STOCH.
1255
+ * MA/EMA/RSI take one period per instance (add more instances for more lines).
1256
+ * VOL plots reported nonnegative volume only, without invented missing values.
1257
+ *
1258
+ * Call invalidate for every in-place data change, as emitted by RealtimeSeries.
1259
+ * Unchanged data (including availability/viewport changes) reuses result identity.
1260
+ * MA/EMA/RSI/MACD retain before/after-last states; tail changes at or after the
1261
+ * previous last bar avoid historical recalculation. MA preserves the core's
1262
+ * compensated sum and periodic window reseed (amortised O(1) per appended bar;
1263
+ * an update at a reseed boundary reads one period). VOL is stateless and
1264
+ * recalculates only changed rows. KDJ tail edits read only their lookback window
1265
+ * and retain the previous recursive K/D values. BOLL retains compensated mean
1266
+ * and Welford variance with the same periodic reseed as the core. Custom
1267
+ * definitions still recompute on data changes. Reset/prepend/history
1268
+ * corrections always rebuild.
1269
+ *
1270
+ * Results are borrowed read-only views, not snapshots: a later tail computation
1271
+ * can update their rows in place. Custom calculations must not mutate inputs.
1272
+ */
1273
+ export declare class EngineIndicators {
1274
+ private readonly definitions;
1275
+ private readonly builtinNames;
1276
+ private readonly entries;
1277
+ private result;
1278
+ private bars;
1279
+ private length;
1280
+ private dataDirty;
1281
+ private structureDirty;
1282
+ private fullReset;
1283
+ private from;
1284
+ private nextId;
1285
+ private disposed;
1286
+ constructor();
1287
+ register(definition: IndicatorDefinition): void;
1288
+ /** Never remove built-ins or a definition still used by an instance. */
1289
+ unregister(name: string, expectedCalculate?: IndicatorDefinition["calculate"]): boolean;
1290
+ add(spec: EngineIndicatorSpec): string;
1291
+ update(id: string, changes: Pick<EngineIndicatorSpec, "params" | "pane" | "paneId" | "visible">): boolean;
1292
+ private validatePlacement;
1293
+ remove(id: string): boolean;
1294
+ /** Custom formulas may depend on future bars, so offscreen changes can affect visible values. */
1295
+ hasCustom(): boolean;
1296
+ list(): readonly EngineIndicatorInstance[];
1297
+ registeredNames(): readonly string[];
1298
+ /** Validate a complete document without changing live instances or calculations. */
1299
+ validateReplacement(specs: readonly EngineIndicatorSpec[]): void;
1300
+ /** Explicit replacement: every spec is accepted before any live instance changes. */
1301
+ replace(specs: readonly EngineIndicatorSpec[]): void;
1302
+ private prepareReplacement;
1303
+ /** Release retained history/results and custom calculation closures. Idempotent. */
1304
+ dispose(): void;
1305
+ invalidate(change: RealtimeSeriesChange): void;
1306
+ compute(bars: readonly MarketBar[]): readonly EngineIndicatorResult[];
1307
+ private calculate;
1308
+ private assertLive;
1309
+ }
1310
+ export declare const DATA_DRIVEN_DRAWING_TYPES: readonly [
1311
+ "regression-trend",
1312
+ "position-long",
1313
+ "position-short",
1314
+ "anchored-vwap",
1315
+ "fixed-range-volume-profile",
1316
+ "anchored-volume-profile"
1317
+ ];
1318
+ export type DataDrivenDrawingType = typeof DATA_DRIVEN_DRAWING_TYPES[number];
1319
+ export type DataDrivenDrawingStatus = "ready" | "empty" | "missing-volume" | "invalid-data" | "too-wide" | "invalid-position" | "unprojectable" | "unavailable-history";
1320
+ export interface DataDrivenDrawingResult {
1321
+ readonly type: DataDrivenDrawingType;
1322
+ readonly status: DataDrivenDrawingStatus;
1323
+ readonly fromIndex?: number;
1324
+ readonly toIndex?: number;
1325
+ readonly missingVolumeBars?: number;
1326
+ readonly statistics?: Readonly<{
1327
+ /** Raw price per bar index, not price per elapsed second. */
1328
+ slope?: number;
1329
+ /** Fitted close at the first selected bar. */
1330
+ intercept?: number;
1331
+ /** Population RMS residual in raw price units; channel width is ±2σ. */
1332
+ standardDeviation?: number;
1333
+ /** Absolute target distance / stop distance; excludes fees, size and leverage. */
1334
+ rewardRiskRatio?: number;
1335
+ /** Signed raw-price change relative to |entry|, not leveraged trade P&L. */
1336
+ targetChangePercent?: number;
1337
+ stopChangePercent?: number;
1338
+ /** Unconverted feed volume units. No turnover/quote-unit substitution. */
1339
+ totalVolume?: number;
1340
+ poc?: number;
1341
+ valueAreaHigh?: number;
1342
+ valueAreaLow?: number;
1343
+ }>;
1344
+ }
1345
+ export declare const DATA_DRIVEN_DRAWING_LIMITS: Readonly<{
1346
+ rangeBars: 100000;
1347
+ visibleVwapBars: 8192;
1348
+ cachedCells: 1000000;
1349
+ cacheEntries: 64;
1350
+ }>;
1351
+ /**
1352
+ * Raw revealed OHLCV only, including when the renderer displays Heikin Ashi.
1353
+ * Anchors resolve to their containing loaded bar; an anchor outside supplied
1354
+ * history is unavailable, never clamped to a different/future bar. Profile
1355
+ * volume is distributed proportionally across each candle's low/high range;
1356
+ * it is not order-book activity or actual volume traded at each price.
1357
+ *
1358
+ * A revision must change for ANY edit in supplied data. Without it no numeric
1359
+ * cache is reused. Visible range bounds only VWAP projection, not its sums.
1360
+ * The sink clips finite primitives and shares normal drawing hit geometry.
1361
+ */
1362
+ export declare function projectDataDrivenDrawing(value: Drawing, project: DrawingProjector, bounds: DrawingBounds, context: DrawingContext | undefined, sink: DrawingGeometrySink): DataDrivenDrawingResult | null;
1363
+ export declare const DRAWING_TYPES: readonly [
1364
+ "horizontal",
1365
+ "vertical",
1366
+ "horizontal-ray",
1367
+ "segment",
1368
+ "ray",
1369
+ "trend-line",
1370
+ "arrow",
1371
+ "rectangle",
1372
+ "ellipse",
1373
+ "circle",
1374
+ "price-range",
1375
+ "time-range",
1376
+ "fibonacci",
1377
+ "horizontal-segment",
1378
+ "vertical-segment",
1379
+ "vertical-ray",
1380
+ "parallel-channel",
1381
+ "price-channel",
1382
+ "pitchfork",
1383
+ "schiff-pitchfork",
1384
+ "modified-schiff-pitchfork",
1385
+ "fibonacci-extension",
1386
+ "triangle",
1387
+ "parallelogram",
1388
+ "text",
1389
+ "price-label",
1390
+ "arrow-up",
1391
+ "arrow-down",
1392
+ "price-line",
1393
+ "curve",
1394
+ "arc",
1395
+ "double-curve",
1396
+ "flag",
1397
+ "regression-trend",
1398
+ "disjoint-channel",
1399
+ "rotated-rectangle",
1400
+ "fibonacci-line",
1401
+ "fibonacci-circle",
1402
+ "fibonacci-spiral",
1403
+ "fibonacci-fan",
1404
+ "fibonacci-time-zone",
1405
+ "gann-box",
1406
+ "gann-fan",
1407
+ "gann-square",
1408
+ "fibonacci-arcs",
1409
+ "xabcd",
1410
+ "abcd",
1411
+ "three-waves",
1412
+ "five-waves",
1413
+ "eight-waves",
1414
+ "any-waves",
1415
+ "position-long",
1416
+ "position-short",
1417
+ "price-time-range",
1418
+ "forecast",
1419
+ "note",
1420
+ "callout",
1421
+ "signpost",
1422
+ "pin",
1423
+ "image",
1424
+ "anchored-vwap",
1425
+ "fixed-range-volume-profile",
1426
+ "anchored-volume-profile",
1427
+ "brush",
1428
+ "highlighter"
1429
+ ];
1430
+ export type DrawingType = typeof DRAWING_TYPES[number];
1431
+ export interface DrawingAnchor {
1432
+ readonly timestamp: number;
1433
+ readonly price: number;
1434
+ }
1435
+ export interface Drawing {
1436
+ readonly id: string;
1437
+ readonly type: DrawingType;
1438
+ readonly anchors: readonly DrawingAnchor[];
1439
+ readonly locked: boolean;
1440
+ readonly hidden: boolean;
1441
+ /** Plain text only; present exclusively on text drawings. */
1442
+ readonly text?: string;
1443
+ readonly image?: string;
1444
+ readonly strokeWidth?: number;
1445
+ }
1446
+ export interface DrawingInput {
1447
+ id: string;
1448
+ type: DrawingType;
1449
+ anchors: readonly DrawingAnchor[];
1450
+ locked?: boolean;
1451
+ hidden?: boolean;
1452
+ text?: string;
1453
+ image?: string;
1454
+ strokeWidth?: number;
1455
+ }
1456
+ export interface DrawingPatch {
1457
+ anchors?: readonly DrawingAnchor[];
1458
+ locked?: boolean;
1459
+ hidden?: boolean;
1460
+ text?: string;
1461
+ image?: string;
1462
+ strokeWidth?: number;
1463
+ }
1464
+ export interface DrawingPoint {
1465
+ readonly x: number;
1466
+ readonly y: number;
1467
+ }
1468
+ export interface DrawingBounds {
1469
+ readonly left: number;
1470
+ readonly top: number;
1471
+ readonly right: number;
1472
+ readonly bottom: number;
1473
+ }
1474
+ export type DrawingProjector = (timestamp: number, price: number) => DrawingPoint | null;
1475
+ export interface DrawingContext {
1476
+ readonly bars: readonly MarketBar[];
1477
+ readonly revision?: unknown;
1478
+ readonly visibleRange?: readonly [
1479
+ number,
1480
+ number
1481
+ ];
1482
+ }
1483
+ export interface DrawingGeometrySink {
1484
+ line: (from: DrawingPoint, to: DrawingPoint, ray?: boolean, full?: boolean) => void;
1485
+ polygon: (points: readonly DrawingPoint[]) => void;
1486
+ text: (position: DrawingPoint, text: string, price?: number, align?: "left" | "right" | "center") => void;
1487
+ label: (position: DrawingPoint, text: string, price?: number, boxed?: boolean) => void;
1488
+ }
1489
+ export type DrawingPrimitive = {
1490
+ readonly kind: "line";
1491
+ readonly from: DrawingPoint;
1492
+ readonly to: DrawingPoint;
1493
+ }
1494
+ /** A clipped fill only. Separate line primitives carry the original rectangle's visible edges. */
1495
+ | {
1496
+ readonly kind: "rect";
1497
+ readonly from: DrawingPoint;
1498
+ readonly to: DrawingPoint;
1499
+ } | {
1500
+ readonly kind: "ellipse";
1501
+ readonly center: DrawingPoint;
1502
+ readonly radiusX: number;
1503
+ readonly radiusY: number;
1504
+ readonly clip: DrawingBounds;
1505
+ }
1506
+ /** Filled, clipped polygon. Original boundary segments remain separate primitives. */
1507
+ | {
1508
+ readonly kind: "polygon";
1509
+ readonly points: readonly DrawingPoint[];
1510
+ }
1511
+ /** Explicit paint and hit rectangle, distinct from unselectable measurement captions. */
1512
+ | {
1513
+ readonly kind: "label";
1514
+ readonly bounds: DrawingBounds;
1515
+ readonly clip: DrawingBounds;
1516
+ readonly lines: readonly string[];
1517
+ readonly price?: number;
1518
+ readonly boxed?: boolean;
1519
+ } | {
1520
+ readonly kind: "stroke";
1521
+ readonly points: readonly DrawingPoint[];
1522
+ readonly width: number;
1523
+ readonly opacity: number;
1524
+ readonly clip: DrawingBounds;
1525
+ } | {
1526
+ readonly kind: "image";
1527
+ readonly source: string;
1528
+ readonly bounds: DrawingBounds;
1529
+ readonly clip: DrawingBounds;
1530
+ } | {
1531
+ readonly kind: "text";
1532
+ readonly position: DrawingPoint;
1533
+ readonly text: string;
1534
+ readonly price?: number;
1535
+ readonly align: "left" | "right" | "center";
1536
+ };
1537
+ export interface DrawingHandle {
1538
+ readonly anchorIndex: number;
1539
+ readonly point: DrawingPoint;
1540
+ }
1541
+ export interface DrawingGeometry {
1542
+ readonly id: string;
1543
+ readonly type: DrawingType;
1544
+ readonly locked: boolean;
1545
+ readonly primitives: readonly DrawingPrimitive[];
1546
+ readonly handles: readonly DrawingHandle[];
1547
+ readonly analysis?: DataDrivenDrawingResult;
1548
+ }
1549
+ export interface DrawingHit {
1550
+ readonly id: string;
1551
+ readonly anchorIndex: number | null;
1552
+ readonly distance: number;
1553
+ }
1554
+ export interface DrawingSnapshot {
1555
+ readonly drawings: readonly Drawing[];
1556
+ readonly selectedId: string | null;
1557
+ readonly canUndo: boolean;
1558
+ readonly canRedo: boolean;
1559
+ }
1560
+ export declare function drawingUsesText(type: DrawingType): boolean;
1561
+ export declare function drawingAnchorCount(type: DrawingType): number;
1562
+ /** Projection never edits retained anchors or history. Hosts may call it after any data/layout change. */
1563
+ export declare function projectDrawing(value: Drawing, project: DrawingProjector, bounds: DrawingBounds, context?: DrawingContext): DrawingGeometry | null;
1564
+ /** Only selected handles are interactive. Text labels have no arbitrary font-size hit boxes. */
1565
+ export declare function hitTestDrawingGeometry(geometries: readonly DrawingGeometry[], selectedId: string | null, point: DrawingPoint, tolerance?: number): DrawingHit | null;
1566
+ /** Immutable drawing snapshots share unchanged entries; bounded undo contains user edits only. */
1567
+ export declare class DrawingStore {
1568
+ private drawings;
1569
+ private selectedId;
1570
+ private past;
1571
+ private future;
1572
+ private readonly listeners;
1573
+ private readonly historyLimit;
1574
+ private snapshot;
1575
+ constructor(options?: {
1576
+ historyLimit?: number;
1577
+ });
1578
+ readonly getSnapshot: () => DrawingSnapshot;
1579
+ readonly subscribe: (listener: () => void) => (() => void);
1580
+ add(input: DrawingInput): Drawing;
1581
+ /** Locked anchors are unchanged until explicitly unlocked. Visibility remains editable. */
1582
+ update(id: string, patch: DrawingPatch): boolean;
1583
+ remove(id: string): boolean;
1584
+ clear(): boolean;
1585
+ select(id: string | null): boolean;
1586
+ undo(): boolean;
1587
+ redo(): boolean;
1588
+ exportJson(): string;
1589
+ /** Complete validation precedes changes. Layout restoration clears history unless explicitly a user edit. */
1590
+ importJson(json: string, options?: {
1591
+ recordHistory?: boolean;
1592
+ }): void;
1593
+ geometry(project: DrawingProjector, bounds: DrawingBounds, context?: DrawingContext): DrawingGeometry[];
1594
+ hitTest(point: DrawingPoint, project: DrawingProjector, bounds: DrawingBounds, tolerance?: number, context?: DrawingContext): DrawingHit | null;
1595
+ private commit;
1596
+ private publish;
1597
+ }
1598
+ export interface FrameIndicator {
1599
+ id: string;
1600
+ name: string;
1601
+ pane: string;
1602
+ figures: readonly IndicatorFigure[];
1603
+ rows: ReadonlyArray<Readonly<Record<string, number | null>>>;
1604
+ }
1605
+ export interface EngineLayout {
1606
+ axisGutter?: number;
1607
+ priceScale?: PriceScaleOptions;
1608
+ /** Portion of chart height used by price when indicator panes exist. */
1609
+ priceRatio?: number;
1610
+ /** Positive relative heights, keyed by the pane ids in EngineFrame. */
1611
+ paneWeights?: Readonly<Record<string, number>>;
1612
+ }
1613
+ export declare function validateEngineLayout(layout: EngineLayout): void;
1614
+ export interface EnginePane {
1615
+ id: string;
1616
+ top: number;
1617
+ height: number;
1618
+ frame: EngineRenderFrame;
1619
+ scale: PriceScale;
1620
+ }
1621
+ export interface EngineInspection {
1622
+ index: number;
1623
+ timestamp: number;
1624
+ mode: RealtimeViewSnapshot["mode"];
1625
+ displayBar: Readonly<MarketBar>;
1626
+ indicatorBasis: "raw";
1627
+ /** Actual values used by rendered figures, keyed by indicator instance id. */
1628
+ indicators: Readonly<Record<string, Readonly<Record<string, number | null>>>>;
1629
+ }
1630
+ export interface EngineRenderFrame {
1631
+ snapshot: RealtimeViewSnapshot;
1632
+ model: FinancialChartModel;
1633
+ inspect: (chartX: number) => EngineInspection | null;
1634
+ /** Lightweight renderer lookup; does not materialize all indicator rows. */
1635
+ inspectBar?: (chartX: number) => Omit<EngineInspection, "indicators" | "indicatorBasis"> | null;
1636
+ previousClose?: number;
1637
+ /** Indicator-only panes share time coordinates but never label an OHLC price. */
1638
+ indicatorPane?: boolean;
1639
+ title?: string;
1640
+ figureStyles?: ReadonlyMap<string, IndicatorFigure>;
1641
+ /** Derived once from this immutable snapshot, shared by panes and cursor paints. */
1642
+ pricePrecision?: number;
1643
+ }
1644
+ export interface EngineFrame extends EngineRenderFrame {
1645
+ /** Borrowed revealed raw bars and data revision for data-derived drawings. */
1646
+ drawingContext: DrawingContext;
1647
+ panes: readonly EnginePane[];
1648
+ project: (timestamp: number, price: number) => {
1649
+ x: number;
1650
+ y: number;
1651
+ } | null;
1652
+ unproject: (x: number, y: number) => {
1653
+ timestamp: number;
1654
+ price: number;
1655
+ } | null;
1656
+ }
1657
+ /** Visible-only geometry. Indicator computation and market history stay outside the renderer. */
1658
+ export declare function buildEngineFrame(snapshot: RealtimeViewSnapshot, rawBars: readonly MarketBar[], indicators: readonly FrameIndicator[], width: number, height: number, layout?: EngineLayout, previousClose?: number, dataRevision?: unknown): EngineFrame;
1659
+ export declare function projectAdditionalDrawing(value: Drawing, points: readonly DrawingPoint[], project: DrawingProjector, bounds: DrawingBounds, context: DrawingContext | undefined, sink: DrawingGeometrySink): void;
1660
+ /** Web renderer settings. Geometry, data ownership and native drawing stay in their own layers. */
1661
+ export declare const ENGINE_CHART_TYPES: readonly [
1662
+ "candles",
1663
+ "hollow-candles",
1664
+ "outline-candles",
1665
+ "hollow-down-candles",
1666
+ "ohlc",
1667
+ "volume-bars",
1668
+ "columns",
1669
+ "high-low",
1670
+ "line",
1671
+ "line-markers",
1672
+ "step-line",
1673
+ "area",
1674
+ "hlc-area",
1675
+ "baseline"
1676
+ ];
1677
+ export type EngineChartType = typeof ENGINE_CHART_TYPES[number];
1678
+ export interface EngineRenderOptions {
1679
+ chartType?: EngineChartType;
1680
+ /** Explicit dense-candle paint aggregation; raw prices and inspection stay unchanged. */
1681
+ candleDensity?: "raw" | "pixel-envelope";
1682
+ /** Baseline chart reference price; defaults to the first visible close. */
1683
+ baseline?: number;
1684
+ background?: string;
1685
+ grid?: string;
1686
+ text?: string;
1687
+ up?: string;
1688
+ down?: string;
1689
+ line?: string;
1690
+ font?: string;
1691
+ pricePrecision?: number;
1692
+ /** Viewer/display IANA timezone, used for intraday bars. Default UTC. */
1693
+ timeZone?: string;
1694
+ /** Actual feed period; day-and-larger labels represent market sessions. */
1695
+ timespan?: Timespan;
1696
+ /** SymbolInfo.timezone for daily/weekly/monthly/yearly session dates; default UTC. */
1697
+ symbolTimezone?: string;
1698
+ /** Internal pane composition can omit repeated time labels. */
1699
+ showTimeAxis?: boolean;
1700
+ formatPrice?: (price: number, precision: number) => string;
1701
+ }
1702
+ /** Timed playback for the owned loader; no renderer, DOM or global registry. */
1703
+ export interface ReplayLoaderLike {
1704
+ enterReplay: (at?: number) => boolean;
1705
+ exitReplay: () => void;
1706
+ replayStep: (delta: number) => void;
1707
+ readonly replaying: boolean;
1708
+ readonly replayAtEnd: boolean;
1709
+ readonly replayInfo: {
1710
+ index: number;
1711
+ length: number;
1712
+ timestamp: number;
1713
+ } | null;
1714
+ on?: (type: "replay", listener: (active: boolean) => void) => () => void;
1715
+ }
1716
+ export interface ReplayTimer {
1717
+ setTimeout: (callback: () => void, milliseconds: number) => unknown;
1718
+ clearTimeout: (handle: unknown) => void;
1719
+ }
1720
+ export interface TimedReplayState {
1721
+ readonly active: boolean;
1722
+ readonly index: number | null;
1723
+ readonly length: number;
1724
+ readonly timestamp: number | null;
1725
+ readonly atEnd: boolean;
1726
+ readonly playing: boolean;
1727
+ readonly speed: number;
1728
+ }
1729
+ export interface ReplayStartOptions {
1730
+ index?: number;
1731
+ timestamp?: number;
1732
+ }
1733
+ export interface TimedReplayOptions {
1734
+ loader: ReplayLoaderLike;
1735
+ /** Borrow the current data; restarting first exits replay to expose full history. */
1736
+ getDataList: () => ReadonlyArray<{
1737
+ timestamp: number;
1738
+ }>;
1739
+ /** Null while loading/unavailable; use the complete symbol + period identity. */
1740
+ getMarketKey: () => string | null;
1741
+ onChange?: (state: TimedReplayState) => void;
1742
+ timer?: ReplayTimer;
1743
+ }
1744
+ export interface TimedReplay {
1745
+ start: (options?: ReplayStartOptions) => boolean;
1746
+ startByTimestamp: (timestamp: number) => boolean;
1747
+ step: (delta?: number) => TimedReplayState;
1748
+ play: (speed?: number) => boolean;
1749
+ setSpeed: (speed: number) => void;
1750
+ pause: () => void;
1751
+ exit: () => void;
1752
+ getState: () => TimedReplayState;
1753
+ dispose: () => void;
1754
+ }
1755
+ export declare const REPLAY_BASE_STEP_MS = 600;
1756
+ /** Last loaded bar at or before an epoch-ms timestamp; clamps before the first to zero. */
1757
+ export declare function indexAtOrBefore(bars: ReadonlyArray<{
1758
+ timestamp: number;
1759
+ }>, timestamp: number): number;
1760
+ /** One scheduled step, never elapsed-time catch-up or synthetic price animation. */
1761
+ export declare function createTimedReplay(options: TimedReplayOptions): TimedReplay;
1762
+ export type CountdownPeriod = Pick<Period, "multiplier" | "timespan">;
1763
+ /** Fixed intraday elapsed time; daily+ advances the market's local calendar, preserving open time. */
1764
+ export declare function nextBarClose(openedAt: number, period: CountdownPeriod, symbolTimezone?: string): number | null;
1765
+ export declare function barRemaining(openedAt: number, period: CountdownPeriod, now: number, symbolTimezone?: string): number | null;
1766
+ export declare function formatCountdown(milliseconds: number): string;
1767
+ export interface CountdownContext {
1768
+ marketKey: string;
1769
+ lastBar: {
1770
+ timestamp: number;
1771
+ open: number;
1772
+ close: number;
1773
+ } | null;
1774
+ period: CountdownPeriod;
1775
+ symbolTimezone?: string;
1776
+ replaying?: boolean;
1777
+ enabled?: boolean;
1778
+ /** Undefined derives a period boundary; null explicitly marks an unknown session close. */
1779
+ closeTimestamp?: number | null;
1780
+ }
1781
+ export interface BarCountdownSnapshot {
1782
+ readonly marketKey: string;
1783
+ readonly openedAt: number;
1784
+ readonly closesAt: number;
1785
+ readonly remainingMs: number;
1786
+ readonly text: string;
1787
+ readonly price: number;
1788
+ readonly direction: "up" | "down" | "flat";
1789
+ }
1790
+ export declare function getBarCountdown(context: CountdownContext | null, now: number): BarCountdownSnapshot | null;
1791
+ export interface BarCountdownOptions {
1792
+ getContext: () => CountdownContext | null;
1793
+ onChange: (snapshot: BarCountdownSnapshot | null) => void;
1794
+ now?: () => number;
1795
+ timer?: ReplayTimer;
1796
+ hidden?: () => boolean;
1797
+ }
1798
+ export interface BarCountdown {
1799
+ refresh: () => void;
1800
+ getSnapshot: () => BarCountdownSnapshot | null;
1801
+ dispose: () => void;
1802
+ }
1803
+ /** Host refreshes on data, market, replay and visibility changes; no timer runs while unavailable. */
1804
+ export declare function createBarCountdown(options: BarCountdownOptions): BarCountdown;
1805
+ export interface WorkspaceMarket {
1806
+ symbol: SymbolInfo;
1807
+ period: Period;
1808
+ }
1809
+ export type WorkspaceLoadResult = {
1810
+ status: "loaded";
1811
+ symbol: SymbolInfo;
1812
+ period: Period;
1813
+ bars: number;
1814
+ } | {
1815
+ status: "unchanged";
1816
+ symbol: SymbolInfo;
1817
+ period: Period;
1818
+ } | {
1819
+ status: "superseded";
1820
+ by: WorkspaceMarket;
1821
+ } | {
1822
+ status: "error";
1823
+ symbol: SymbolInfo;
1824
+ period: Period;
1825
+ message: string;
1826
+ timeout: boolean;
1827
+ } | {
1828
+ status: "cancelled";
1829
+ symbol: SymbolInfo;
1830
+ period: Period;
1831
+ } | {
1832
+ status: "disposed";
1833
+ };
1834
+ export interface WorkspaceLoadState {
1835
+ requested: WorkspaceMarket;
1836
+ /** Data actually applied to the chart, including a settled empty result. */
1837
+ loaded: WorkspaceMarket | null;
1838
+ status: DataState | "cancelled";
1839
+ loadingMore: boolean;
1840
+ error: {
1841
+ message: string;
1842
+ phase: "initial" | "more" | "sync";
1843
+ timeout: boolean;
1844
+ } | null;
1845
+ }
1846
+ export interface WorkspaceReplayState {
1847
+ active: boolean;
1848
+ index: number | null;
1849
+ length: number;
1850
+ timestamp: number | null;
1851
+ atEnd: boolean;
1852
+ playing: boolean;
1853
+ speed: number;
1854
+ }
1855
+ export interface WorkspaceState {
1856
+ schema: 1;
1857
+ load: WorkspaceLoadState;
1858
+ replay: WorkspaceReplayState;
1859
+ data: {
1860
+ count: number;
1861
+ firstTimestamp: number | null;
1862
+ lastTimestamp: number | null;
1863
+ };
1864
+ view: {
1865
+ from: number;
1866
+ to: number;
1867
+ following: boolean;
1868
+ mode: CandleMode;
1869
+ };
1870
+ indicators: readonly EngineIndicatorInstance[];
1871
+ drawings: {
1872
+ count: number;
1873
+ selectedId: string | null;
1874
+ };
1875
+ }
1876
+ export interface WorkspaceEvents {
1877
+ marketChange: {
1878
+ previous: WorkspaceMarket;
1879
+ requested: WorkspaceMarket;
1880
+ };
1881
+ loadState: WorkspaceLoadState;
1882
+ loadResult: WorkspaceLoadResult;
1883
+ dataChange: {
1884
+ market: WorkspaceMarket;
1885
+ kind: "reset" | "prepend" | "tail";
1886
+ count: number;
1887
+ };
1888
+ replayChange: WorkspaceReplayState;
1889
+ }
1890
+ export declare function copyWorkspaceMarket(market: WorkspaceMarket): WorkspaceMarket;
1891
+ export declare function workspaceMarketKey(market: WorkspaceMarket): string;
1892
+ /**
1893
+ * Waits for the owner's actual data application, never for request dispatch.
1894
+ * Calls before the next microtask share one final market/outcome. A later
1895
+ * request supersedes the active batch. This queue does not fetch or abort;
1896
+ * DataLoader remains responsible for the network and its generation guards.
1897
+ */
1898
+ export declare class WorkspaceLoadQueue {
1899
+ private readonly schedule;
1900
+ private readonly reportSuperseded;
1901
+ private active;
1902
+ private disposed;
1903
+ constructor(schedule: (callback: () => void) => void, reportSuperseded: (result: WorkspaceLoadResult) => void);
1904
+ get pending(): boolean;
1905
+ current(market: WorkspaceMarket): Promise<WorkspaceLoadResult> | null;
1906
+ request(market: WorkspaceMarket): Promise<WorkspaceLoadResult>;
1907
+ private retireSuperseded;
1908
+ settle(market: WorkspaceMarket, result: WorkspaceLoadResult): boolean;
1909
+ cancel(): WorkspaceLoadResult | null;
1910
+ dispose(): void;
1911
+ }
1912
+ /** Microtask delivery avoids re-entering DataLoader halfway through applying a page. */
1913
+ export declare class WorkspaceEventBus {
1914
+ private readonly warn;
1915
+ private readonly schedule;
1916
+ private readonly listeners;
1917
+ constructor(warn: (...args: unknown[]) => void, schedule?: (callback: () => void) => void);
1918
+ on<K extends keyof WorkspaceEvents>(type: K, listener: (event: WorkspaceEvents[K]) => void): () => void;
1919
+ off<K extends keyof WorkspaceEvents>(type: K, listener: (event: WorkspaceEvents[K]) => void): void;
1920
+ emit<K extends keyof WorkspaceEvents>(type: K, event: WorkspaceEvents[K]): void;
1921
+ clear(): void;
1922
+ }
1923
+ /** Presentation only. Feed-derived date metadata and callback functions are never stored here. */
1924
+ export type WorkspaceSavedRender = Omit<EngineRenderOptions, "formatPrice" | "showTimeAxis" | "timespan" | "symbolTimezone">;
1925
+ export interface WorkspaceDrawingDocument {
1926
+ readonly version: 1;
1927
+ readonly drawings: readonly Drawing[];
1928
+ }
1929
+ export interface WorkspaceDocumentV1 {
1930
+ readonly version: 1;
1931
+ readonly symbol: Readonly<SymbolInfo>;
1932
+ readonly period: Readonly<Period>;
1933
+ readonly mode?: CandleMode;
1934
+ readonly render: Readonly<WorkspaceSavedRender>;
1935
+ readonly layout: Readonly<EngineLayout>;
1936
+ readonly indicators: readonly EngineIndicatorInstance[];
1937
+ readonly drawings: WorkspaceDrawingDocument;
1938
+ }
1939
+ export interface WorkspaceDocumentOptions {
1940
+ /** Explicitly registered custom definitions only; this does not register or execute them. */
1941
+ readonly registeredIndicatorNames?: readonly string[];
1942
+ }
1943
+ export declare const WORKSPACE_DOCUMENT_LIMITS: Readonly<{
1944
+ characters: number;
1945
+ nodes: 1100000;
1946
+ depth: 24;
1947
+ indicators: 64;
1948
+ params: 64;
1949
+ drawings: 1000;
1950
+ }>;
1951
+ /**
1952
+ * Parse untrusted JSON without storage, chart mutation, feed requests or custom
1953
+ * code execution. Returns detached frozen data, not a successful restoration.
1954
+ * The host must validate custom parameters through its registered definitions,
1955
+ * load the matching market, and validate data-dependent log/percentage scales
1956
+ * before replacing any live state. This schema never restores code or layers.
1957
+ */
1958
+ export declare function parseWorkspaceDocument(json: string, options?: WorkspaceDocumentOptions): WorkspaceDocumentV1;
1959
+ /** Existing zone detectors inspect later candles; cap their quadratic scan explicitly. */
1960
+ export declare const MARKET_ZONE_SCAN_LIMIT = 5000;
1961
+ export interface MarketOverlayOptions {
1962
+ volumeProfile?: boolean | {
1963
+ /** Equal price bins, from 1 to 200. @default 24 */
1964
+ rows?: number;
1965
+ /** Fraction of reported volume included in the value area. @default 0.7 */
1966
+ valueArea?: number;
1967
+ /** Fraction of plot width occupied by the largest bin. @default 0.2 */
1968
+ widthFraction?: number;
1969
+ };
1970
+ fairValueGaps?: boolean;
1971
+ orderBlocks?: boolean | {
1972
+ /** Prior candles defining the swing, from 1 to 1000. @default 10 */
1973
+ swingLookback?: number;
1974
+ /** Received candles allowed to confirm a break, from 1 to 1000. @default 3 */
1975
+ lookahead?: number;
1976
+ displacementFactor?: number;
1977
+ };
1978
+ }
1979
+ export type MarketOverlayStatus = "off" | "ready" | "empty" | "missing-volume" | "too-wide" | "invalid-data";
1980
+ export interface MarketOverlayRect {
1981
+ readonly x: number;
1982
+ readonly y: number;
1983
+ readonly width: number;
1984
+ readonly height: number;
1985
+ }
1986
+ export interface MarketProfileRow {
1987
+ readonly priceLow: number;
1988
+ readonly priceHigh: number;
1989
+ readonly volume: number;
1990
+ readonly pointOfControl: boolean;
1991
+ readonly inValueArea: boolean;
1992
+ /** Null when the price scale cannot project this bin or it is outside the plot. */
1993
+ readonly rect: MarketOverlayRect | null;
1994
+ }
1995
+ export interface MarketVolumeProfile {
1996
+ readonly rows: readonly MarketProfileRow[];
1997
+ readonly totalVolume: number;
1998
+ /** Missing/negative/nonfinite volume contributes zero, never invented activity. */
1999
+ readonly missingVolumeBars: number;
2000
+ readonly poc: number;
2001
+ readonly vah: number;
2002
+ readonly val: number;
2003
+ readonly pocY: number | null;
2004
+ readonly vahY: number | null;
2005
+ readonly valY: number | null;
2006
+ }
2007
+ export interface MarketZone {
2008
+ readonly kind: "fair-value-gap" | "order-block";
2009
+ readonly direction: "bullish" | "bearish";
2010
+ readonly status: "open" | "filled" | "mitigated";
2011
+ readonly startIndex: number;
2012
+ readonly endIndex: number;
2013
+ readonly confirmedAtIndex: number;
2014
+ readonly top: number;
2015
+ readonly bottom: number;
2016
+ readonly rect: MarketOverlayRect;
2017
+ }
2018
+ export interface MarketOverlayFrame {
2019
+ readonly bounds: Readonly<{
2020
+ left: number;
2021
+ right: number;
2022
+ top: number;
2023
+ bottom: number;
2024
+ }>;
2025
+ readonly profile: MarketVolumeProfile | null;
2026
+ readonly zones: readonly MarketZone[];
2027
+ readonly status: Readonly<{
2028
+ volumeProfile: MarketOverlayStatus;
2029
+ fairValueGaps: MarketOverlayStatus;
2030
+ orderBlocks: MarketOverlayStatus;
2031
+ }>;
2032
+ }
2033
+ /**
2034
+ * Pure, raw-OHLC projection, including in Heikin Ashi display mode. Volume is
2035
+ * distributed uniformly across each candle's price range, not actual trades
2036
+ * at each price. Missing volume is reported and contributes zero.
2037
+ *
2038
+ * FVG uses A/C separation and requires a later single candle to cover the
2039
+ * entire gap. Its scan starts two candles before the viewport and stops at
2040
+ * the visible right edge. Older gaps and fills outside that window are not
2041
+ * tracked. OB preserves the owned heuristic: an opposite candle followed by
2042
+ * a displacement breaking a prior swing. It does not infer order-book orders
2043
+ * or suppress superseded candidates. Its scan includes lookback/lookahead
2044
+ * margins, so already-received candles just right of the viewport may confirm
2045
+ * or mitigate a block. Mitigation means a later close inside the zone; its
2046
+ * rectangle continues to the viewport edge, because no mitigation index is
2047
+ * tracked by the detector. Replay callers must supply only revealed bars.
2048
+ *
2049
+ * No full-history scans or mutable calculation state. Zone scans beyond the
2050
+ * explicit limit return `too-wide`, never a silently truncated result.
2051
+ * Inputs must be the raw history corresponding to this frame's snapshot.
2052
+ */
2053
+ export declare function projectMarketOverlays(frame: EngineFrame, rawBars: readonly MarketBar[], options?: MarketOverlayOptions): MarketOverlayFrame;
2054
+ /** Pure, local raster resources only: no remote URL or SVG is decoded. Shared by the renderer-free drawing model and the Web image renderer. */
2055
+ export declare const DRAWING_IMAGE_LIMITS: Readonly<{
2056
+ encodedCharacters: number;
2057
+ dimension: 4096;
2058
+ pixels: number;
2059
+ cachedImages: 32;
2060
+ cachedPixels: number;
2061
+ }>;
2062
+ export interface Raster {
2063
+ mime: string;
2064
+ bytes: Uint8Array;
2065
+ width: number;
2066
+ height: number;
2067
+ }
2068
+ export declare const fail: () => never;
2069
+ export declare function dimensions(width: number, height: number): void;
2070
+ export declare function header(bytes: Uint8Array, mime: string): {
2071
+ width: number;
2072
+ height: number;
2073
+ };
2074
+ export declare function raster(source: unknown): Raster;
2075
+ /** Validates metadata before the browser decoder can allocate a large bitmap. */
2076
+ export declare function validateDrawingImage(value: unknown): string;
2077
+ export type FreehandTool = "brush" | "highlighter";
2078
+ export interface FreehandDrawing {
2079
+ readonly id: string;
2080
+ readonly type: FreehandTool;
2081
+ readonly anchors: readonly DrawingAnchor[];
2082
+ readonly locked: boolean;
2083
+ readonly hidden: boolean;
2084
+ readonly strokeWidth?: number;
2085
+ }
2086
+ export interface FreehandPrimitive {
2087
+ readonly kind: "stroke";
2088
+ readonly points: readonly DrawingPoint[];
2089
+ readonly width: number;
2090
+ readonly opacity: number;
2091
+ readonly clip: DrawingBounds;
2092
+ }
2093
+ export declare const MAX_FREEHAND_POINTS = 2048;
2094
+ /** Timestamp/price paths use the current financial projection, never retained screen pixels. */
2095
+ export declare function projectFreehandDrawing(drawing: {
2096
+ readonly type: string;
2097
+ readonly anchors: readonly DrawingAnchor[];
2098
+ readonly hidden: boolean;
2099
+ readonly strokeWidth?: number;
2100
+ }, project: DrawingProjector, bounds: DrawingBounds): FreehandPrimitive | null;
2101
+ /** The context requesting a financial date label. */
2102
+ export type BarDateRequestType = "xAxis" | "crosshair" | "tooltip";
2103
+ export interface FormatBarDateParams {
2104
+ /** The viewer's display-timezone formatter. */
2105
+ displayDtf: Intl.DateTimeFormat;
2106
+ /** SymbolInfo.timezone; undefined (and anything Intl rejects) is read as 'UTC'. */
2107
+ symbolTimezone: string | undefined;
2108
+ timespan: Timespan;
2109
+ timestamp: number;
2110
+ /** Requested axis pattern, e.g. 'HH:mm', 'YYYY-MM', 'MM-DD'. */
2111
+ format: string;
2112
+ type: BarDateRequestType;
2113
+ }
2114
+ /**
2115
+ * Day-and-larger bars are
2116
+ * read in `symbolTimezone` (default UTC); minute and hour bars keep
2117
+ * `displayDtf` unchanged, and a minute chart's boundary-format requests
2118
+ * ('YYYY' / 'YYYY-MM' / 'MM-DD') are answered instead of forced to 'HH:mm'.
2119
+ */
2120
+ export declare function formatBarDate(p: FormatBarDateParams): string;
2121
+ export interface Bar {
2122
+ high: number;
2123
+ low: number;
2124
+ }
2125
+ export type FvgDirection = "bullish" | "bearish";
2126
+ export interface FairValueGap {
2127
+ /** Index of candle A (the gap spans A/B/C, indices i, i+1, i+2). */
2128
+ index: number;
2129
+ top: number;
2130
+ bottom: number;
2131
+ direction: FvgDirection;
2132
+ /** True once any later bar's range has traded back through the full gap (SC-NEXT: "extending until filled"). */
2133
+ filled: boolean;
2134
+ /** Index of the bar that filled it, or null while still open. */
2135
+ filledAtIndex: number | null;
2136
+ }
2137
+ /**
2138
+ * Detects every 3-candle FVG in `bars`. A gap is "filled" the first time a
2139
+ * later bar's [low, high] covers the ENTIRE gap (partial fills are common in
2140
+ * practice but the common convention — and the simplest, most defensible
2141
+ * OHLCV-only rule — treats the gap as open until fully covered).
2142
+ */
2143
+ export declare function detectFairValueGaps(bars: readonly Bar[]): FairValueGap[];
2144
+ export interface Bar {
2145
+ high: number;
2146
+ low: number;
2147
+ open: number;
2148
+ close: number;
2149
+ }
2150
+ export type OrderBlockDirection = "bullish" | "bearish";
2151
+ export interface OrderBlock {
2152
+ /** Index of the order-block candle itself (the last opposite candle before the move). */
2153
+ index: number;
2154
+ high: number;
2155
+ low: number;
2156
+ direction: OrderBlockDirection;
2157
+ /** Index of the candle whose close broke structure (confirming this block). */
2158
+ breakIndex: number;
2159
+ /** True once a later close has re-entered [low, high] (SMC "mitigation"). */
2160
+ mitigated: boolean;
2161
+ }
2162
+ export interface OrderBlockOptions {
2163
+ /** How many bars ahead of the candidate candle count as "the move" that must break structure. @default 3 */
2164
+ lookahead?: number;
2165
+ /** The move's total range must be at least this multiple of the candidate candle's own range to count as a displacement, not noise. @default 1.5 */
2166
+ displacementFactor?: number;
2167
+ /** How many bars back to look for the swing high/low the move must break. @default 10 */
2168
+ swingLookback?: number;
2169
+ }
2170
+ /**
2171
+ * Detects order blocks over the whole `bars` array (callers pass whatever
2172
+ * window — e.g. the visible range plus lookback — they want scanned).
2173
+ * Bullish: a down candle (close < open) immediately before an up-move whose
2174
+ * close breaks above the prior `swingLookback` bars' high, moving at least
2175
+ * `displacementFactor`x the candidate's own range within `lookahead` bars.
2176
+ * Bearish is the mirror image. A candidate already superseded by a fresher
2177
+ * one of the same direction before its own break is skipped (SMC keeps the
2178
+ * most recent unmitigated block, not every historical one).
2179
+ */
2180
+ export declare function detectOrderBlocks(bars: readonly Bar[], options?: OrderBlockOptions): OrderBlock[];
2181
+ export interface Bar {
2182
+ timestamp: number;
2183
+ high: number;
2184
+ low: number;
2185
+ }
2186
+ export type RangePeriod = "day" | "week";
2187
+ export interface PreviousRangeResult {
2188
+ high: number;
2189
+ low: number;
2190
+ /** The period key (a date string) this high/low covers, for display/debugging. */
2191
+ key: string;
2192
+ fromIndex: number;
2193
+ toIndex: number;
2194
+ }
2195
+ /**
2196
+ * The high/low of the period immediately before the one the LAST bar in
2197
+ * `bars` falls in (ascending, as klinecharts requires). Null when there is
2198
+ * no earlier period at all (e.g. the whole list is one day old).
2199
+ */
2200
+ export declare function previousRangeHighLow(bars: readonly Bar[], period: RangePeriod, tz: string): PreviousRangeResult | null;
2201
+ /**
2202
+ * Volume-by-price binning shared by the fixedRangeVolumeProfile and
2203
+ * anchoredVolumeProfile drawing tools (src/extension/volumeTools.ts) and by
2204
+ * SC_VRVP (SC-171). Pure: no klinecharts, no canvas, no chart access, so it is
2205
+ * unit-testable on its own and cannot pull in the two tools' chartRef/dataIndex
2206
+ * concerns (owned elsewhere; see the batch's overlap note).
2207
+ *
2208
+ * Each bar's volume is spread across every row its [low, high] range touches,
2209
+ * in proportion to the overlap — not dropped into one "typical price" row,
2210
+ * which put the POC (the widest row) off by several percent of the range on
2211
+ * synthetic and real data alike. POC is the row with the most volume; the
2212
+ * value area expands out from it, one row at a time on whichever side has
2213
+ * more volume, until it holds `valueArea` (default 70%) of the total.
2214
+ *
2215
+ * Part of Super Chart.
2216
+ */
2217
+ export interface VolumeProfileBar {
2218
+ high: number;
2219
+ low: number;
2220
+ volume: number;
2221
+ }
2222
+ export interface VolumeProfileRow {
2223
+ priceLow: number;
2224
+ priceHigh: number;
2225
+ volume: number;
2226
+ }
2227
+ export interface VolumeProfileResult {
2228
+ rows: VolumeProfileRow[];
2229
+ /** The row with the most volume (its midpoint). NaN when there is no data. */
2230
+ poc: number;
2231
+ /** Value-area high/low bounds. NaN when there is no data. */
2232
+ vah: number;
2233
+ val: number;
2234
+ pmin: number;
2235
+ pmax: number;
2236
+ }
2237
+ export interface VolumeProfileOptions {
2238
+ rows?: number;
2239
+ /** Fraction of total volume the value area should hold. @default 0.7 */
2240
+ valueArea?: number;
2241
+ }
2242
+ /** Bins `bars` by price into `rows` equal-height rows across [lowest low, highest high]. */
2243
+ export declare function volumeProfile(bars: readonly VolumeProfileBar[], options?: VolumeProfileOptions): VolumeProfileResult;
2244
+ /** Fractional candle coordinates. Sampling stays integral; movement does not. */
2245
+ export declare function clampContinuousViewport(value: Viewport, length: number, limits?: ViewportLimits): Viewport;
2246
+ export declare function zoomContinuousViewport(value: Viewport, length: number, factor: number, anchor: number, limits?: ViewportLimits): Viewport;
2247
+ /** Explicit named functions keep generated declarations independent of module namespaces. */
2248
+ export declare const ta: Readonly<{
2249
+ isLength: typeof isLength;
2250
+ sum: typeof sum;
2251
+ sma: typeof sma;
2252
+ wma: typeof wma;
2253
+ hma: typeof hma;
2254
+ vwma: typeof vwma;
2255
+ ema: typeof ema;
2256
+ rma: typeof rma;
2257
+ rsi: typeof rsi;
2258
+ macd: typeof macd;
2259
+ stdev: typeof stdev;
2260
+ dev: typeof dev;
2261
+ bollinger: typeof bollinger;
2262
+ highest: typeof highest;
2263
+ lowest: typeof lowest;
2264
+ linreg: typeof linreg;
2265
+ correlation: typeof correlation;
2266
+ change: typeof change;
2267
+ mom: typeof mom;
2268
+ roc: typeof roc;
2269
+ crossover: typeof crossover;
2270
+ crossunder: typeof crossunder;
2271
+ cross: typeof cross;
2272
+ cum: typeof cum;
2273
+ barssince: typeof barssince;
2274
+ valuewhen: typeof valuewhen;
2275
+ pivot: typeof pivot;
2276
+ trueRange: typeof trueRange;
2277
+ atr: typeof atr;
2278
+ obv: typeof obv;
2279
+ vwap: typeof vwap;
2280
+ cci: typeof cci;
2281
+ mfi: typeof mfi;
2282
+ stochK: typeof stochK;
2283
+ sar: typeof sar;
2284
+ stoch: typeof stoch;
2285
+ stochRsi: typeof stochRsi;
2286
+ bbPercent: typeof bbPercent;
2287
+ keltner: typeof keltner;
2288
+ donchian: typeof donchian;
2289
+ atrBands: typeof atrBands;
2290
+ supertrend: typeof supertrend;
2291
+ ichimoku: typeof ichimoku;
2292
+ anchoredVwap: typeof anchoredVwap;
2293
+ }>;
2294
+
2295
+ export {
2296
+ indicatorSeries as nativeIndicatorSeries,
2297
+ };
2298
+
2299
+ export {};