@supersolutions/super-chart-superscript 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,354 @@
1
+ import { Series } from '@supersolutions/super-chart-core';
2
+
3
+ /**
4
+ * SuperScript diagnostics: every problem has a severity, a code, a message and
5
+ * a 1-based position, so a person, an editor or an AI repair loop can act on
6
+ * it. Part of Super Chart.
7
+ */
8
+ export type DiagnosticSeverity = "error" | "warning";
9
+ /**
10
+ * Codes are stable; messages may be reworded.
11
+ *
12
+ * Errors (the script does not compile):
13
+ * UNEXPECTED_CHAR, UNTERMINATED_STRING, UNEXPECTED_TOKEN, TRAILING_TOKENS,
14
+ * UNBALANCED, REASSIGNMENT (`:=`, `+=`, …), CONTROL_FLOW (`if`, `for`, …),
15
+ * FUNCTION_DEF (`f(x) => …`), BUILTIN_REASSIGNED, UNKNOWN_IDENTIFIER,
16
+ * UNKNOWN_FUNCTION, ARITY, UNKNOWN_ARGUMENT, DUPLICATE_ARGUMENT,
17
+ * EXPECTED_CONSTANT, BAD_LENGTH, BAD_OFFSET, TYPE, PINE_MISMATCH,
18
+ * UNSUPPORTED, STATEMENT (`plot()` inside an expression).
19
+ *
20
+ * Warnings (the script compiles; the part named is ignored):
21
+ * IGNORED_STATEMENT (plotshape, bgcolor, strategy.*, …), UNUSED_EXPRESSION,
22
+ * IGNORED_KEYWORD (var, float, …), UNKNOWN_KEYWORD (an unknown plot()
23
+ * keyword), NO_PLOTS.
24
+ */
25
+ export type DiagnosticCode = "UNEXPECTED_CHAR" | "UNTERMINATED_STRING" | "UNEXPECTED_TOKEN" | "TRAILING_TOKENS" | "UNBALANCED" | "REASSIGNMENT" | "CONTROL_FLOW" | "FUNCTION_DEF" | "BUILTIN_REASSIGNED" | "UNKNOWN_IDENTIFIER" | "UNKNOWN_FUNCTION" | "ARITY" | "UNKNOWN_ARGUMENT" | "DUPLICATE_ARGUMENT" | "EXPECTED_CONSTANT" | "BAD_LENGTH" | "BAD_OFFSET" | "TYPE" | "PINE_MISMATCH" | "UNSUPPORTED" | "STATEMENT" | "IGNORED_STATEMENT" | "UNUSED_EXPRESSION" | "IGNORED_KEYWORD" | "UNKNOWN_KEYWORD" | "NO_PLOTS";
26
+ export interface Diagnostic {
27
+ severity: DiagnosticSeverity;
28
+ code: DiagnosticCode;
29
+ message: string;
30
+ /** 1-based line. */
31
+ line: number;
32
+ /** 1-based column of the first character. */
33
+ col: number;
34
+ /** 1-based column just past the last character. */
35
+ endCol: number;
36
+ /** A suggested fix, when there is one. */
37
+ hint?: string;
38
+ }
39
+ /**
40
+ * Thrown by `compile()` for the first error (all diagnostics are on
41
+ * `diagnostics`) and by `run()` for a problem that only shows with real
42
+ * parameters. Identify it with `isSuperScriptError(e)`: the `.` and `./lite`
43
+ * CommonJS/UMD builds each carry their own copy of this class, so
44
+ * `instanceof` can miss.
45
+ */
46
+ export declare class SuperScriptError extends Error {
47
+ readonly code: DiagnosticCode;
48
+ readonly line: number;
49
+ readonly col: number;
50
+ readonly endCol: number;
51
+ readonly hint?: string;
52
+ readonly diagnostics: Diagnostic[];
53
+ constructor(diagnostic: Diagnostic, diagnostics?: Diagnostic[]);
54
+ }
55
+ /** True for a SuperScriptError from any copy of this package. */
56
+ export declare function isSuperScriptError(e: unknown): e is SuperScriptError;
57
+ /**
58
+ * Diagnostics as text, one per problem, each with its source line and a caret
59
+ * under the span: what a model needs to repair its script.
60
+ */
61
+ export declare function formatDiagnostics(diagnostics: readonly Diagnostic[], source?: string): string;
62
+ export interface Bar {
63
+ timestamp: number;
64
+ open: number;
65
+ high: number;
66
+ low: number;
67
+ close: number;
68
+ volume?: number;
69
+ }
70
+ export interface PlotStyle {
71
+ color?: string;
72
+ lineWidth?: number;
73
+ type?: "line" | "histogram" | "circle";
74
+ /** Where a histogram's bars start (default 0). On a log- or percentage-scaled
75
+ * price pane 0 is off the scale and the bars vanish: set it to a price there. */
76
+ histbase?: number;
77
+ /** Line dash; hline() levels are dashed. */
78
+ lineStyle?: "solid" | "dashed" | "dotted";
79
+ }
80
+ export interface Plot {
81
+ id: string;
82
+ title: string;
83
+ values: Series;
84
+ style?: PlotStyle;
85
+ /** "hline" for a constant level drawn with hline(). */
86
+ kind?: "plot" | "hline";
87
+ }
88
+ /** One `input()` of a script: what a settings form or an agent can change. */
89
+ export interface ScriptInput {
90
+ /** The name it is bound to (`len = input(14)` → "len"), else "in<index>". */
91
+ id: string;
92
+ title: string;
93
+ defval: number;
94
+ min?: number;
95
+ max?: number;
96
+ step?: number;
97
+ type: "int" | "float";
98
+ }
99
+ /** Input values for `run()`: by position (the order of `meta.inputs`) or by input id. */
100
+ export type ScriptParams = ReadonlyArray<number | null | undefined> | Readonly<Record<string, number | null | undefined>>;
101
+ export interface ScriptMeta {
102
+ title: string;
103
+ /** The script's inputs in source order (SuperScript). */
104
+ inputs?: ScriptInput[];
105
+ /** True when the script declares `// @overlay` (it plots on the price scale). */
106
+ overlay?: boolean;
107
+ }
108
+ export interface ScriptResult {
109
+ meta: ScriptMeta;
110
+ plots: Plot[];
111
+ /** Warnings from compiling the script (SuperScript). */
112
+ diagnostics?: Diagnostic[];
113
+ }
114
+ /** A pluggable script language (SuperScript, JavaScript, …). */
115
+ export interface ScriptLanguage {
116
+ id: string;
117
+ name: string;
118
+ compile(source: string): CompiledScript;
119
+ }
120
+ export interface CompiledScript {
121
+ meta: ScriptMeta;
122
+ /** Evaluate over bars. `params` overrides the inputs (clamped to their minval/maxval). */
123
+ run(bars: Bar[], params?: ScriptParams): ScriptResult;
124
+ /** Warnings (a script with errors does not compile). */
125
+ diagnostics?: Diagnostic[];
126
+ }
127
+ export interface CompileOptions {
128
+ /** Throw on warnings too (ignored statements, unknown plot keywords, …). */
129
+ strict?: boolean;
130
+ }
131
+ /**
132
+ * Every problem in a SuperScript source, errors and warnings, each with its
133
+ * line, column and (often) a hint. Never throws; an empty list means the
134
+ * script compiles cleanly. This is what an editor or an AI repair loop reads.
135
+ */
136
+ export declare function checkSuperScript(source: string): Diagnostic[];
137
+ export declare const SuperScriptLanguage: ScriptLanguage & {
138
+ compile: (source: string, options?: CompileOptions) => CompiledScript;
139
+ };
140
+ /** JavaScript language adapter — the script body is `(ctx) => ScriptResult`.
141
+ * Not registered by default: `registerLanguage(JavaScriptLanguage)` opts in.
142
+ * It evaluates the source with `new Function` in the host page (full code
143
+ * execution); never pass it a script from a model, a user or a tool call. */
144
+ export declare const JavaScriptLanguage: ScriptLanguage;
145
+ /** Human/LLM-readable catalog of the SuperScript vocabulary, generated from the
146
+ * same signature table the checker uses, so the docs and the AI system prompt
147
+ * cannot drift from the language. */
148
+ export declare function superscriptReference(): string;
149
+ export declare const superlib: {
150
+ sma: (src: Series, len: number) => Series;
151
+ ema: (src: Series, len: number) => Series;
152
+ rsi: (src: Series, len: number) => Series;
153
+ highest: (src: Series, len: number) => Series;
154
+ lowest: (src: Series, len: number) => Series;
155
+ crossover: (a: Series, b: Series) => Series;
156
+ crossunder: (a: Series, b: Series) => Series;
157
+ wma: (src: Series, len: number) => Series;
158
+ stdev: (src: Series, len: number) => Series;
159
+ change: (src: Series) => Series;
160
+ roc: (src: Series, len: number) => Series;
161
+ tr: (high: Series, low: Series, close: Series) => Series;
162
+ atr: (high: Series, low: Series, close: Series, len: number) => Series;
163
+ sum: (src: Series, len: number) => Series;
164
+ dev: (src: Series, len: number) => Series;
165
+ mom: (src: Series, len: number) => Series;
166
+ linreg: (src: Series, len: number, offset?: number | undefined) => Series;
167
+ rma: (src: Series, len: number) => Series;
168
+ hma: (src: Series, len: number) => Series;
169
+ vwma: (src: Series, volume: Series, len: number) => Series;
170
+ };
171
+ export interface AICompleteInput {
172
+ system?: string;
173
+ prompt: string;
174
+ /** Cancels the request. Clients must not serialise it into the request. */
175
+ signal?: AbortSignal;
176
+ }
177
+ /** The single seam the host implements to plug a model into SUPer-Chart. */
178
+ export interface AIClient {
179
+ complete: (input: AICompleteInput) => Promise<string>;
180
+ }
181
+ export interface HttpAIClientOptions {
182
+ endpoint: string;
183
+ headers?: Record<string, string>;
184
+ /** Abort a request that takes longer (rejects with a "TimeoutError"). */
185
+ timeoutMs?: number;
186
+ /**
187
+ * Map a response body to the model's text when it is none of the shapes the
188
+ * client reads itself (a string, `{ text }`, `{ content: string }`, or
189
+ * Anthropic's `{ content: [{ type: "text", text }] }`), e.g. OpenAI's
190
+ * `{ choices }`.
191
+ */
192
+ extract?: (data: unknown) => string;
193
+ }
194
+ /** An `AIClient` that POSTs `{ system, prompt }` to a host endpoint and reads back
195
+ * the model's text. Keeps model keys on the host/server. It rejects (instead of
196
+ * returning "" or "[object Object]") on an HTTP error, a body with an `error`,
197
+ * a body it cannot read, or empty text. */
198
+ export declare function createHttpAIClient(opts: HttpAIClientOptions): AIClient;
199
+ export declare const SUPERSCRIPT_SYSTEM_PROMPT: string;
200
+ export interface AIRequestOptions {
201
+ signal?: AbortSignal;
202
+ }
203
+ /**
204
+ * Natural language → a SuperScript indicator (script source). The reply is
205
+ * compiled before it is returned: a reply that is not a valid script, or that
206
+ * draws nothing (prose, "", "[object Object]"), rejects with the error and the
207
+ * start of the reply, so it never reaches registerScriptIndicator. For a
208
+ * repair loop use nlToSuperScriptChecked.
209
+ */
210
+ export declare function nlToSuperScript(client: AIClient, request: string, opts?: AIRequestOptions): Promise<string>;
211
+ export interface CheckedScript {
212
+ /** True when the last script compiles and draws something. */
213
+ ok: boolean;
214
+ /** The last script the model returned. */
215
+ source: string;
216
+ /** Its diagnostics (errors and warnings). */
217
+ diagnostics: Diagnostic[];
218
+ /** Model calls made (1 + repairs). */
219
+ attempts: number;
220
+ }
221
+ /**
222
+ * nlToSuperScript with a bounded repair loop: when the script has errors (or
223
+ * draws nothing), the diagnostics — line, column and the offending source
224
+ * line — go back to the model, up to `maxRepairs` times (default 2). Each
225
+ * repair is another model call the host pays for; nothing retries unless the
226
+ * host calls this. Never throws for a bad script: read `ok`.
227
+ */
228
+ export declare function nlToSuperScriptChecked(client: AIClient, request: string, opts?: AIRequestOptions & {
229
+ maxRepairs?: number;
230
+ }): Promise<CheckedScript>;
231
+ /** How analyzeChart writes the bars (set by buildChartContext); absent = the v1 format. */
232
+ export interface ChartContextFormat {
233
+ pricePrecision?: number;
234
+ volumePrecision?: number;
235
+ /** IANA time zone the times are written in (default UTC). */
236
+ timezone?: string;
237
+ /** Data indexes of the visible window, [from, to). */
238
+ visibleFrom?: number;
239
+ visibleTo?: number;
240
+ /** Bars per row (1 = not aggregated). */
241
+ bucket?: number;
242
+ /** Bars before aggregation. */
243
+ sourceBars?: number;
244
+ /** Leading rows that are context before the visible window. */
245
+ contextRows?: number;
246
+ }
247
+ export interface ChartContext {
248
+ symbol: string;
249
+ period: string;
250
+ bars: Bar[];
251
+ /** Optional indicators already on the chart, for context. */
252
+ indicators?: string[];
253
+ /** Compact serialisation (rounded, indexed rows, aggregated). Set by buildChartContext. */
254
+ format?: ChartContextFormat;
255
+ }
256
+ /** What buildChartContext reads from a chart; a klinecharts Chart has both. */
257
+ export interface ChartDataSource {
258
+ getDataList: () => readonly Bar[];
259
+ getVisibleRange: () => {
260
+ from: number;
261
+ to: number;
262
+ };
263
+ }
264
+ export interface SymbolLike {
265
+ ticker: string;
266
+ pricePrecision?: number | "auto";
267
+ volumePrecision?: number;
268
+ }
269
+ export interface PeriodLike {
270
+ multiplier: number;
271
+ timespan: string;
272
+ text?: string;
273
+ }
274
+ /** A SuperChart (or anything with the same getters). */
275
+ export interface ChartProLike {
276
+ getChart: () => ChartDataSource | null;
277
+ getSymbol: () => SymbolLike;
278
+ getPeriod: () => PeriodLike;
279
+ getTimezone: () => string;
280
+ }
281
+ /**
282
+ * A `ChartWorkspace` from super-chart-web, or anything shaped like one: `buildChartContext(workspace)` reads the
283
+ * bars on screen from its viewport and the display time zone from its render options.
284
+ */
285
+ export interface ChartWorkspaceLike {
286
+ getBars: (options?: {
287
+ limit?: number;
288
+ }) => readonly Bar[];
289
+ getSymbol: () => SymbolLike;
290
+ getPeriod: () => PeriodLike;
291
+ chart: {
292
+ view: {
293
+ getSnapshot: () => {
294
+ viewport: {
295
+ i0: number;
296
+ i1: number;
297
+ };
298
+ };
299
+ };
300
+ getRenderOptions?: () => {
301
+ timeZone?: string;
302
+ };
303
+ };
304
+ }
305
+ export interface ChartContextParts {
306
+ chart: ChartDataSource;
307
+ symbol: SymbolLike;
308
+ period: PeriodLike | string;
309
+ timezone?: string;
310
+ }
311
+ export interface ChartContextOptions {
312
+ /** 'visible' (default): the bars on screen; 'all'; or data indexes [from, to). */
313
+ range?: "visible" | "all" | {
314
+ from: number;
315
+ to: number;
316
+ };
317
+ /** Most rows to send (default 200); more bars are aggregated into OHLCV buckets. */
318
+ maxBars?: number;
319
+ /**
320
+ * Bars before the range to include, labelled as context (default 0). When
321
+ * rows are aggregated the context is whole rows ending at the first visible
322
+ * bar: rounded up to whole rows, fewer when the data starts sooner, none
323
+ * when not even one row fits or maxBars is 1.
324
+ */
325
+ lookback?: number;
326
+ indicators?: string[];
327
+ }
328
+ /**
329
+ * The ChartContext for analyzeChart from a chart: the bars the user sees (not
330
+ * the newest 160), aggregated into at most `maxBars` OHLCV rows when zoomed
331
+ * out, with the symbol's precision and the chart's time zone so the prompt
332
+ * is short and exact. Works with a SuperChart or `{ chart, symbol, period }`
333
+ * around any klinecharts Chart (./lite).
334
+ */
335
+ export declare function buildChartContext(source: ChartProLike | ChartWorkspaceLike | ChartContextParts, opts?: ChartContextOptions): ChartContext;
336
+ export declare const ANALYST_SYSTEM_PROMPT = "You are a professional markets analyst embedded in a trading chart.\nBe concise and concrete. Reference price structure, key support/resistance, momentum,\nand lay out the most likely scenarios with invalidation levels. Never give financial\nadvice or position sizing \u2014 describe the chart, not what the user should do.";
337
+ /** Analyse the candles in `ctx` (buildChartContext gives the visible ones). `question` is optional follow-up context. */
338
+ export declare function analyzeChart(client: AIClient, ctx: ChartContext, question?: string, opts?: AIRequestOptions): Promise<string>;
339
+ /**
340
+ * Register a script language and enable it on this entry. This is the only
341
+ * way to run anything but SuperScript through `./superscript`.
342
+ */
343
+ export declare function registerLanguage(lang: ScriptLanguage): void;
344
+ /** The language with this id, if it is enabled on this entry. */
345
+ export declare function getLanguage(id: string): ScriptLanguage | undefined;
346
+ /** The languages enabled on this entry (SuperScript plus any the host registered here). */
347
+ export declare function listLanguages(): ScriptLanguage[];
348
+ /**
349
+ * Compile and run a script. Throws for a language that is not enabled on this
350
+ * entry, including `"javascript"` unless the host registered it here.
351
+ */
352
+ export declare function runScript(source: string, bars: Bar[], languageId?: string, params?: ScriptParams): ScriptResult;
353
+
354
+ export {};