oakscriptjs 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/box/index.d.ts +3 -3
- package/dist/cjs/box/index.d.ts.map +1 -1
- package/dist/cjs/box/index.js.map +2 -2
- package/dist/cjs/check/harness.d.ts.map +1 -1
- package/dist/cjs/check/harness.js +35 -1
- package/dist/cjs/check/harness.js.map +2 -2
- package/dist/cjs/drawing/output.d.ts +2 -1
- package/dist/cjs/drawing/output.d.ts.map +1 -1
- package/dist/cjs/drawing/output.js +5 -4
- package/dist/cjs/drawing/output.js.map +2 -2
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/label/index.d.ts +2 -2
- package/dist/cjs/label/index.d.ts.map +1 -1
- package/dist/cjs/label/index.js.map +2 -2
- package/dist/cjs/line/index.d.ts +4 -4
- package/dist/cjs/line/index.d.ts.map +1 -1
- package/dist/cjs/line/index.js +1 -1
- package/dist/cjs/line/index.js.map +2 -2
- package/dist/cjs/polyline/index.d.ts +2 -2
- package/dist/cjs/polyline/index.d.ts.map +1 -1
- package/dist/cjs/polyline/index.js.map +2 -2
- package/dist/cjs/script/constants.d.ts +6 -1
- package/dist/cjs/script/constants.d.ts.map +1 -1
- package/dist/cjs/script/constants.js +2 -1
- package/dist/cjs/script/constants.js.map +2 -2
- package/dist/cjs/script/globals.d.ts +3 -0
- package/dist/cjs/script/globals.d.ts.map +1 -1
- package/dist/cjs/script/globals.js.map +1 -1
- package/dist/cjs/script/index.d.ts +255 -28
- package/dist/cjs/script/index.d.ts.map +1 -1
- package/dist/cjs/script/index.js +349 -34
- package/dist/cjs/script/index.js.map +3 -3
- package/dist/cjs/security/events.d.ts +16 -0
- package/dist/cjs/security/events.d.ts.map +1 -0
- package/dist/cjs/security/events.js +84 -0
- package/dist/cjs/security/events.js.map +7 -0
- package/dist/cjs/types/index.d.ts +13 -11
- package/dist/cjs/types/index.d.ts.map +1 -1
- package/dist/cjs/types/index.js +3 -1
- package/dist/cjs/types/index.js.map +2 -2
- package/dist/cjs/types/metadata.d.ts +12 -8
- package/dist/cjs/types/metadata.d.ts.map +1 -1
- package/dist/cjs/types/metadata.js.map +1 -1
- package/dist/esm/box/index.d.ts +3 -3
- package/dist/esm/box/index.d.ts.map +1 -1
- package/dist/esm/box/index.js +1 -1
- package/dist/esm/box/index.js.map +1 -1
- package/dist/esm/check/harness.d.ts.map +1 -1
- package/dist/esm/check/harness.js +25 -0
- package/dist/esm/check/harness.js.map +1 -1
- package/dist/esm/drawing/output.d.ts +2 -1
- package/dist/esm/drawing/output.d.ts.map +1 -1
- package/dist/esm/drawing/output.js +9 -7
- package/dist/esm/drawing/output.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/label/index.d.ts +2 -2
- package/dist/esm/label/index.d.ts.map +1 -1
- package/dist/esm/label/index.js.map +1 -1
- package/dist/esm/line/index.d.ts +4 -4
- package/dist/esm/line/index.d.ts.map +1 -1
- package/dist/esm/line/index.js +3 -3
- package/dist/esm/line/index.js.map +1 -1
- package/dist/esm/polyline/index.d.ts +2 -2
- package/dist/esm/polyline/index.d.ts.map +1 -1
- package/dist/esm/polyline/index.js +1 -1
- package/dist/esm/polyline/index.js.map +1 -1
- package/dist/esm/script/constants.d.ts +6 -1
- package/dist/esm/script/constants.d.ts.map +1 -1
- package/dist/esm/script/constants.js +6 -1
- package/dist/esm/script/constants.js.map +1 -1
- package/dist/esm/script/globals.d.ts +3 -0
- package/dist/esm/script/globals.d.ts.map +1 -1
- package/dist/esm/script/globals.js.map +1 -1
- package/dist/esm/script/index.d.ts +255 -28
- package/dist/esm/script/index.d.ts.map +1 -1
- package/dist/esm/script/index.js +370 -38
- package/dist/esm/script/index.js.map +1 -1
- package/dist/esm/security/events.d.ts +16 -0
- package/dist/esm/security/events.d.ts.map +1 -0
- package/dist/esm/security/events.js +78 -0
- package/dist/esm/security/events.js.map +1 -0
- package/dist/esm/types/index.d.ts +13 -11
- package/dist/esm/types/index.d.ts.map +1 -1
- package/dist/esm/types/index.js +3 -1
- package/dist/esm/types/index.js.map +1 -1
- package/dist/esm/types/metadata.d.ts +12 -8
- package/dist/esm/types/metadata.d.ts.map +1 -1
- package/package.json +1 -1
- package/skills/oakscript/reference/pine-differences.md +2 -0
- package/skills/oakscript/reference/plotting.md +24 -1
- package/skills/oakscript/reference/timeframes-symbols.md +27 -0
- package/src/box/index.ts +4 -4
- package/src/check/harness.ts +27 -0
- package/src/drawing/output.ts +12 -8
- package/src/index.ts +1 -1
- package/src/label/index.ts +3 -3
- package/src/line/index.ts +6 -6
- package/src/polyline/index.ts +2 -2
- package/src/script/constants.ts +6 -1
- package/src/script/globals.ts +3 -0
- package/src/script/index.ts +580 -50
- package/src/security/events.ts +85 -0
- package/src/types/index.ts +13 -11
- package/src/types/metadata.ts +12 -8
package/dist/cjs/box/index.d.ts
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
* @version 6
|
|
13
13
|
*/
|
|
14
14
|
import type { ChartPoint, Box, color } from '../types/index.js';
|
|
15
|
-
type BoxXloc = 'bar_index' | 'bar_time';
|
|
15
|
+
type BoxXloc = 'bar_index' | 'bar_time' | 'pane';
|
|
16
16
|
type BoxExtend = 'none' | 'left' | 'right' | 'both';
|
|
17
17
|
/**
|
|
18
18
|
* Creates a new box (PineScript `box.new`), with two chart points or with coordinates, in PineScript's
|
|
@@ -223,7 +223,7 @@ export declare function set_rightbottom(id: Box, right: number, bottom: number):
|
|
|
223
223
|
* @param id - Box object to modify
|
|
224
224
|
* @param left - New left border coordinate
|
|
225
225
|
* @param right - New right border coordinate
|
|
226
|
-
* @param xloc - New coordinate system ('bar_index' or '
|
|
226
|
+
* @param xloc - New coordinate system ('bar_index', 'bar_time' or 'pane')
|
|
227
227
|
* @returns Modified box object
|
|
228
228
|
*
|
|
229
229
|
* @remarks
|
|
@@ -236,7 +236,7 @@ export declare function set_rightbottom(id: Box, right: number, bottom: number):
|
|
|
236
236
|
* box.set_xloc(box, 1609459200000, 1609545600000, 'bar_time');
|
|
237
237
|
* ```
|
|
238
238
|
*/
|
|
239
|
-
export declare function set_xloc(id: Box, left: number, right: number, xloc: 'bar_index' | 'bar_time'): Box;
|
|
239
|
+
export declare function set_xloc(id: Box, left: number, right: number, xloc: 'bar_index' | 'bar_time' | 'pane'): Box;
|
|
240
240
|
/**
|
|
241
241
|
* Sets the horizontal extension mode.
|
|
242
242
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/box/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAEhE,KAAK,OAAO,GAAG,WAAW,GAAG,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/box/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,UAAU,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAEhE,KAAK,OAAO,GAAG,WAAW,GAAG,UAAU,GAAG,MAAM,CAAC;AACjD,KAAK,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,CAAC;AAEpD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,OAAO,CACrB,QAAQ,EAAE,UAAU,EACpB,YAAY,EAAE,UAAU,EACxB,YAAY,CAAC,EAAE,KAAK,EACpB,YAAY,CAAC,EAAE,MAAM,EACrB,YAAY,CAAC,EAAE,OAAO,GAAG,QAAQ,GAAG,QAAQ,EAC5C,MAAM,CAAC,EAAE,SAAS,EAClB,IAAI,CAAC,EAAE,OAAO,EACd,OAAO,CAAC,EAAE,KAAK,EACf,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F;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,aAAa,CAAC,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,GAAG,CAIjE;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,EAAE,EAAE,GAAG,EAAE,IAAI,EAAE,SAAS,GAAG,WAAW,GAAG,GAAG,CAIhF;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,UAAU,CAAC,EAAE,EAAE,GAAG,GAAG,IAAI,CAExC;AAQD;;GAEG;AACH,wBAAgB,GAAG,IAAI,GAAG,EAAE,CAE3B;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,UAAU,GAAG,GAAG,CAKlE;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,UAAU,GAAG,GAAG,CAKtE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,EAAE,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,GAAG,GAAG,CAIpE;AAGD,OAAO,EAAE,OAAO,IAAI,GAAG,EAAE,CAAC;AAC1B,OAAO,EAAE,UAAU,IAAI,MAAM,EAAE,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/box/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Box namespace\n * Functions for creating and manipulating box drawing objects.\n *\n * @remarks\n * Box objects represent rectangular areas on the chart. The getter functions\n * (get_top, get_bottom, get_left, get_right) enable computational use cases like:\n * - Gap detection and tracking (detecting when price fills gaps)\n * - Range breakout analysis (detecting when price breaks out of consolidation)\n * - Rectangle pattern recognition\n *\n * @version 6\n */\n\nimport { all as allDrawings, checkBarIndex, isDeleted, register, remove } from '../drawing/registry.js';\nimport type { ChartPoint, Box, color } from '../types/index.js';\n\ntype BoxXloc = 'bar_index' | 'bar_time';\ntype BoxExtend = 'none' | 'left' | 'right' | 'both';\n\n/**\n * Creates a new box (PineScript `box.new`), with two chart points or with coordinates, in PineScript's\n * parameter order:\n *\n * - `box.new(top_left, bottom_right, border_color?, border_width?, border_style?, extend?, xloc?, bgcolor?,\n * text?, text_size?, text_color?, text_halign?, text_valign?, text_wrap?, text_font_family?,\n * force_overlay?, text_formatting?)`\n * - `box.new(left, top, right, bottom, border_color?, border_width?, border_style?, extend?, xloc?, ...)`\n *\n * With chart points, x is `point.index` for `bar_index` boxes and `point.time` for `bar_time` boxes.\n *\n * @example\n * ```typescript\n * // Gap box from bar 10 to 20, between 100 and 105, extended to the right\n * const gap = box.new(10, 105, 20, 100, '#2196F3', 1, 'solid', 'right');\n * ```\n */\nexport function new_box(\n top_left: ChartPoint,\n bottom_right: ChartPoint,\n border_color?: color,\n border_width?: number,\n border_style?: 'solid' | 'dotted' | 'dashed',\n extend?: BoxExtend,\n xloc?: BoxXloc,\n bgcolor?: color,\n text?: string,\n text_size?: string | number,\n text_color?: color,\n text_halign?: 'left' | 'center' | 'right',\n text_valign?: 'top' | 'center' | 'bottom',\n text_wrap?: 'none' | 'auto',\n text_font_family?: 'default' | 'monospace',\n force_overlay?: boolean,\n text_formatting?: number\n): Box;\nexport function new_box(\n left: number,\n top: number,\n right: number,\n bottom: number,\n border_color?: color,\n border_width?: number,\n border_style?: 'solid' | 'dotted' | 'dashed',\n extend?: BoxExtend,\n xloc?: BoxXloc,\n bgcolor?: color,\n text?: string,\n text_size?: string | number,\n text_color?: color,\n text_halign?: 'left' | 'center' | 'right',\n text_valign?: 'top' | 'center' | 'bottom',\n text_wrap?: 'none' | 'auto',\n text_font_family?: 'default' | 'monospace',\n force_overlay?: boolean,\n text_formatting?: number\n): Box;\nexport function new_box(...args: unknown[]): Box {\n let left: number, top: number, right: number, bottom: number, rest: unknown[];\n if (typeof args[0] === 'object' && args[0] !== null) {\n const [tl, br, ...others] = args as [ChartPoint, ChartPoint, ...unknown[]];\n const xloc = (others[4] as BoxXloc | undefined) ?? 'bar_index';\n [left, top, right, bottom, rest] = [pointX(tl, xloc), tl.price, pointX(br, xloc), br.price, others];\n } else {\n [left, top, right, bottom] = args as [number, number, number, number];\n rest = args.slice(4);\n }\n const [border_color, border_width, border_style, extend, xloc, bgcolor, text, text_size, text_color,\n text_halign, text_valign, text_wrap, text_font_family, force_overlay, text_formatting] = rest as [\n color?, number?, ('solid' | 'dotted' | 'dashed')?, BoxExtend?, BoxXloc?, color?, string?,\n (string | number)?, color?, ('left' | 'center' | 'right')?, ('top' | 'center' | 'bottom')?,\n ('none' | 'auto')?, ('default' | 'monospace')?, boolean?, number?,\n ];\n left = checkBarIndex('box.new', 'left', left, xloc);\n right = checkBarIndex('box.new', 'right', right, xloc);\n return register('box', {\n left,\n top,\n right,\n bottom,\n xloc: xloc ?? 'bar_index',\n extend: extend ?? 'none',\n border_color,\n border_width: border_width ?? 1,\n border_style: border_style || 'solid',\n bgcolor,\n text,\n text_size,\n text_color,\n text_halign,\n text_valign,\n text_wrap,\n text_font_family,\n force_overlay: force_overlay ?? false,\n text_formatting,\n });\n}\n\n/**\n * Returns the left border x coordinate.\n *\n * @param id - Box object\n * @returns Left border coordinate (bar index or timestamp)\n *\n * @remarks\n * **COMPUTATIONAL USE**: Calculate gap duration, validate range timeframes\n *\n * @example\n * ```typescript\n * const gap = box.new(10, 105, 20, 100);\n * const currentBar = 30;\n * const duration = currentBar - box.get_left(gap); // Returns 20\n *\n * if (duration > 50) {\n * console.log('Gap has been open for 50+ bars');\n * }\n * ```\n */\nexport function get_left(id: Box): number {\n return id.left;\n}\n\n/**\n * Returns the right border x coordinate.\n *\n * @param id - Box object\n * @returns Right border coordinate (bar index or timestamp)\n *\n * @remarks\n * **COMPUTATIONAL USE**: Calculate gap duration, update trailing edges\n *\n * @example\n * ```typescript\n * const range = box.new(100, 155, 150, 145);\n * const width = box.get_right(range) - box.get_left(range); // Returns 50 bars\n * ```\n */\nexport function get_right(id: Box): number {\n return id.right;\n}\n\n/**\n * Returns the top border price level.\n *\n * @param id - Box object\n * @returns Top border price\n *\n * @remarks\n * **COMPUTATIONAL USE**: Detect breakouts above resistance, check gap fills\n *\n * @example\n * ```typescript\n * const gap = box.new(10, 105, 20, 100); // Bearish gap\n *\n * // Check if price has filled gap from below\n * const high = 106;\n * if (high > box.get_top(gap)) {\n * console.log('Gap completely filled!');\n * }\n * ```\n */\nexport function get_top(id: Box): number {\n return id.top;\n}\n\n/**\n * Returns the bottom border price level.\n *\n * @param id - Box object\n * @returns Bottom border price\n *\n * @remarks\n * **COMPUTATIONAL USE**: Detect breakouts below support, check gap fills\n *\n * @example\n * ```typescript\n * const gap = box.new(10, 105, 20, 100); // Bearish gap\n *\n * // Check if price has touched gap from above\n * const low = 104;\n * if (low < box.get_top(gap) && low > box.get_bottom(gap)) {\n * console.log('Price entered the gap!');\n * }\n * ```\n */\nexport function get_bottom(id: Box): number {\n return id.bottom;\n}\n\n/**\n * Creates a copy of the box object.\n *\n * @param id - Box object to copy\n * @returns New box object with same properties\n *\n * @remarks\n * Creates a shallow copy of the box. Modifications to the copy won't affect the original.\n *\n * @example\n * ```typescript\n * const originalBox = box.new(10, 105, 20, 100);\n * const copiedBox = box.copy(originalBox);\n *\n * // Modify copy without affecting original\n * copiedBox.top = 110;\n * ```\n */\nexport function copy(id: Box): Box {\n return register('box', { ...id });\n}\n\n// =============================================================================\n// COORDINATE SETTERS\n// =============================================================================\n\n/**\n * Sets the left border x coordinate.\n *\n * @param id - Box object to modify\n * @param left - New left border coordinate\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_left(box, 15); // Move left edge to bar 15\n * ```\n */\nexport function set_left(id: Box, left: number): Box {\n if (isDeleted(id)) return id;\n left = checkBarIndex('box.set_(left*/xloc)', 'left', left, id.xloc);\n id.left = left;\n return id;\n}\n\n/**\n * Sets the right border x coordinate.\n *\n * @param id - Box object to modify\n * @param right - New right border coordinate\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_right(box, 25); // Move right edge to bar 25\n * ```\n */\nexport function set_right(id: Box, right: number): Box {\n if (isDeleted(id)) return id;\n right = checkBarIndex('box.set_(right*/xlock)', 'right', right, id.xloc);\n id.right = right;\n return id;\n}\n\n/**\n * Sets the top border price level.\n *\n * @param id - Box object to modify\n * @param top - New top border price\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_top(box, 110); // Move top edge to price 110\n * ```\n */\nexport function set_top(id: Box, top: number): Box {\n if (isDeleted(id)) return id;\n id.top = top;\n return id;\n}\n\n/**\n * Sets the bottom border price level.\n *\n * @param id - Box object to modify\n * @param bottom - New bottom border price\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_bottom(box, 95); // Move bottom edge to price 95\n * ```\n */\nexport function set_bottom(id: Box, bottom: number): Box {\n if (isDeleted(id)) return id;\n id.bottom = bottom;\n return id;\n}\n\n/**\n * Sets the left and top coordinates.\n *\n * @param id - Box object to modify\n * @param left - New left border coordinate\n * @param top - New top border price\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_lefttop(box, 12, 108); // Move top-left corner\n * ```\n */\nexport function set_lefttop(id: Box, left: number, top: number): Box {\n if (isDeleted(id)) return id;\n left = checkBarIndex('box.set_(left*/xloc)', 'left', left, id.xloc);\n id.left = left;\n id.top = top;\n return id;\n}\n\n/**\n * Sets the right and bottom coordinates.\n *\n * @param id - Box object to modify\n * @param right - New right border coordinate\n * @param bottom - New bottom border price\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_rightbottom(box, 25, 98); // Move bottom-right corner\n * ```\n */\nexport function set_rightbottom(id: Box, right: number, bottom: number): Box {\n if (isDeleted(id)) return id;\n right = checkBarIndex('box.set_(right*/xlock)', 'right', right, id.xloc);\n id.right = right;\n id.bottom = bottom;\n return id;\n}\n\n/**\n * Sets the coordinate system for the box.\n *\n * @param id - Box object to modify\n * @param left - New left border coordinate\n * @param right - New right border coordinate\n * @param xloc - New coordinate system ('bar_index' or 'bar_time')\n * @returns Modified box object\n *\n * @remarks\n * When changing xloc, you must provide appropriate x coordinates for the new system.\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * // Change to timestamp-based coordinates\n * box.set_xloc(box, 1609459200000, 1609545600000, 'bar_time');\n * ```\n */\nexport function set_xloc(id: Box, left: number, right: number, xloc: 'bar_index' | 'bar_time'): Box {\n if (isDeleted(id)) return id;\n id.left = left;\n id.right = right;\n id.xloc = xloc;\n return id;\n}\n\n/**\n * Sets the horizontal extension mode.\n *\n * @param id - Box object to modify\n * @param extend - New extension mode\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_extend(box, 'right'); // Extend box to the right\n * ```\n */\nexport function set_extend(id: Box, extend: 'none' | 'left' | 'right' | 'both'): Box {\n if (isDeleted(id)) return id;\n id.extend = extend;\n return id;\n}\n\n// =============================================================================\n// STYLING SETTERS\n// =============================================================================\n\n/**\n * Sets the border color.\n *\n * @param id - Box object to modify\n * @param borderColor - New border color\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_border_color(box, '#FF0000'); // Red border\n * ```\n */\nexport function set_border_color(id: Box, borderColor: color): Box {\n if (isDeleted(id)) return id;\n id.border_color = borderColor;\n return id;\n}\n\n/**\n * Sets the border width.\n *\n * @param id - Box object to modify\n * @param width - New border width in pixels\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_border_width(box, 2); // Thicker border\n * ```\n */\nexport function set_border_width(id: Box, width: number): Box {\n if (isDeleted(id)) return id;\n id.border_width = width;\n return id;\n}\n\n/**\n * Sets the border style.\n *\n * @param id - Box object to modify\n * @param style - New border style\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_border_style(box, 'dashed'); // Dashed border\n * ```\n */\nexport function set_border_style(id: Box, style: 'solid' | 'dotted' | 'dashed'): Box {\n if (isDeleted(id)) return id;\n id.border_style = style;\n return id;\n}\n\n/**\n * Sets the background fill color.\n *\n * @param id - Box object to modify\n * @param bgColor - New background color\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_bgcolor(box, '#00FF0030'); // Transparent green fill\n * ```\n */\nexport function set_bgcolor(id: Box, bgColor: color): Box {\n if (isDeleted(id)) return id;\n id.bgcolor = bgColor;\n return id;\n}\n\n// =============================================================================\n// TEXT SETTERS\n// =============================================================================\n\n/**\n * Sets the text content.\n *\n * @param id - Box object to modify\n * @param text - New text content\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text(box, 'Gap Filled'); // Update text\n * ```\n */\nexport function set_text(id: Box, text: string): Box {\n if (isDeleted(id)) return id;\n id.text = text;\n return id;\n}\n\n/**\n * Sets the text color.\n *\n * @param id - Box object to modify\n * @param textColor - New text color\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_color(box, '#FFFFFF'); // White text\n * ```\n */\nexport function set_text_color(id: Box, textColor: color): Box {\n if (isDeleted(id)) return id;\n id.text_color = textColor;\n return id;\n}\n\n/**\n * Sets the text size.\n *\n * @param id - Box object to modify\n * @param size - New text size\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_size(box, 'large'); // Larger text\n * ```\n */\nexport function set_text_size(id: Box, size: string | number): Box {\n if (isDeleted(id)) return id;\n id.text_size = size;\n return id;\n}\n\n/**\n * Sets the horizontal text alignment.\n *\n * @param id - Box object to modify\n * @param align - New horizontal alignment\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_halign(box, 'center'); // Center text horizontally\n * ```\n */\nexport function set_text_halign(id: Box, align: 'left' | 'center' | 'right'): Box {\n if (isDeleted(id)) return id;\n id.text_halign = align;\n return id;\n}\n\n/**\n * Sets the vertical text alignment.\n *\n * @param id - Box object to modify\n * @param align - New vertical alignment\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_valign(box, 'center'); // Center text vertically\n * ```\n */\nexport function set_text_valign(id: Box, align: 'top' | 'center' | 'bottom'): Box {\n if (isDeleted(id)) return id;\n id.text_valign = align;\n return id;\n}\n\n/**\n * Sets the text wrapping mode.\n *\n * @param id - Box object to modify\n * @param wrap - New text wrap mode\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_wrap(box, 'auto'); // Enable text wrapping\n * ```\n */\nexport function set_text_wrap(id: Box, wrap: 'none' | 'auto'): Box {\n if (isDeleted(id)) return id;\n id.text_wrap = wrap;\n return id;\n}\n\n/**\n * Sets the text font family.\n *\n * @param id - Box object to modify\n * @param font - New font family\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_font_family(box, 'monospace'); // Monospace font\n * ```\n */\nexport function set_text_font_family(id: Box, font: 'default' | 'monospace'): Box {\n if (isDeleted(id)) return id;\n id.text_font_family = font;\n return id;\n}\n\n/**\n * Deletes the box object.\n *\n * @param id - Box object to delete\n *\n * @remarks\n * Removes the box from `box.all()`. As in PineScript, the deleted box is `na`: its getters\n * return NaN and its setters do nothing. Deleting it twice has no effect.\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.delete(box);\n * // box.all() no longer contains it\n * ```\n */\nexport function delete_box(id: Box): void {\n remove('box', id);\n}\n\n/** x coordinate of a chart point for an object's xloc (`na` when the point has no such coordinate). */\nfunction pointX(point: ChartPoint, xloc: 'bar_index' | 'bar_time'): number {\n const x = xloc === 'bar_time' ? point.time : point.index;\n return x ?? NaN;\n}\n\n/**\n * All live boxes, in creation order (PineScript `box.all`). A new array.\n */\nexport function all(): Box[] {\n return allDrawings('box');\n}\n\n/**\n * Sets the left and top borders from a chart point (`point.index` or `point.time` by xloc, and `point.price`).\n */\nexport function set_top_left_point(id: Box, point: ChartPoint): Box {\n if (isDeleted(id)) return id;\n id.left = pointX(point, id.xloc);\n id.top = point.price;\n return id;\n}\n\n/**\n * Sets the right and bottom borders from a chart point (`point.index` or `point.time` by xloc, and `point.price`).\n */\nexport function set_bottom_right_point(id: Box, point: ChartPoint): Box {\n if (isDeleted(id)) return id;\n id.right = pointX(point, id.xloc);\n id.bottom = point.price;\n return id;\n}\n\n/**\n * Sets the text formatting: `text.format_none`, `text.format_bold`, `text.format_italic`,\n * or `text.format_bold + text.format_italic`.\n */\nexport function set_text_formatting(id: Box, formatting: number): Box {\n if (isDeleted(id)) return id;\n id.text_formatting = formatting;\n return id;\n}\n\n// Alias to match PineScript API\nexport { new_box as new };\nexport { delete_box as delete };\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,sBAA+E;AA+DxE,SAAS,WAAW,MAAsB;AAC/C,MAAI,MAAc,KAAa,OAAe,QAAgB;AAC9D,MAAI,OAAO,KAAK,CAAC,MAAM,YAAY,KAAK,CAAC,MAAM,MAAM;AACnD,UAAM,CAAC,IAAI,IAAI,GAAG,MAAM,IAAI;AAC5B,UAAMA,QAAQ,OAAO,CAAC,KAA6B;AACnD,KAAC,MAAM,KAAK,OAAO,QAAQ,IAAI,IAAI,CAAC,OAAO,IAAI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AACV,SAAO;AACT;AAeO,SAAS,UAAU,IAAS,OAAoB;AACrD,UAAI,2BAAU,EAAE,EAAG,QAAO;AAC1B,cAAQ,+BAAc,0BAA0B,SAAS,OAAO,GAAG,IAAI;AACvE,KAAG,QAAQ;AACX,SAAO;AACT;AAeO,SAAS,QAAQ,IAAS,KAAkB;AACjD,UAAI,2BAAU,EAAE,EAAG,QAAO;AAC1B,KAAG,MAAM;AACT,SAAO;AACT;AAeO,SAAS,WAAW,IAAS,QAAqB;AACvD,UAAI,2BAAU,EAAE,EAAG,QAAO;AAC1B,KAAG,SAAS;AACZ,SAAO;AACT;AAgBO,SAAS,YAAY,IAAS,MAAc,KAAkB;AACnE,UAAI,2BAAU,EAAE,EAAG,QAAO;AAC1B,aAAO,+BAAc,wBAAwB,QAAQ,MAAM,GAAG,IAAI;AAClE,KAAG,OAAO;AACV,KAAG,MAAM;AACT,SAAO;AACT;AAgBO,SAAS,gBAAgB,IAAS,OAAe,QAAqB;AAC3E,UAAI,2BAAU,EAAE,EAAG,QAAO;AAC1B,cAAQ,+BAAc,0BAA0B,SAAS,OAAO,GAAG,IAAI;AACvE,KAAG,QAAQ;AACX,KAAG,SAAS;AACZ,SAAO;AACT;AAqBO,SAAS,SAAS,IAAS,MAAc,OAAe,
|
|
4
|
+
"sourcesContent": ["/**\n * Box namespace\n * Functions for creating and manipulating box drawing objects.\n *\n * @remarks\n * Box objects represent rectangular areas on the chart. The getter functions\n * (get_top, get_bottom, get_left, get_right) enable computational use cases like:\n * - Gap detection and tracking (detecting when price fills gaps)\n * - Range breakout analysis (detecting when price breaks out of consolidation)\n * - Rectangle pattern recognition\n *\n * @version 6\n */\n\nimport { all as allDrawings, checkBarIndex, isDeleted, register, remove } from '../drawing/registry.js';\nimport type { ChartPoint, Box, color } from '../types/index.js';\n\ntype BoxXloc = 'bar_index' | 'bar_time' | 'pane';\ntype BoxExtend = 'none' | 'left' | 'right' | 'both';\n\n/**\n * Creates a new box (PineScript `box.new`), with two chart points or with coordinates, in PineScript's\n * parameter order:\n *\n * - `box.new(top_left, bottom_right, border_color?, border_width?, border_style?, extend?, xloc?, bgcolor?,\n * text?, text_size?, text_color?, text_halign?, text_valign?, text_wrap?, text_font_family?,\n * force_overlay?, text_formatting?)`\n * - `box.new(left, top, right, bottom, border_color?, border_width?, border_style?, extend?, xloc?, ...)`\n *\n * With chart points, x is `point.index` for `bar_index` boxes and `point.time` for `bar_time` boxes.\n *\n * @example\n * ```typescript\n * // Gap box from bar 10 to 20, between 100 and 105, extended to the right\n * const gap = box.new(10, 105, 20, 100, '#2196F3', 1, 'solid', 'right');\n * ```\n */\nexport function new_box(\n top_left: ChartPoint,\n bottom_right: ChartPoint,\n border_color?: color,\n border_width?: number,\n border_style?: 'solid' | 'dotted' | 'dashed',\n extend?: BoxExtend,\n xloc?: BoxXloc,\n bgcolor?: color,\n text?: string,\n text_size?: string | number,\n text_color?: color,\n text_halign?: 'left' | 'center' | 'right',\n text_valign?: 'top' | 'center' | 'bottom',\n text_wrap?: 'none' | 'auto',\n text_font_family?: 'default' | 'monospace',\n force_overlay?: boolean,\n text_formatting?: number\n): Box;\nexport function new_box(\n left: number,\n top: number,\n right: number,\n bottom: number,\n border_color?: color,\n border_width?: number,\n border_style?: 'solid' | 'dotted' | 'dashed',\n extend?: BoxExtend,\n xloc?: BoxXloc,\n bgcolor?: color,\n text?: string,\n text_size?: string | number,\n text_color?: color,\n text_halign?: 'left' | 'center' | 'right',\n text_valign?: 'top' | 'center' | 'bottom',\n text_wrap?: 'none' | 'auto',\n text_font_family?: 'default' | 'monospace',\n force_overlay?: boolean,\n text_formatting?: number\n): Box;\nexport function new_box(...args: unknown[]): Box {\n let left: number, top: number, right: number, bottom: number, rest: unknown[];\n if (typeof args[0] === 'object' && args[0] !== null) {\n const [tl, br, ...others] = args as [ChartPoint, ChartPoint, ...unknown[]];\n const xloc = (others[4] as BoxXloc | undefined) ?? 'bar_index';\n [left, top, right, bottom, rest] = [pointX(tl, xloc), tl.price, pointX(br, xloc), br.price, others];\n } else {\n [left, top, right, bottom] = args as [number, number, number, number];\n rest = args.slice(4);\n }\n const [border_color, border_width, border_style, extend, xloc, bgcolor, text, text_size, text_color,\n text_halign, text_valign, text_wrap, text_font_family, force_overlay, text_formatting] = rest as [\n color?, number?, ('solid' | 'dotted' | 'dashed')?, BoxExtend?, BoxXloc?, color?, string?,\n (string | number)?, color?, ('left' | 'center' | 'right')?, ('top' | 'center' | 'bottom')?,\n ('none' | 'auto')?, ('default' | 'monospace')?, boolean?, number?,\n ];\n left = checkBarIndex('box.new', 'left', left, xloc);\n right = checkBarIndex('box.new', 'right', right, xloc);\n return register('box', {\n left,\n top,\n right,\n bottom,\n xloc: xloc ?? 'bar_index',\n extend: extend ?? 'none',\n border_color,\n border_width: border_width ?? 1,\n border_style: border_style || 'solid',\n bgcolor,\n text,\n text_size,\n text_color,\n text_halign,\n text_valign,\n text_wrap,\n text_font_family,\n force_overlay: force_overlay ?? false,\n text_formatting,\n });\n}\n\n/**\n * Returns the left border x coordinate.\n *\n * @param id - Box object\n * @returns Left border coordinate (bar index or timestamp)\n *\n * @remarks\n * **COMPUTATIONAL USE**: Calculate gap duration, validate range timeframes\n *\n * @example\n * ```typescript\n * const gap = box.new(10, 105, 20, 100);\n * const currentBar = 30;\n * const duration = currentBar - box.get_left(gap); // Returns 20\n *\n * if (duration > 50) {\n * console.log('Gap has been open for 50+ bars');\n * }\n * ```\n */\nexport function get_left(id: Box): number {\n return id.left;\n}\n\n/**\n * Returns the right border x coordinate.\n *\n * @param id - Box object\n * @returns Right border coordinate (bar index or timestamp)\n *\n * @remarks\n * **COMPUTATIONAL USE**: Calculate gap duration, update trailing edges\n *\n * @example\n * ```typescript\n * const range = box.new(100, 155, 150, 145);\n * const width = box.get_right(range) - box.get_left(range); // Returns 50 bars\n * ```\n */\nexport function get_right(id: Box): number {\n return id.right;\n}\n\n/**\n * Returns the top border price level.\n *\n * @param id - Box object\n * @returns Top border price\n *\n * @remarks\n * **COMPUTATIONAL USE**: Detect breakouts above resistance, check gap fills\n *\n * @example\n * ```typescript\n * const gap = box.new(10, 105, 20, 100); // Bearish gap\n *\n * // Check if price has filled gap from below\n * const high = 106;\n * if (high > box.get_top(gap)) {\n * console.log('Gap completely filled!');\n * }\n * ```\n */\nexport function get_top(id: Box): number {\n return id.top;\n}\n\n/**\n * Returns the bottom border price level.\n *\n * @param id - Box object\n * @returns Bottom border price\n *\n * @remarks\n * **COMPUTATIONAL USE**: Detect breakouts below support, check gap fills\n *\n * @example\n * ```typescript\n * const gap = box.new(10, 105, 20, 100); // Bearish gap\n *\n * // Check if price has touched gap from above\n * const low = 104;\n * if (low < box.get_top(gap) && low > box.get_bottom(gap)) {\n * console.log('Price entered the gap!');\n * }\n * ```\n */\nexport function get_bottom(id: Box): number {\n return id.bottom;\n}\n\n/**\n * Creates a copy of the box object.\n *\n * @param id - Box object to copy\n * @returns New box object with same properties\n *\n * @remarks\n * Creates a shallow copy of the box. Modifications to the copy won't affect the original.\n *\n * @example\n * ```typescript\n * const originalBox = box.new(10, 105, 20, 100);\n * const copiedBox = box.copy(originalBox);\n *\n * // Modify copy without affecting original\n * copiedBox.top = 110;\n * ```\n */\nexport function copy(id: Box): Box {\n return register('box', { ...id });\n}\n\n// =============================================================================\n// COORDINATE SETTERS\n// =============================================================================\n\n/**\n * Sets the left border x coordinate.\n *\n * @param id - Box object to modify\n * @param left - New left border coordinate\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_left(box, 15); // Move left edge to bar 15\n * ```\n */\nexport function set_left(id: Box, left: number): Box {\n if (isDeleted(id)) return id;\n left = checkBarIndex('box.set_(left*/xloc)', 'left', left, id.xloc);\n id.left = left;\n return id;\n}\n\n/**\n * Sets the right border x coordinate.\n *\n * @param id - Box object to modify\n * @param right - New right border coordinate\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_right(box, 25); // Move right edge to bar 25\n * ```\n */\nexport function set_right(id: Box, right: number): Box {\n if (isDeleted(id)) return id;\n right = checkBarIndex('box.set_(right*/xlock)', 'right', right, id.xloc);\n id.right = right;\n return id;\n}\n\n/**\n * Sets the top border price level.\n *\n * @param id - Box object to modify\n * @param top - New top border price\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_top(box, 110); // Move top edge to price 110\n * ```\n */\nexport function set_top(id: Box, top: number): Box {\n if (isDeleted(id)) return id;\n id.top = top;\n return id;\n}\n\n/**\n * Sets the bottom border price level.\n *\n * @param id - Box object to modify\n * @param bottom - New bottom border price\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_bottom(box, 95); // Move bottom edge to price 95\n * ```\n */\nexport function set_bottom(id: Box, bottom: number): Box {\n if (isDeleted(id)) return id;\n id.bottom = bottom;\n return id;\n}\n\n/**\n * Sets the left and top coordinates.\n *\n * @param id - Box object to modify\n * @param left - New left border coordinate\n * @param top - New top border price\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_lefttop(box, 12, 108); // Move top-left corner\n * ```\n */\nexport function set_lefttop(id: Box, left: number, top: number): Box {\n if (isDeleted(id)) return id;\n left = checkBarIndex('box.set_(left*/xloc)', 'left', left, id.xloc);\n id.left = left;\n id.top = top;\n return id;\n}\n\n/**\n * Sets the right and bottom coordinates.\n *\n * @param id - Box object to modify\n * @param right - New right border coordinate\n * @param bottom - New bottom border price\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_rightbottom(box, 25, 98); // Move bottom-right corner\n * ```\n */\nexport function set_rightbottom(id: Box, right: number, bottom: number): Box {\n if (isDeleted(id)) return id;\n right = checkBarIndex('box.set_(right*/xlock)', 'right', right, id.xloc);\n id.right = right;\n id.bottom = bottom;\n return id;\n}\n\n/**\n * Sets the coordinate system for the box.\n *\n * @param id - Box object to modify\n * @param left - New left border coordinate\n * @param right - New right border coordinate\n * @param xloc - New coordinate system ('bar_index', 'bar_time' or 'pane')\n * @returns Modified box object\n *\n * @remarks\n * When changing xloc, you must provide appropriate x coordinates for the new system.\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * // Change to timestamp-based coordinates\n * box.set_xloc(box, 1609459200000, 1609545600000, 'bar_time');\n * ```\n */\nexport function set_xloc(id: Box, left: number, right: number, xloc: 'bar_index' | 'bar_time' | 'pane'): Box {\n if (isDeleted(id)) return id;\n id.left = left;\n id.right = right;\n id.xloc = xloc;\n return id;\n}\n\n/**\n * Sets the horizontal extension mode.\n *\n * @param id - Box object to modify\n * @param extend - New extension mode\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_extend(box, 'right'); // Extend box to the right\n * ```\n */\nexport function set_extend(id: Box, extend: 'none' | 'left' | 'right' | 'both'): Box {\n if (isDeleted(id)) return id;\n id.extend = extend;\n return id;\n}\n\n// =============================================================================\n// STYLING SETTERS\n// =============================================================================\n\n/**\n * Sets the border color.\n *\n * @param id - Box object to modify\n * @param borderColor - New border color\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_border_color(box, '#FF0000'); // Red border\n * ```\n */\nexport function set_border_color(id: Box, borderColor: color): Box {\n if (isDeleted(id)) return id;\n id.border_color = borderColor;\n return id;\n}\n\n/**\n * Sets the border width.\n *\n * @param id - Box object to modify\n * @param width - New border width in pixels\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_border_width(box, 2); // Thicker border\n * ```\n */\nexport function set_border_width(id: Box, width: number): Box {\n if (isDeleted(id)) return id;\n id.border_width = width;\n return id;\n}\n\n/**\n * Sets the border style.\n *\n * @param id - Box object to modify\n * @param style - New border style\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_border_style(box, 'dashed'); // Dashed border\n * ```\n */\nexport function set_border_style(id: Box, style: 'solid' | 'dotted' | 'dashed'): Box {\n if (isDeleted(id)) return id;\n id.border_style = style;\n return id;\n}\n\n/**\n * Sets the background fill color.\n *\n * @param id - Box object to modify\n * @param bgColor - New background color\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_bgcolor(box, '#00FF0030'); // Transparent green fill\n * ```\n */\nexport function set_bgcolor(id: Box, bgColor: color): Box {\n if (isDeleted(id)) return id;\n id.bgcolor = bgColor;\n return id;\n}\n\n// =============================================================================\n// TEXT SETTERS\n// =============================================================================\n\n/**\n * Sets the text content.\n *\n * @param id - Box object to modify\n * @param text - New text content\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text(box, 'Gap Filled'); // Update text\n * ```\n */\nexport function set_text(id: Box, text: string): Box {\n if (isDeleted(id)) return id;\n id.text = text;\n return id;\n}\n\n/**\n * Sets the text color.\n *\n * @param id - Box object to modify\n * @param textColor - New text color\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_color(box, '#FFFFFF'); // White text\n * ```\n */\nexport function set_text_color(id: Box, textColor: color): Box {\n if (isDeleted(id)) return id;\n id.text_color = textColor;\n return id;\n}\n\n/**\n * Sets the text size.\n *\n * @param id - Box object to modify\n * @param size - New text size\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_size(box, 'large'); // Larger text\n * ```\n */\nexport function set_text_size(id: Box, size: string | number): Box {\n if (isDeleted(id)) return id;\n id.text_size = size;\n return id;\n}\n\n/**\n * Sets the horizontal text alignment.\n *\n * @param id - Box object to modify\n * @param align - New horizontal alignment\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_halign(box, 'center'); // Center text horizontally\n * ```\n */\nexport function set_text_halign(id: Box, align: 'left' | 'center' | 'right'): Box {\n if (isDeleted(id)) return id;\n id.text_halign = align;\n return id;\n}\n\n/**\n * Sets the vertical text alignment.\n *\n * @param id - Box object to modify\n * @param align - New vertical alignment\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_valign(box, 'center'); // Center text vertically\n * ```\n */\nexport function set_text_valign(id: Box, align: 'top' | 'center' | 'bottom'): Box {\n if (isDeleted(id)) return id;\n id.text_valign = align;\n return id;\n}\n\n/**\n * Sets the text wrapping mode.\n *\n * @param id - Box object to modify\n * @param wrap - New text wrap mode\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_wrap(box, 'auto'); // Enable text wrapping\n * ```\n */\nexport function set_text_wrap(id: Box, wrap: 'none' | 'auto'): Box {\n if (isDeleted(id)) return id;\n id.text_wrap = wrap;\n return id;\n}\n\n/**\n * Sets the text font family.\n *\n * @param id - Box object to modify\n * @param font - New font family\n * @returns Modified box object\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.set_text_font_family(box, 'monospace'); // Monospace font\n * ```\n */\nexport function set_text_font_family(id: Box, font: 'default' | 'monospace'): Box {\n if (isDeleted(id)) return id;\n id.text_font_family = font;\n return id;\n}\n\n/**\n * Deletes the box object.\n *\n * @param id - Box object to delete\n *\n * @remarks\n * Removes the box from `box.all()`. As in PineScript, the deleted box is `na`: its getters\n * return NaN and its setters do nothing. Deleting it twice has no effect.\n *\n * @example\n * ```typescript\n * const box = box.new(10, 105, 20, 100);\n * box.delete(box);\n * // box.all() no longer contains it\n * ```\n */\nexport function delete_box(id: Box): void {\n remove('box', id);\n}\n\n/** x coordinate of a chart point for an object's xloc (`na` when the point has no such coordinate). */\nfunction pointX(point: ChartPoint, xloc: 'bar_index' | 'bar_time' | 'pane'): number {\n const x = xloc === 'bar_time' ? point.time : point.index;\n return x ?? NaN;\n}\n\n/**\n * All live boxes, in creation order (PineScript `box.all`). A new array.\n */\nexport function all(): Box[] {\n return allDrawings('box');\n}\n\n/**\n * Sets the left and top borders from a chart point (`point.index` or `point.time` by xloc, and `point.price`).\n */\nexport function set_top_left_point(id: Box, point: ChartPoint): Box {\n if (isDeleted(id)) return id;\n id.left = pointX(point, id.xloc);\n id.top = point.price;\n return id;\n}\n\n/**\n * Sets the right and bottom borders from a chart point (`point.index` or `point.time` by xloc, and `point.price`).\n */\nexport function set_bottom_right_point(id: Box, point: ChartPoint): Box {\n if (isDeleted(id)) return id;\n id.right = pointX(point, id.xloc);\n id.bottom = point.price;\n return id;\n}\n\n/**\n * Sets the text formatting: `text.format_none`, `text.format_bold`, `text.format_italic`,\n * or `text.format_bold + text.format_italic`.\n */\nexport function set_text_formatting(id: Box, formatting: number): Box {\n if (isDeleted(id)) return id;\n id.text_formatting = formatting;\n return id;\n}\n\n// Alias to match PineScript API\nexport { new_box as new };\nexport { delete_box as delete };\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAcA,sBAA+E;AA+DxE,SAAS,WAAW,MAAsB;AAC/C,MAAI,MAAc,KAAa,OAAe,QAAgB;AAC9D,MAAI,OAAO,KAAK,CAAC,MAAM,YAAY,KAAK,CAAC,MAAM,MAAM;AACnD,UAAM,CAAC,IAAI,IAAI,GAAG,MAAM,IAAI;AAC5B,UAAMA,QAAQ,OAAO,CAAC,KAA6B;AACnD,KAAC,MAAM,KAAK,OAAO,QAAQ,IAAI,IAAI,CAAC,OAAO,IAAIA,KAAI,GAAG,GAAG,OAAO,OAAO,IAAIA,KAAI,GAAG,GAAG,OAAO,MAAM;AAAA,EACpG,O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T;AAKO,SAAS,uBAAuB,IAAS,OAAwB;AACtE,UAAI,2BAAU,EAAE,EAAG,QAAO;AAC1B,KAAG,QAAQ,OAAO,OAAO,GAAG,IAAI;AAChC,KAAG,SAAS,MAAM;AAClB,SAAO;AACT;AAMO,SAAS,oBAAoB,IAAS,YAAyB;AACpE,UAAI,2BAAU,EAAE,EAAG,QAAO;AAC1B,KAAG,kBAAkB;AACrB,SAAO;AACT;",
|
|
6
6
|
"names": ["xloc", "allDrawings"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"harness.d.ts","sourceRoot":"","sources":["../../../src/check/harness.ts"],"names":[],"mappings":"AAUA,OAAO,EAGL,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,aAAa,
|
|
1
|
+
{"version":3,"file":"harness.d.ts","sourceRoot":"","sources":["../../../src/check/harness.ts"],"names":[],"mappings":"AAUA,OAAO,EAGL,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,oBAAoB,EACzB,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,KAAK,oBAAoB,EACzB,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,aAAa,EAElB,KAAK,gBAAgB,EACtB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AAE7C,iGAAiG;AACjG,eAAO,MAAM,cAAc,EAAE,SAAS,MAAM,EAE3C,CAAC;AAEF,mHAAmH;AACnH,eAAO,MAAM,iBAAiB,kBAAkB,CAAC;AAEjD,oHAAoH;AACpH,wBAAgB,eAAe,IAAI,OAAO,EAAE,CAE3C;AAED;;;;GAIG;AACH,wBAAgB,cA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,MAAM,GAAG,IAAI;IAKxB,UAAU,IAAI,IAAI;IAKlB,QAAQ,CAAC,KAAK,EAAE,gBAAgB,EAAE,CAAM;IAExC,IAAI,CAAC,IAAI,EAAE,gBAAgB,GAAG,IAAI;IAIlC,GAAG,CAAC,QAAQ,EAAE,gBAAgB,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS;IAmB5D,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,GAAG,SAAS;IAInD,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,GAAG,SAAS;CAGtD;AAED,MAAM,WAAW,SAAS;IACxB,GAAG,EAAE,eAAe,CAAC;IACrB,MAAM,CAAC,EAAE,UAAU,CAAC;CACrB;AAED,MAAM,WAAW,gBAAiB,SAAQ,gBAAgB;IACxD,6FAA6F;IAC7F,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,IAAI,CAAC;CAC1C;AAED,uGAAuG;AACvG,wBAAgB,SAAS,CACvB,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,GAAG,EAAE,EACX,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,EACpC,OAAO,GAAE,gBAAqB,GAC7B,SAAS,CAOX;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,GAAG,EAAE,EACX,MAAM,GAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAM,EACpC,OAAO,GAAE,gBAAqB,GAC7B,MAAM,GAAG,IAAI,CAQf"}
|
|
@@ -144,9 +144,43 @@ function testChart(bars, options = {}) {
|
|
|
144
144
|
time: first + (b.time - START)
|
|
145
145
|
}));
|
|
146
146
|
},
|
|
147
|
-
symbolInfo: () => ({ timezone, session, mintick: 0.01, currency: "USD" })
|
|
147
|
+
symbolInfo: () => ({ timezone, session, mintick: 0.01, currency: "USD" }),
|
|
148
|
+
// the other symbol fields: none (na), so that a script reading them runs
|
|
149
|
+
symbolType: "stock",
|
|
150
|
+
description: "Synthetic test symbol",
|
|
151
|
+
...NO_SYMBOL_FIELDS,
|
|
152
|
+
events: () => testEvents(bars)
|
|
148
153
|
};
|
|
149
154
|
}
|
|
155
|
+
const NO_SYMBOL_FIELDS = {
|
|
156
|
+
basecurrency: null,
|
|
157
|
+
country: null,
|
|
158
|
+
currentContract: null,
|
|
159
|
+
expirationDate: null,
|
|
160
|
+
sector: null,
|
|
161
|
+
industry: null,
|
|
162
|
+
isin: null,
|
|
163
|
+
volumetype: null,
|
|
164
|
+
employees: null,
|
|
165
|
+
shareholders: null,
|
|
166
|
+
sharesOutstandingTotal: null,
|
|
167
|
+
sharesOutstandingFloat: null,
|
|
168
|
+
recommendations: null,
|
|
169
|
+
targetPrice: null
|
|
170
|
+
};
|
|
171
|
+
function testEvents(bars) {
|
|
172
|
+
if (!bars.length) return {};
|
|
173
|
+
const first = bars[0].time * 1e3;
|
|
174
|
+
const last = bars[bars.length - 1].time * 1e3;
|
|
175
|
+
const QUARTER = 90 * 864e5;
|
|
176
|
+
const dividends = [];
|
|
177
|
+
const earnings = [];
|
|
178
|
+
for (let t = first, k = 1; t <= last; t += QUARTER, k++) {
|
|
179
|
+
dividends.push({ time: t, net: 0.2 + 0.01 * k });
|
|
180
|
+
earnings.push({ time: t + 30 * 864e5, actual: 1 + 0.1 * k, estimate: 1 + 0.09 * k, standardized: 1 + 0.1 * k });
|
|
181
|
+
}
|
|
182
|
+
return { dividends, earnings, splits: [{ time: Math.round((first + last) / 2), numerator: 2, denominator: 1 }] };
|
|
183
|
+
}
|
|
150
184
|
class TestEngine {
|
|
151
185
|
constructor(setup) {
|
|
152
186
|
this.setup = setup;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/check/harness.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @fileoverview Runs a script source the way a host app runs a script written in its editor: the source is the body\n * of the script, with every value export of `oakscriptjs/script` but `executeScript` as an implicit global, on\n * deterministic synthetic bars (or given bars), with a chart context and, for a strategy, a small order engine.\n * Used by {@link checkScript}, the `oakscript check` command and the tests of the agent guide.\n *\n * @module check/harness\n */\nimport * as lib from '../index.js';\nimport * as api from '../script/index.js';\nimport {\n createScriptRun,\n executeScript,\n type ChartContext,\n type ScriptRunResult,\n type StrategyCloseOptions,\n type StrategyDirection,\n type StrategyEngine,\n type StrategyEntryOptions,\n type StrategyExitOptions,\n type StrategyRiskRule,\n type StrategySetup,\n type StrategyTrade,\n type StrategyVariable,\n} from '../script/index.js';\nimport type { Bar } from '../types/index.js';\n\n/** The implicit globals of a script: every value export of the script API but the host entry. */\nexport const SCRIPT_GLOBALS: readonly string[] = Object.keys(api).filter(\n (k) => k !== 'default' && k !== 'executeScript' && /^[A-Za-z_$][\\w$]*$/.test(k)\n);\n\n/** Name of the parameter that receives the `oakscriptjs` module in a compiled script (its `import` statements). */\nexport const LIBRARY_PARAMETER = '__oakscriptjs';\n\n/** The values of {@link SCRIPT_GLOBALS}, then the `oakscriptjs` module, in the order of the compiled parameters. */\nexport function scriptArguments(): unknown[] {\n return [...SCRIPT_GLOBALS.map((k) => (api as Record<string, unknown>)[k]), lib];\n}\n\n/**\n * Rewrites the `import { a, b as c } from \"oakscriptjs\"` statements of a script into `const { a, b: c } = ...` on the\n * same lines (the line numbers of the source do not change). Throws on an import of another module: a script runs\n * self-contained.\n */\nexport function rewriteImports(source: string): string {\n return source.replace(/^([ \\t]*)import\\s*(\\{[^}]*\\}|\\*\\s+as\\s+[A-Za-z_$][\\w$]*)\\s*from\\s*(['\"])([^'\"]+)\\3\\s*;?/gm, (all, indent, what, _q, from) => {\n if (from !== 'oakscriptjs' && from !== 'oakscriptjs/script') {\n throw new SyntaxError(`A script can only import from \"oakscriptjs\" (found \"${from}\").`);\n }\n const lines = all.split('\\n').length - 1;\n const binding = what.startsWith('*')\n ? what.replace(/^\\*\\s+as\\s+/, '')\n : what.replace(/\\s+as\\s+/g, ': ').replace(/\\s+/g, ' ');\n return `${indent}const ${binding} = ${LIBRARY_PARAMETER};${'\\n'.repeat(lines)}`;\n });\n}\n\n/**\n * Start and end of the function the script source is wrapped in. The globals are the parameters of an outer function\n * and the source is the body of an inner one, so a script can declare a name of a global (`const size = 2`), as in an\n * app that imports the globals at the top of a module. The start goes on the first line of the source.\n */\nexport const SCRIPT_PREFIX = '\"use strict\"; return (function () { ';\nexport const SCRIPT_SUFFIX = '\\n})();';\n\n/** The source of the function body of a compiled script (imports rewritten, lines kept). */\nexport function wrapSource(source: string): string {\n return SCRIPT_PREFIX + rewriteImports(source) + SCRIPT_SUFFIX;\n}\n\n/** Compiles a script source into a body for executeScript(); throws a SyntaxError on invalid code. */\nexport function compileScript(source: string): () => void {\n const fn = new Function(...SCRIPT_GLOBALS, LIBRARY_PARAMETER, wrapSource(source)) as (...args: unknown[]) => void;\n const values = scriptArguments();\n return () => fn(...values);\n}\n\nconst HOUR = 3600;\n/** 2024-01-01 00:00 UTC, in seconds. */\nconst START = 1704067200;\n\n/** Deterministic synthetic bars: two waves, a slow trend and seeded noise. `step`: seconds between bars. */\nexport function syntheticBars(count: number, step = HOUR, seed = 1): Bar[] {\n let s = seed >>> 0 || 1;\n const rand = (): number => {\n s = (Math.imul(s, 1664525) + 1013904223) >>> 0;\n return s / 2 ** 32;\n };\n const scale = Math.sqrt(step / HOUR);\n const bars: Bar[] = [];\n let prev = 100;\n for (let i = 0; i < count; i++) {\n const t = (i * step) / HOUR;\n const close = 100 + 12 * Math.sin(t / 60) + 4 * Math.sin(t / 11) + t * 0.004 + (rand() - 0.5) * 1.5 * scale;\n const open = prev;\n const high = Math.max(open, close) + rand() * 0.8 * scale;\n const low = Math.min(open, close) - rand() * 0.8 * scale;\n bars.push({ time: START + i * step, open, high, low, close, volume: Math.round(1000 + rand() * 4000) });\n prev = close;\n }\n return bars;\n}\n\n/** Seconds of a timeframe string (\"1\", \"60\", \"240\", \"D\", \"1D\", \"W\", \"M\"); NaN when it is not one. */\nexport function timeframeSeconds(timeframe: string): number {\n const m = /^(\\d*)([SDWM]?)$/.exec(timeframe.trim().toUpperCase());\n if (!m) return NaN;\n const n = m[1] ? Number(m[1]) : 1;\n const unit = { '': 60, S: 1, D: 86400, W: 7 * 86400, M: 30 * 86400 }[m[2] as '' | 'S' | 'D' | 'W' | 'M'];\n return n * unit;\n}\n\n/** The timeframe of bars from the most common spacing of their times (\"60\", \"D\", \"W\"...); \"60\" for fewer than 2 bars. */\nexport function inferTimeframe(bars: readonly Bar[]): string {\n const counts = new Map<number, number>();\n for (let i = 1; i < bars.length; i++) {\n const d = bars[i]!.time - bars[i - 1]!.time;\n if (d > 0) counts.set(d, (counts.get(d) ?? 0) + 1);\n }\n let step = 0;\n let best = 0;\n for (const [d, c] of counts) if (c > best) [step, best] = [d, c];\n if (!step) return '60';\n if (step >= 28 * 86400) return 'M';\n if (step >= 7 * 86400) return 'W';\n if (step >= 86400) return 'D';\n if (step < 60) return `${step}S`;\n return String(Math.round(step / 60));\n}\n\nexport interface TestChartOptions {\n /** Chart timeframe (default \"60\"). */\n timeframe?: string;\n /** Chart ticker id (default \"TEST:SYN\"). */\n tickerid?: string;\n /** Time zone of the chart and of the other symbols (default \"Etc/UTC\"). */\n timezone?: string;\n /** Session of the chart and of the other symbols (default \"24x7\"). */\n session?: string;\n}\n\n/**\n * Chart context of the test runs: a 24x7 symbol in UTC. Higher timeframes of the chart symbol are resampled from the\n * chart bars by the library; other symbols get synthetic bars of their own (seeded by the symbol name).\n */\nexport function testChart(bars: Bar[], options: TestChartOptions = {}): ChartContext {\n const timezone = options.timezone ?? 'Etc/UTC';\n const session = options.session ?? '24x7';\n const chartStep = timeframeSeconds(options.timeframe ?? '60') || HOUR;\n const span = bars.length ? bars[bars.length - 1]!.time - bars[0]!.time + chartStep : 0;\n return {\n tickerid: options.tickerid ?? 'TEST:SYN',\n timeframe: options.timeframe ?? '60',\n timezone,\n session,\n mintick: 0.01,\n pointvalue: 1,\n mincontract: 1,\n currency: 'USD',\n bars: (symbol, timeframe) => {\n const step = timeframeSeconds(timeframe);\n if (!step) return [];\n // a run on zero bars (the declaration run of a host) gets one empty bar: no bars at all is an invalid symbol\n if (!bars.length) return [{ time: 0, open: 0, high: 0, low: 0, close: 0, volume: 0 }];\n const first = bars[0]!.time;\n return syntheticBars(Math.ceil(span / step), step, symbol.length + 7).map((b) => ({\n ...b,\n time: first + (b.time - START),\n }));\n },\n symbolInfo: () => ({ timezone, session, mintick: 0.01, currency: 'USD' }),\n };\n}\n\n/**\n * A small order engine for checks and tests (the library does not fill orders). Market entries and closes fill at the\n * next bar open; `strategy.exit` stop / limit levels are checked inside each bar (stop first when both are hit).\n * Entry limit / stop prices, pyramiding and process_orders_on_close are not simulated.\n */\n/** A saved state of {@link TestEngine} */\ninterface TestEngineState {\n closed: StrategyTrade[];\n open: StrategyTrade | null;\n pendingEntry: { id: string; direction: StrategyDirection; qty?: number } | null;\n pendingClose: boolean;\n exits: Map<string, StrategyExitOptions>;\n net: number;\n bar: number;\n}\n\nexport class TestEngine implements StrategyEngine {\n readonly closed: StrategyTrade[] = [];\n private open: StrategyTrade | null = null;\n private pendingEntry: { id: string; direction: StrategyDirection; qty?: number } | null = null;\n private pendingClose = false;\n private exits = new Map<string, StrategyExitOptions>();\n private net = 0;\n private bar = 0;\n\n constructor(readonly setup: StrategySetup) {}\n\n /** The engine state at the end of a bar, for incremental runs (#196) */\n save(): TestEngineState {\n return {\n closed: this.closed.map((t) => ({ ...t })),\n open: this.open ? { ...this.open } : null,\n pendingEntry: this.pendingEntry ? { ...this.pendingEntry } : null,\n pendingClose: this.pendingClose,\n exits: new Map([...this.exits].map(([k, v]) => [k, { ...v }])),\n net: this.net,\n bar: this.bar,\n };\n }\n\n restore(state: unknown): void {\n const s = state as TestEngineState;\n this.closed.length = 0;\n for (const t of s.closed) this.closed.push({ ...t });\n this.open = s.open ? { ...s.open } : null;\n this.pendingEntry = s.pendingEntry ? { ...s.pendingEntry } : null;\n this.pendingClose = s.pendingClose;\n this.exits = new Map([...s.exits].map(([k, v]) => [k, { ...v }]));\n this.net = s.net;\n this.bar = s.bar;\n }\n\n private get bars(): readonly Bar[] {\n return this.setup.bars;\n }\n\n private equity(price: number): number {\n return this.setup.properties.initial_capital + this.net + this.openProfit(price);\n }\n\n private openProfit(price: number): number {\n return this.open ? (price - this.open.entry_price) * this.open.size : 0;\n }\n\n private commission(value: number): number {\n const p = this.setup.properties;\n return p.commission_type === 'percent' ? (Math.abs(value) * p.commission_value) / 100 : 0;\n }\n\n private closeAt(price: number, exitId: string): void {\n const t = this.open;\n if (!t) return;\n const commission = t.commission + this.commission(price * t.size);\n const profit = (price - t.entry_price) * t.size - commission;\n this.net += profit;\n this.closed.push({\n ...t,\n commission,\n profit,\n profit_percent: (profit / Math.abs(t.entry_price * t.size)) * 100,\n exit_id: exitId,\n exit_price: price,\n exit_bar_index: this.bar,\n exit_time: this.bars[this.bar]!.time * 1000,\n });\n this.open = null;\n this.exits.clear();\n }\n\n /** The open trade, if any. */\n get openTradeNow(): StrategyTrade | null {\n return this.open;\n }\n\n processBar(bar: number): void {\n this.bar = bar;\n const b = this.bars[bar]!;\n if (this.pendingClose) this.closeAt(b.open, 'Close');\n this.pendingClose = false;\n const e = this.pendingEntry;\n this.pendingEntry = null;\n if (e && !(this.open && Math.sign(this.open.size) === (e.direction === 'long' ? 1 : -1))) {\n if (this.open) this.closeAt(b.open, e.id);\n const p = this.setup.properties;\n const equity = this.equity(b.open);\n const qty =\n e.qty ??\n (p.default_qty_type === 'fixed'\n ? p.default_qty_value\n : p.default_qty_type === 'cash'\n ? p.default_qty_value / b.open\n : (equity * p.default_qty_value) / 100 / b.open);\n const size = e.direction === 'long' ? qty : -qty;\n this.open = {\n entry_id: e.id,\n entry_price: b.open,\n entry_bar_index: bar,\n entry_time: b.time * 1000,\n size,\n profit: 0,\n profit_percent: 0,\n commission: this.commission(b.open * size),\n max_runup: 0,\n max_runup_percent: 0,\n max_drawdown: 0,\n max_drawdown_percent: 0,\n };\n }\n const t = this.open;\n if (!t) return;\n for (const [id, x] of this.exits) {\n if (x.from_entry !== undefined && x.from_entry !== t.entry_id) continue;\n const long = t.size > 0;\n if (x.stop !== undefined && (long ? b.low <= x.stop : b.high >= x.stop)) {\n this.closeAt(long ? Math.min(b.open, x.stop) : Math.max(b.open, x.stop), id);\n return;\n }\n if (x.limit !== undefined && (long ? b.high >= x.limit : b.low <= x.limit)) {\n this.closeAt(long ? Math.max(b.open, x.limit) : Math.min(b.open, x.limit), id);\n return;\n }\n }\n }\n\n processClose(): void {}\n\n entry(id: string, direction: StrategyDirection, options: StrategyEntryOptions): void {\n this.pendingEntry = { id, direction, qty: options.qty };\n }\n\n order(id: string, direction: StrategyDirection, options: StrategyEntryOptions): void {\n this.entry(id, direction, options);\n }\n\n exit(id: string, options: StrategyExitOptions): void {\n this.exits.set(id, options);\n }\n\n close(id: string, _options: StrategyCloseOptions): void {\n if (this.open?.entry_id === id) this.pendingClose = true;\n }\n\n close_all(): void {\n if (this.open) this.pendingClose = true;\n }\n\n cancel(id: string): void {\n this.exits.delete(id);\n if (this.pendingEntry?.id === id) this.pendingEntry = null;\n }\n\n cancel_all(): void {\n this.exits.clear();\n this.pendingEntry = null;\n }\n\n readonly rules: StrategyRiskRule[] = [];\n\n risk(rule: StrategyRiskRule): void {\n this.rules.push(rule);\n }\n\n get(variable: StrategyVariable): number | string | undefined {\n const price = this.bars[this.bar]?.close ?? NaN;\n const wins = this.closed.filter((t) => t.profit > 0).length;\n const values: Partial<Record<StrategyVariable, number | string>> = {\n position_size: this.open?.size ?? 0,\n position_avg_price: this.open?.entry_price ?? NaN,\n initial_capital: this.setup.properties.initial_capital,\n equity: this.equity(price),\n netprofit: this.net,\n openprofit: this.openProfit(price),\n opentrades: this.open ? 1 : 0,\n closedtrades: this.closed.length,\n wintrades: wins,\n losstrades: this.closed.length - wins,\n account_currency: 'USD',\n };\n return values[variable];\n }\n\n openTrade(index: number): StrategyTrade | undefined {\n return index === 0 && this.open ? this.open : undefined;\n }\n\n closedTrade(index: number): StrategyTrade | undefined {\n return this.closed[index];\n }\n}\n\nexport interface ScriptRun {\n run: ScriptRunResult;\n engine?: TestEngine;\n}\n\nexport interface RunScriptOptions extends TestChartOptions {\n /** Compiles the source (default {@link compileScript}); the CLI compiles with file lines. */\n compile?: (source: string) => () => void;\n}\n\n/** Runs a script source on `bars` with the test chart context and, for a strategy, the test engine. */\nexport function runScript(\n source: string,\n bars: Bar[],\n inputs: Record<string, unknown> = {},\n options: RunScriptOptions = {}\n): ScriptRun {\n let engine: TestEngine | undefined;\n const body = (options.compile ?? compileScript)(source);\n const run = executeScript(body, bars, inputs, testChart(bars, options), {\n strategyEngine: (setup) => (engine = new TestEngine(setup)),\n });\n return { run, engine };\n}\n\n/**\n * Why a live chart would calculate the script in full on every update (#196), or null when its updates are resumed:\n * the script runs as on a live chart, on the bars but the last one, then once more with the last bar (a resumed update,\n * compared with a full run).\n */\nexport function incrementalReason(\n source: string,\n bars: Bar[],\n inputs: Record<string, unknown> = {},\n options: RunScriptOptions = {}\n): string | null {\n if (bars.length < 2) return null;\n const body = (options.compile ?? compileScript)(source);\n const chart = testChart(bars, options);\n const run = createScriptRun(body, inputs, chart, { strategyEngine: (setup) => new TestEngine(setup), verify: 1 });\n run.update(bars.slice(0, -1), chart);\n run.update(bars, chart);\n return run.fullRunReason;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,UAAqB;AACrB,UAAqB;AACrB,
|
|
4
|
+
"sourcesContent": ["/**\n * @fileoverview Runs a script source the way a host app runs a script written in its editor: the source is the body\n * of the script, with every value export of `oakscriptjs/script` but `executeScript` as an implicit global, on\n * deterministic synthetic bars (or given bars), with a chart context and, for a strategy, a small order engine.\n * Used by {@link checkScript}, the `oakscript check` command and the tests of the agent guide.\n *\n * @module check/harness\n */\nimport * as lib from '../index.js';\nimport * as api from '../script/index.js';\nimport {\n createScriptRun,\n executeScript,\n type ChartContext,\n type ScriptRunResult,\n type StrategyCloseOptions,\n type StrategyDirection,\n type StrategyEngine,\n type StrategyEntryOptions,\n type StrategyExitOptions,\n type StrategyRiskRule,\n type StrategySetup,\n type StrategyTrade,\n type SymbolEvents,\n type StrategyVariable,\n} from '../script/index.js';\nimport type { Bar } from '../types/index.js';\n\n/** The implicit globals of a script: every value export of the script API but the host entry. */\nexport const SCRIPT_GLOBALS: readonly string[] = Object.keys(api).filter(\n (k) => k !== 'default' && k !== 'executeScript' && /^[A-Za-z_$][\\w$]*$/.test(k)\n);\n\n/** Name of the parameter that receives the `oakscriptjs` module in a compiled script (its `import` statements). */\nexport const LIBRARY_PARAMETER = '__oakscriptjs';\n\n/** The values of {@link SCRIPT_GLOBALS}, then the `oakscriptjs` module, in the order of the compiled parameters. */\nexport function scriptArguments(): unknown[] {\n return [...SCRIPT_GLOBALS.map((k) => (api as Record<string, unknown>)[k]), lib];\n}\n\n/**\n * Rewrites the `import { a, b as c } from \"oakscriptjs\"` statements of a script into `const { a, b: c } = ...` on the\n * same lines (the line numbers of the source do not change). Throws on an import of another module: a script runs\n * self-contained.\n */\nexport function rewriteImports(source: string): string {\n return source.replace(/^([ \\t]*)import\\s*(\\{[^}]*\\}|\\*\\s+as\\s+[A-Za-z_$][\\w$]*)\\s*from\\s*(['\"])([^'\"]+)\\3\\s*;?/gm, (all, indent, what, _q, from) => {\n if (from !== 'oakscriptjs' && from !== 'oakscriptjs/script') {\n throw new SyntaxError(`A script can only import from \"oakscriptjs\" (found \"${from}\").`);\n }\n const lines = all.split('\\n').length - 1;\n const binding = what.startsWith('*')\n ? what.replace(/^\\*\\s+as\\s+/, '')\n : what.replace(/\\s+as\\s+/g, ': ').replace(/\\s+/g, ' ');\n return `${indent}const ${binding} = ${LIBRARY_PARAMETER};${'\\n'.repeat(lines)}`;\n });\n}\n\n/**\n * Start and end of the function the script source is wrapped in. The globals are the parameters of an outer function\n * and the source is the body of an inner one, so a script can declare a name of a global (`const size = 2`), as in an\n * app that imports the globals at the top of a module. The start goes on the first line of the source.\n */\nexport const SCRIPT_PREFIX = '\"use strict\"; return (function () { ';\nexport const SCRIPT_SUFFIX = '\\n})();';\n\n/** The source of the function body of a compiled script (imports rewritten, lines kept). */\nexport function wrapSource(source: string): string {\n return SCRIPT_PREFIX + rewriteImports(source) + SCRIPT_SUFFIX;\n}\n\n/** Compiles a script source into a body for executeScript(); throws a SyntaxError on invalid code. */\nexport function compileScript(source: string): () => void {\n const fn = new Function(...SCRIPT_GLOBALS, LIBRARY_PARAMETER, wrapSource(source)) as (...args: unknown[]) => void;\n const values = scriptArguments();\n return () => fn(...values);\n}\n\nconst HOUR = 3600;\n/** 2024-01-01 00:00 UTC, in seconds. */\nconst START = 1704067200;\n\n/** Deterministic synthetic bars: two waves, a slow trend and seeded noise. `step`: seconds between bars. */\nexport function syntheticBars(count: number, step = HOUR, seed = 1): Bar[] {\n let s = seed >>> 0 || 1;\n const rand = (): number => {\n s = (Math.imul(s, 1664525) + 1013904223) >>> 0;\n return s / 2 ** 32;\n };\n const scale = Math.sqrt(step / HOUR);\n const bars: Bar[] = [];\n let prev = 100;\n for (let i = 0; i < count; i++) {\n const t = (i * step) / HOUR;\n const close = 100 + 12 * Math.sin(t / 60) + 4 * Math.sin(t / 11) + t * 0.004 + (rand() - 0.5) * 1.5 * scale;\n const open = prev;\n const high = Math.max(open, close) + rand() * 0.8 * scale;\n const low = Math.min(open, close) - rand() * 0.8 * scale;\n bars.push({ time: START + i * step, open, high, low, close, volume: Math.round(1000 + rand() * 4000) });\n prev = close;\n }\n return bars;\n}\n\n/** Seconds of a timeframe string (\"1\", \"60\", \"240\", \"D\", \"1D\", \"W\", \"M\"); NaN when it is not one. */\nexport function timeframeSeconds(timeframe: string): number {\n const m = /^(\\d*)([SDWM]?)$/.exec(timeframe.trim().toUpperCase());\n if (!m) return NaN;\n const n = m[1] ? Number(m[1]) : 1;\n const unit = { '': 60, S: 1, D: 86400, W: 7 * 86400, M: 30 * 86400 }[m[2] as '' | 'S' | 'D' | 'W' | 'M'];\n return n * unit;\n}\n\n/** The timeframe of bars from the most common spacing of their times (\"60\", \"D\", \"W\"...); \"60\" for fewer than 2 bars. */\nexport function inferTimeframe(bars: readonly Bar[]): string {\n const counts = new Map<number, number>();\n for (let i = 1; i < bars.length; i++) {\n const d = bars[i]!.time - bars[i - 1]!.time;\n if (d > 0) counts.set(d, (counts.get(d) ?? 0) + 1);\n }\n let step = 0;\n let best = 0;\n for (const [d, c] of counts) if (c > best) [step, best] = [d, c];\n if (!step) return '60';\n if (step >= 28 * 86400) return 'M';\n if (step >= 7 * 86400) return 'W';\n if (step >= 86400) return 'D';\n if (step < 60) return `${step}S`;\n return String(Math.round(step / 60));\n}\n\nexport interface TestChartOptions {\n /** Chart timeframe (default \"60\"). */\n timeframe?: string;\n /** Chart ticker id (default \"TEST:SYN\"). */\n tickerid?: string;\n /** Time zone of the chart and of the other symbols (default \"Etc/UTC\"). */\n timezone?: string;\n /** Session of the chart and of the other symbols (default \"24x7\"). */\n session?: string;\n}\n\n/**\n * Chart context of the test runs: a 24x7 symbol in UTC. Higher timeframes of the chart symbol are resampled from the\n * chart bars by the library; other symbols get synthetic bars of their own (seeded by the symbol name).\n */\nexport function testChart(bars: Bar[], options: TestChartOptions = {}): ChartContext {\n const timezone = options.timezone ?? 'Etc/UTC';\n const session = options.session ?? '24x7';\n const chartStep = timeframeSeconds(options.timeframe ?? '60') || HOUR;\n const span = bars.length ? bars[bars.length - 1]!.time - bars[0]!.time + chartStep : 0;\n return {\n tickerid: options.tickerid ?? 'TEST:SYN',\n timeframe: options.timeframe ?? '60',\n timezone,\n session,\n mintick: 0.01,\n pointvalue: 1,\n mincontract: 1,\n currency: 'USD',\n bars: (symbol, timeframe) => {\n const step = timeframeSeconds(timeframe);\n if (!step) return [];\n // a run on zero bars (the declaration run of a host) gets one empty bar: no bars at all is an invalid symbol\n if (!bars.length) return [{ time: 0, open: 0, high: 0, low: 0, close: 0, volume: 0 }];\n const first = bars[0]!.time;\n return syntheticBars(Math.ceil(span / step), step, symbol.length + 7).map((b) => ({\n ...b,\n time: first + (b.time - START),\n }));\n },\n symbolInfo: () => ({ timezone, session, mintick: 0.01, currency: 'USD' }),\n // the other symbol fields: none (na), so that a script reading them runs\n symbolType: 'stock',\n description: 'Synthetic test symbol',\n ...NO_SYMBOL_FIELDS,\n events: () => testEvents(bars),\n };\n}\n\nconst NO_SYMBOL_FIELDS = {\n basecurrency: null, country: null, currentContract: null, expirationDate: null, sector: null, industry: null,\n isin: null, volumetype: null, employees: null, shareholders: null, sharesOutstandingTotal: null,\n sharesOutstandingFloat: null, recommendations: null, targetPrice: null,\n} satisfies Partial<ChartContext>;\n\n/** Events of the test symbol: a dividend and an earnings release every 90 days of its bars, a 2-for-1 split half-way. */\nfunction testEvents(bars: Bar[]): SymbolEvents {\n if (!bars.length) return {};\n const first = bars[0]!.time * 1000;\n const last = bars[bars.length - 1]!.time * 1000;\n const QUARTER = 90 * 86_400_000;\n const dividends: SymbolEvents['dividends'] = [];\n const earnings: SymbolEvents['earnings'] = [];\n for (let t = first, k = 1; t <= last; t += QUARTER, k++) {\n dividends.push({ time: t, net: 0.2 + 0.01 * k });\n earnings.push({ time: t + 30 * 86_400_000, actual: 1 + 0.1 * k, estimate: 1 + 0.09 * k, standardized: 1 + 0.1 * k });\n }\n return { dividends, earnings, splits: [{ time: Math.round((first + last) / 2), numerator: 2, denominator: 1 }] };\n}\n\n/**\n * A small order engine for checks and tests (the library does not fill orders). Market entries and closes fill at the\n * next bar open; `strategy.exit` stop / limit levels are checked inside each bar (stop first when both are hit).\n * Entry limit / stop prices, pyramiding and process_orders_on_close are not simulated.\n */\n/** A saved state of {@link TestEngine} */\ninterface TestEngineState {\n closed: StrategyTrade[];\n open: StrategyTrade | null;\n pendingEntry: { id: string; direction: StrategyDirection; qty?: number } | null;\n pendingClose: boolean;\n exits: Map<string, StrategyExitOptions>;\n net: number;\n bar: number;\n}\n\nexport class TestEngine implements StrategyEngine {\n readonly closed: StrategyTrade[] = [];\n private open: StrategyTrade | null = null;\n private pendingEntry: { id: string; direction: StrategyDirection; qty?: number } | null = null;\n private pendingClose = false;\n private exits = new Map<string, StrategyExitOptions>();\n private net = 0;\n private bar = 0;\n\n constructor(readonly setup: StrategySetup) {}\n\n /** The engine state at the end of a bar, for incremental runs (#196) */\n save(): TestEngineState {\n return {\n closed: this.closed.map((t) => ({ ...t })),\n open: this.open ? { ...this.open } : null,\n pendingEntry: this.pendingEntry ? { ...this.pendingEntry } : null,\n pendingClose: this.pendingClose,\n exits: new Map([...this.exits].map(([k, v]) => [k, { ...v }])),\n net: this.net,\n bar: this.bar,\n };\n }\n\n restore(state: unknown): void {\n const s = state as TestEngineState;\n this.closed.length = 0;\n for (const t of s.closed) this.closed.push({ ...t });\n this.open = s.open ? { ...s.open } : null;\n this.pendingEntry = s.pendingEntry ? { ...s.pendingEntry } : null;\n this.pendingClose = s.pendingClose;\n this.exits = new Map([...s.exits].map(([k, v]) => [k, { ...v }]));\n this.net = s.net;\n this.bar = s.bar;\n }\n\n private get bars(): readonly Bar[] {\n return this.setup.bars;\n }\n\n private equity(price: number): number {\n return this.setup.properties.initial_capital + this.net + this.openProfit(price);\n }\n\n private openProfit(price: number): number {\n return this.open ? (price - this.open.entry_price) * this.open.size : 0;\n }\n\n private commission(value: number): number {\n const p = this.setup.properties;\n return p.commission_type === 'percent' ? (Math.abs(value) * p.commission_value) / 100 : 0;\n }\n\n private closeAt(price: number, exitId: string): void {\n const t = this.open;\n if (!t) return;\n const commission = t.commission + this.commission(price * t.size);\n const profit = (price - t.entry_price) * t.size - commission;\n this.net += profit;\n this.closed.push({\n ...t,\n commission,\n profit,\n profit_percent: (profit / Math.abs(t.entry_price * t.size)) * 100,\n exit_id: exitId,\n exit_price: price,\n exit_bar_index: this.bar,\n exit_time: this.bars[this.bar]!.time * 1000,\n });\n this.open = null;\n this.exits.clear();\n }\n\n /** The open trade, if any. */\n get openTradeNow(): StrategyTrade | null {\n return this.open;\n }\n\n processBar(bar: number): void {\n this.bar = bar;\n const b = this.bars[bar]!;\n if (this.pendingClose) this.closeAt(b.open, 'Close');\n this.pendingClose = false;\n const e = this.pendingEntry;\n this.pendingEntry = null;\n if (e && !(this.open && Math.sign(this.open.size) === (e.direction === 'long' ? 1 : -1))) {\n if (this.open) this.closeAt(b.open, e.id);\n const p = this.setup.properties;\n const equity = this.equity(b.open);\n const qty =\n e.qty ??\n (p.default_qty_type === 'fixed'\n ? p.default_qty_value\n : p.default_qty_type === 'cash'\n ? p.default_qty_value / b.open\n : (equity * p.default_qty_value) / 100 / b.open);\n const size = e.direction === 'long' ? qty : -qty;\n this.open = {\n entry_id: e.id,\n entry_price: b.open,\n entry_bar_index: bar,\n entry_time: b.time * 1000,\n size,\n profit: 0,\n profit_percent: 0,\n commission: this.commission(b.open * size),\n max_runup: 0,\n max_runup_percent: 0,\n max_drawdown: 0,\n max_drawdown_percent: 0,\n };\n }\n const t = this.open;\n if (!t) return;\n for (const [id, x] of this.exits) {\n if (x.from_entry !== undefined && x.from_entry !== t.entry_id) continue;\n const long = t.size > 0;\n if (x.stop !== undefined && (long ? b.low <= x.stop : b.high >= x.stop)) {\n this.closeAt(long ? Math.min(b.open, x.stop) : Math.max(b.open, x.stop), id);\n return;\n }\n if (x.limit !== undefined && (long ? b.high >= x.limit : b.low <= x.limit)) {\n this.closeAt(long ? Math.max(b.open, x.limit) : Math.min(b.open, x.limit), id);\n return;\n }\n }\n }\n\n processClose(): void {}\n\n entry(id: string, direction: StrategyDirection, options: StrategyEntryOptions): void {\n this.pendingEntry = { id, direction, qty: options.qty };\n }\n\n order(id: string, direction: StrategyDirection, options: StrategyEntryOptions): void {\n this.entry(id, direction, options);\n }\n\n exit(id: string, options: StrategyExitOptions): void {\n this.exits.set(id, options);\n }\n\n close(id: string, _options: StrategyCloseOptions): void {\n if (this.open?.entry_id === id) this.pendingClose = true;\n }\n\n close_all(): void {\n if (this.open) this.pendingClose = true;\n }\n\n cancel(id: string): void {\n this.exits.delete(id);\n if (this.pendingEntry?.id === id) this.pendingEntry = null;\n }\n\n cancel_all(): void {\n this.exits.clear();\n this.pendingEntry = null;\n }\n\n readonly rules: StrategyRiskRule[] = [];\n\n risk(rule: StrategyRiskRule): void {\n this.rules.push(rule);\n }\n\n get(variable: StrategyVariable): number | string | undefined {\n const price = this.bars[this.bar]?.close ?? NaN;\n const wins = this.closed.filter((t) => t.profit > 0).length;\n const values: Partial<Record<StrategyVariable, number | string>> = {\n position_size: this.open?.size ?? 0,\n position_avg_price: this.open?.entry_price ?? NaN,\n initial_capital: this.setup.properties.initial_capital,\n equity: this.equity(price),\n netprofit: this.net,\n openprofit: this.openProfit(price),\n opentrades: this.open ? 1 : 0,\n closedtrades: this.closed.length,\n wintrades: wins,\n losstrades: this.closed.length - wins,\n account_currency: 'USD',\n };\n return values[variable];\n }\n\n openTrade(index: number): StrategyTrade | undefined {\n return index === 0 && this.open ? this.open : undefined;\n }\n\n closedTrade(index: number): StrategyTrade | undefined {\n return this.closed[index];\n }\n}\n\nexport interface ScriptRun {\n run: ScriptRunResult;\n engine?: TestEngine;\n}\n\nexport interface RunScriptOptions extends TestChartOptions {\n /** Compiles the source (default {@link compileScript}); the CLI compiles with file lines. */\n compile?: (source: string) => () => void;\n}\n\n/** Runs a script source on `bars` with the test chart context and, for a strategy, the test engine. */\nexport function runScript(\n source: string,\n bars: Bar[],\n inputs: Record<string, unknown> = {},\n options: RunScriptOptions = {}\n): ScriptRun {\n let engine: TestEngine | undefined;\n const body = (options.compile ?? compileScript)(source);\n const run = executeScript(body, bars, inputs, testChart(bars, options), {\n strategyEngine: (setup) => (engine = new TestEngine(setup)),\n });\n return { run, engine };\n}\n\n/**\n * Why a live chart would calculate the script in full on every update (#196), or null when its updates are resumed:\n * the script runs as on a live chart, on the bars but the last one, then once more with the last bar (a resumed update,\n * compared with a full run).\n */\nexport function incrementalReason(\n source: string,\n bars: Bar[],\n inputs: Record<string, unknown> = {},\n options: RunScriptOptions = {}\n): string | null {\n if (bars.length < 2) return null;\n const body = (options.compile ?? compileScript)(source);\n const chart = testChart(bars, options);\n const run = createScriptRun(body, inputs, chart, { strategyEngine: (setup) => new TestEngine(setup), verify: 1 });\n run.update(bars.slice(0, -1), chart);\n run.update(bars, chart);\n return run.fullRunReason;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,UAAqB;AACrB,UAAqB;AACrB,oBAeO;AAIA,MAAM,iBAAoC,OAAO,KAAK,GAAG,EAAE;AAAA,EAChE,CAAC,MAAM,MAAM,aAAa,MAAM,mBAAmB,qBAAqB,KAAK,CAAC;AAChF;AAGO,MAAM,oBAAoB;AAG1B,SAAS,kBAA6B;AAC3C,SAAO,CAAC,GAAG,eAAe,IAAI,CAAC,MAAO,IAAgC,CAAC,CAAC,GAAG,GAAG;AAChF;AAOO,SAAS,eAAe,QAAwB;AACrD,SAAO,OAAO,QAAQ,6FAA6F,CAAC,KAAK,QAAQ,MAAM,IAAI,SAAS;AAClJ,QAAI,SAAS,iBAAiB,SAAS,sBAAsB;AAC3D,YAAM,IAAI,YAAY,uDAAuD,IAAI,KAAK;AAAA,IACxF;AACA,UAAM,QAAQ,IAAI,MAAM,IAAI,EAAE,SAAS;AACvC,UAAM,UAAU,KAAK,WAAW,GAAG,IAC/B,KAAK,QAAQ,eAAe,EAAE,IAC9B,KAAK,QAAQ,aAAa,IAAI,EAAE,QAAQ,QAAQ,GAAG;AACvD,WAAO,GAAG,MAAM,SAAS,OAAO,MAAM,iBAAiB,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,EAC/E,CAAC;A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AAM,QAAQ,OAAO,EAAE,gBAAgB,CAAC,UAAU,IAAI,WAAW,KAAK,GAAG,QAAQ,EAAE,CAAC;AAChH,MAAI,OAAO,KAAK,MAAM,GAAG,EAAE,GAAG,KAAK;AACnC,MAAI,OAAO,MAAM,KAAK;AACtB,SAAO,IAAI;AACb;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
* Conversion rules:
|
|
6
6
|
* - x coordinates become bar times: a `bar_index` x is the time of that bar, or of a future bar after the last bar
|
|
7
7
|
* (see {@link barTime}); a `bar_time` x (UNIX ms, as PineScript) is converted to the unit of the bar times and the
|
|
8
|
-
* object keeps `xloc: 'bar_time'` (a renderer places a time after the last bar on the chart's own calendar)
|
|
8
|
+
* object keeps `xloc: 'bar_time'` (a renderer places a time after the last bar on the chart's own calendar); a `pane`
|
|
9
|
+
* x (percent of the pane's width) is kept in the time fields, with `xloc: 'pane'`
|
|
9
10
|
* - an object with an `na` coordinate (or a bar index before the first bar) is not drawn, as in PineScript
|
|
10
11
|
* - a property the script did not set is omitted (the renderer uses the PineScript default); a colour set to `na`
|
|
11
12
|
* is 'transparent'
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output.d.ts","sourceRoot":"","sources":["../../../src/drawing/output.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"output.d.ts","sourceRoot":"","sources":["../../../src/drawing/output.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAKH,OAAO,KAAK,EACV,OAAO,EACP,SAAS,EACT,eAAe,EACf,YAAY,EACZ,YAAY,EAEZ,SAAS,EACV,MAAM,sBAAsB,CAAC;AAE9B,sFAAsF;AACtF,MAAM,WAAW,cAAc;IAC7B,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC;IACrB,KAAK,CAAC,EAAE,eAAe,EAAE,CAAC;IAC1B,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC;IAClB,SAAS,CAAC,EAAE,YAAY,EAAE,CAAC;IAC3B,SAAS,CAAC,EAAE,YAAY,EAAE,CAAC;IAC3B,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC;CACtB;AAsBD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,aAAa,CAAC;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,EAAE,QAAQ,GAAE,GAAG,GAAG,IAAU,GAAG,cAAc,CAiKhH"}
|
|
@@ -33,11 +33,11 @@ function compact(obj) {
|
|
|
33
33
|
return obj;
|
|
34
34
|
}
|
|
35
35
|
const overlay = (flag) => flag ? true : void 0;
|
|
36
|
-
const xlocOut = (xloc) => xloc === "bar_time"
|
|
36
|
+
const xlocOut = (xloc) => xloc === "bar_time" || xloc === "pane" ? xloc : void 0;
|
|
37
37
|
function drawingOutputs(bars, timeUnit = "s") {
|
|
38
38
|
const interval = (0, import_bar_time.barInterval)(bars);
|
|
39
39
|
const msUnit = timeUnit === "ms" ? 1 : 1e3;
|
|
40
|
-
const xTime = (x, xloc) => xloc === "bar_time" ? x / msUnit : (0, import_bar_time.barTime)(bars, x, interval);
|
|
40
|
+
const xTime = (x, xloc) => xloc === "pane" ? x : xloc === "bar_time" ? x / msUnit : (0, import_bar_time.barTime)(bars, x, interval);
|
|
41
41
|
const ok = (...values) => values.every(Number.isFinite);
|
|
42
42
|
const lineData = (l) => {
|
|
43
43
|
const time1 = xTime(l.x1, l.xloc);
|
|
@@ -58,7 +58,8 @@ function drawingOutputs(bars, timeUnit = "s") {
|
|
|
58
58
|
};
|
|
59
59
|
const labelData = (l) => {
|
|
60
60
|
const time = xTime(l.x, l.xloc);
|
|
61
|
-
|
|
61
|
+
const yloc = l.xloc === "pane" ? "price" : l.yloc;
|
|
62
|
+
if (!ok(time) || yloc === "price" && !ok(l.y)) return void 0;
|
|
62
63
|
return compact({
|
|
63
64
|
time,
|
|
64
65
|
price: l.y,
|
|
@@ -68,7 +69,7 @@ function drawingOutputs(bars, timeUnit = "s") {
|
|
|
68
69
|
textColor: colorOut(l.textcolor),
|
|
69
70
|
style: l.style,
|
|
70
71
|
size: l.size,
|
|
71
|
-
yloc
|
|
72
|
+
yloc,
|
|
72
73
|
textAlign: l.textalign,
|
|
73
74
|
tooltip: l.tooltip,
|
|
74
75
|
fontFamily: l.text_font_family,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/drawing/output.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Renderable form of the live drawing objects (labels, lines, boxes, linefills, polylines, tables): the\n * `IndicatorResult` fields `labels`, `lines`, `boxes`, `linefills`, `polylines` and `tables`.\n *\n * Conversion rules:\n * - x coordinates become bar times: a `bar_index` x is the time of that bar, or of a future bar after the last bar\n * (see {@link barTime}); a `bar_time` x (UNIX ms, as PineScript) is converted to the unit of the bar times and the\n * object keeps `xloc: 'bar_time'` (a renderer places a time after the last bar on the chart's own calendar)
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;
|
|
4
|
+
"sourcesContent": ["/**\n * Renderable form of the live drawing objects (labels, lines, boxes, linefills, polylines, tables): the\n * `IndicatorResult` fields `labels`, `lines`, `boxes`, `linefills`, `polylines` and `tables`.\n *\n * Conversion rules:\n * - x coordinates become bar times: a `bar_index` x is the time of that bar, or of a future bar after the last bar\n * (see {@link barTime}); a `bar_time` x (UNIX ms, as PineScript) is converted to the unit of the bar times and the\n * object keeps `xloc: 'bar_time'` (a renderer places a time after the last bar on the chart's own calendar); a `pane`\n * x (percent of the pane's width) is kept in the time fields, with `xloc: 'pane'`\n * - an object with an `na` coordinate (or a bar index before the first bar) is not drawn, as in PineScript\n * - a property the script did not set is omitted (the renderer uses the PineScript default); a colour set to `na`\n * is 'transparent'\n * - `force_overlay` is kept only when true\n *\n * @module drawing/output\n */\n\nimport { all } from './registry.js';\nimport { barInterval, barTime } from './bar-time.js';\nimport type { Box, ChartPoint, Label, Line, Polyline, Table, color } from '../types/index.js';\nimport type {\n BoxData,\n LabelData,\n LineDrawingData,\n LinefillData,\n PolylineData,\n TableCellData,\n TableData,\n} from '../types/metadata.js';\n\n/** Drawing fields of an IndicatorResult; a kind without live objects is undefined. */\nexport interface DrawingOutputs {\n labels?: LabelData[];\n lines?: LineDrawingData[];\n boxes?: BoxData[];\n linefills?: LinefillData[];\n polylines?: PolylineData[];\n tables?: TableData[];\n}\n\n/** A colour of the result: 'transparent' for na (null), '#rrggbb' for a numeric colour. */\nfunction colorOut(c: color | null | undefined): string | undefined {\n if (c === undefined) return undefined;\n if (c === null || (typeof c === 'number' && Number.isNaN(c))) return 'transparent';\n return typeof c === 'number' ? `#${(c & 0xffffff).toString(16).padStart(6, '0')}` : c;\n}\n\n/** The object without its undefined fields (so that the result has only the properties that were set). */\nfunction compact<T extends object>(obj: T): T {\n for (const k of Object.keys(obj) as Array<keyof T>) if (obj[k] === undefined) delete obj[k];\n return obj;\n}\n\nconst overlay = (flag: boolean | undefined): true | undefined => (flag ? true : undefined);\n\ntype Xloc = 'bar_index' | 'bar_time' | 'pane';\n\n/** xloc of the result: omitted for bar indexes. */\nconst xlocOut = (xloc: Xloc): 'bar_time' | 'pane' | undefined => (xloc === 'bar_time' || xloc === 'pane' ? xloc : undefined);\n\n/**\n * Converts the live drawing objects of the registry. `bars` are the chart bars (their `time` in `timeUnit`, 's' by\n * default as lightweight-charts); they give the time of a bar index.\n */\nexport function drawingOutputs(bars: ReadonlyArray<{ time: number }>, timeUnit: 's' | 'ms' = 's'): DrawingOutputs {\n const interval = barInterval(bars);\n const msUnit = timeUnit === 'ms' ? 1 : 1000;\n const xTime = (x: number, xloc: Xloc): number =>\n xloc === 'pane' ? x : xloc === 'bar_time' ? x / msUnit : barTime(bars, x, interval);\n const ok = (...values: number[]): boolean => values.every(Number.isFinite);\n\n const lineData = (l: Line): LineDrawingData | undefined => {\n const time1 = xTime(l.x1, l.xloc);\n const time2 = xTime(l.x2, l.xloc);\n if (!ok(time1, time2, l.y1, l.y2)) return undefined;\n return compact({\n time1,\n price1: l.y1,\n time2,\n price2: l.y2,\n xloc: xlocOut(l.xloc),\n color: colorOut(l.color),\n width: l.width,\n style: l.style,\n extend: l.extend,\n forceOverlay: overlay(l.force_overlay),\n });\n };\n\n const labelData = (l: Label): LabelData | undefined => {\n const time = xTime(l.x, l.xloc);\n // abovebar / belowbar labels are placed at the bar, not at y; a label placed on the pane has no bar: at y\n const yloc = l.xloc === 'pane' ? 'price' : l.yloc;\n if (!ok(time) || (yloc === 'price' && !ok(l.y))) return undefined;\n return compact({\n time,\n price: l.y,\n xloc: xlocOut(l.xloc),\n text: l.text ?? '',\n color: colorOut(l.color),\n textColor: colorOut(l.textcolor),\n style: l.style,\n size: l.size as LabelData['size'],\n yloc,\n textAlign: l.textalign,\n tooltip: l.tooltip,\n fontFamily: l.text_font_family,\n textFormatting: l.text_formatting,\n forceOverlay: overlay(l.force_overlay),\n });\n };\n\n const boxData = (b: Box): BoxData | undefined => {\n const time1 = xTime(b.left, b.xloc);\n const time2 = xTime(b.right, b.xloc);\n if (!ok(time1, time2, b.top, b.bottom)) return undefined;\n return compact({\n time1,\n price1: b.top,\n time2,\n price2: b.bottom,\n xloc: xlocOut(b.xloc),\n bgColor: colorOut(b.bgcolor),\n borderColor: colorOut(b.border_color),\n borderWidth: b.border_width,\n borderStyle: b.border_style,\n text: b.text,\n textColor: colorOut(b.text_color),\n textSize: b.text_size as BoxData['textSize'],\n textHAlign: b.text_halign,\n textVAlign: b.text_valign,\n textWrap: b.text_wrap,\n fontFamily: b.text_font_family,\n textFormatting: b.text_formatting,\n extend: b.extend,\n forceOverlay: overlay(b.force_overlay),\n });\n };\n\n const polylineData = (p: Polyline): PolylineData | undefined => {\n const points: PolylineData['points'] = [];\n for (const point of p.points as ChartPoint[]) {\n const x = p.xloc === 'bar_time' ? point.time : point.index;\n const time = x === null ? NaN : xTime(x, p.xloc);\n if (ok(time, point.price)) points.push({ time, price: point.price });\n }\n if (points.length === 0) return undefined;\n return compact({\n points,\n xloc: xlocOut(p.xloc),\n curved: p.curved,\n closed: p.closed,\n lineColor: colorOut(p.line_color),\n fillColor: p.fill_color === null ? undefined : colorOut(p.fill_color),\n lineStyle: p.line_style,\n lineWidth: p.line_width,\n forceOverlay: overlay(p.force_overlay),\n });\n };\n\n const tableData = (t: Table): TableData => {\n const cells: TableCellData[] = [];\n for (const [key, c] of t.cells ?? []) {\n const [column, row] = key.split(',').map(Number) as [number, number];\n cells.push(\n compact({\n row,\n column,\n text: c.text ?? '',\n bgColor: colorOut(c.bgcolor),\n textColor: colorOut(c.text_color),\n textSize: c.text_size as TableCellData['textSize'],\n width: c.width,\n height: c.height,\n textHAlign: c.text_halign,\n textVAlign: c.text_valign,\n tooltip: c.tooltip,\n fontFamily: c.text_font_family,\n textFormatting: c.text_formatting,\n })\n );\n }\n cells.sort((a, b) => a.row - b.row || a.column - b.column);\n const merges = (t.merges ?? []).map((m) => ({\n startColumn: m.start_column,\n startRow: m.start_row,\n endColumn: m.end_column,\n endRow: m.end_row,\n }));\n return compact({\n position: t.position,\n columns: t.columns,\n rows: t.rows,\n cells,\n merges: merges.length ? merges : undefined,\n bgColor: colorOut(t.bgcolor),\n frameColor: colorOut(t.frame_color),\n frameWidth: t.frame_width,\n borderColor: colorOut(t.border_color),\n borderWidth: t.border_width,\n forceOverlay: overlay(t.force_overlay),\n });\n };\n\n const convert = <T, R>(items: T[], fn: (item: T) => R | undefined): R[] | undefined => {\n const out: R[] = [];\n for (const item of items) {\n const r = fn(item);\n if (r !== undefined) out.push(r);\n }\n return out.length ? out : undefined;\n };\n\n return {\n labels: convert(all('label'), labelData),\n lines: convert(all('line'), lineData),\n boxes: convert(all('box'), boxData),\n linefills: convert(all('linefill'), (f): LinefillData | undefined => {\n const line1 = lineData(f.line1);\n const line2 = lineData(f.line2);\n return line1 && line2 ? compact({ line1, line2, color: colorOut(f.color) }) : undefined;\n }),\n polylines: conv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I,MAAM,GAAG,QAAQ;AAAA,IACpC,OAAO,YAAQ,qBAAI,KAAK,GAAG,OAAO;AAAA,IAClC,WAAW,YAAQ,qBAAI,UAAU,GAAG,CAAC,MAAgC;AACnE,YAAM,QAAQ,SAAS,EAAE,KAAK;AAC9B,YAAM,QAAQ,SAAS,EAAE,KAAK;AAC9B,aAAO,SAAS,QAAQ,QAAQ,EAAE,OAAO,OAAO,OAAO,SAAS,EAAE,KAAK,EAAE,CAAC,IAAI;AAAA,IAChF,CAAC;AAAA,IACD,WAAW,YAAQ,qBAAI,UAAU,GAAG,YAAY;AAAA,IAChD,QAAQ,YAAQ,qBAAI,OAAO,GAAG,SAAS;AAAA,EACzC;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -66,7 +66,7 @@ export type * from './strategy/index.js';
|
|
|
66
66
|
export { LightweightChartsAdapter } from './runtime/adapters/LightweightChartsAdapter.js';
|
|
67
67
|
export type { LightweightSeriesDefinitions } from './runtime/adapters/LightweightChartsAdapter.js';
|
|
68
68
|
export { SimpleInputAdapter } from './runtime/adapters/SimpleInputAdapter.js';
|
|
69
|
-
export declare const VERSION = "0.
|
|
69
|
+
export declare const VERSION = "0.20.0";
|
|
70
70
|
/**
|
|
71
71
|
* Library information
|
|
72
72
|
*/
|
package/dist/cjs/index.js
CHANGED
|
@@ -213,7 +213,7 @@ var import_input_active = require("./runtime/input-active.js");
|
|
|
213
213
|
var import_strategy = require("./strategy/index.js");
|
|
214
214
|
var import_LightweightChartsAdapter = require("./runtime/adapters/LightweightChartsAdapter.js");
|
|
215
215
|
var import_SimpleInputAdapter = require("./runtime/adapters/SimpleInputAdapter.js");
|
|
216
|
-
const VERSION = "0.
|
|
216
|
+
const VERSION = "0.20.0";
|
|
217
217
|
const info = {
|
|
218
218
|
name: "OakScriptJS",
|
|
219
219
|
version: VERSION,
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * OakScriptJS - Simplified PineScript-like library for JavaScript\n *\n * This library provides Series-based lazy evaluation and technical analysis functions\n * for building trading indicators. The PineScript-style script API is in `oakscriptjs/script`.\n *\n * Key features:\n * - Series class for lazy evaluation and method chaining\n * - Core TA functions (array-based)\n * - TA-Series wrappers (Series-based)\n *\n * @packageDocumentation\n */\n\n// Export all types\nexport * from './types/index.js';\nexport * from './types/metadata.js';\n\n// Export core namespaces (array-based functions)\nimport * as taCore from './ta/index.js';\nimport * as math from './math/index.js';\nimport * as array from './array/index.js';\nimport * as map from './map/index.js';\nimport * as str from './str/index.js';\nimport * as color from './color/index.js';\nimport * as time from './time/index.js';\nimport * as timeframe from './timeframe/index.js';\nimport * as matrix from './matrix/index.js';\nimport * as line from './line/index.js';\nimport * as box from './box/index.js';\nimport * as label from './label/index.js';\nimport * as linefill from './linefill/index.js';\nimport * as chartPoint from './chartpoint/index.js';\nimport * as polyline from './polyline/index.js';\nimport * as table from './table/index.js';\nimport * as text from './text/index.js';\nimport * as compare from './compare/index.js';\nimport * as callsite from './callsite/index.js';\n\nexport { taCore, math, array, map, str, color, time, timeframe, matrix, line, box, label, linefill, chartPoint, polyline, table, text, compare, callsite };\n\n// ta.* one bar at a time (step / commit), for incremental calculations (#196)\nexport { taStep, type BarStep } from './ta/step.js';\n\n// Renderable drawings (IndicatorResult labels, lines, boxes, linefills, polylines, tables) and future bar times\nexport { drawingOutputs, type DrawingOutputs } from './drawing/output.js';\nexport { barInterval, barTime } from './drawing/bar-time.js';\n\n// Drawing registry limits (PineScript indicator(max_lines_count / max_labels_count / max_boxes_count / max_polylines_count)),\n// and the drawing checkpoint of a port with its own bar loop (live updates of the forming bar, #203)\nexport {\n resetDrawings,\n setDrawingLimits,\n setDrawingBar,\n holdDrawing,\n releaseDrawing,\n varDrawing,\n createdDrawingKinds,\n saveDrawingCheckpoint,\n restoreDrawingCheckpoint,\n type DrawingCheckpoint,\n type DrawingKind,\n type DrawingLimits,\n type DrawingVariable,\n} from './drawing/registry.js';\n\n// The session of a chart context without a script run: time(tf, session, timezone), time_close(...), time_tradingday,\n// session.* flags, request.security periods with the session and holidays, and bars after the last bar on the trading\n// calendar\nexport {\n chartSessions,\n sessionPeriods,\n periodTime,\n periodClose,\n tradingDayTime,\n chartSessionFlags,\n resampleSession,\n barTimeAfter,\n barsUntil,\n type SessionContext,\n type ChartSessions,\n type SessionPeriods,\n type SessionResample,\n} from './session/context.js';\nexport { TradingCalendar, type SessionSpec } from './session/calendar.js';\nexport { SessionBars, sessionFlags, type SessionFlags } from './session/bars.js';\n\n// Same-symbol request.security on a higher timeframe (completion and lookahead rules) and ticker.heikinashi\nexport { resample, periodsOf, afterCompletion, mapToChart, heikinAshi, type Resampled } from './security/resample.js';\n// request.security of another symbol: which bar of the other symbol each chart bar shows (#179)\nexport {\n securityOther,\n securityOtherValues,\n securityLowerTf,\n MAX_INTRABARS,\n type OtherSymbolChart,\n type OtherSymbolOptions,\n type SymbolCalendar,\n} from './security/other.js';\n\n// Export Series class (self-contained, no context)\nexport { Series, BarData } from './runtime/series.js';\nexport type { SeriesExtractor } from './runtime/series.js';\n\n// Export TA-Series namespace (Series-based wrappers)\nimport * as ta from './ta-series.js';\nexport { ta };\n\n// Export metadata types for indicator return values\nexport type {\n PlotOptions,\n HLineOptions,\n FillOptions,\n InputMetadata,\n PlotMetadata,\n IndicatorMetadata,\n TimeValue,\n PlotData,\n HLineData,\n FillData,\n FillGradient,\n IndicatorResult,\n IndicatorFactory,\n PlotStyle,\n LineStyle,\n PlotDisplay,\n InputType\n} from './types/metadata.js';\n\n// Re-export commonly used functions for convenience\nexport { sma, ema, rsi, macd, bb, stdev, crossover, crossunder, change, tr, atr, cum, vwap } from './ta-series.js';\nexport { abs, ceil, floor, round, max, min, avg, sum, sqrt, pow, exp, log, sin, cos, tan } from './math/index.js';\nexport { rgb, from_hex as color_from_hex, new_color } from './color/index.js';\n\n// Export chart data utilities\nexport { ohlcFromBars, getClose, getHigh, getLow, getOpen, getSource, getSourceSeries, at, div } from './utils/index.js';\nexport { setSourceResolver, externalSource, BUILTIN_SOURCES, type SourceResolver } from './utils/source-resolver.js';\n\n// Export libraries (ZigZag, etc.)\nexport * from './lib/index.js';\n\n// Export helper functions for generated indicators (PineScript compatibility)\nexport {isNA as na, nz, fixnan} from './utils/index.js';\n\n// Export indicator infrastructure\nexport {\n indicator,\n type IndicatorMetadataConfig,\n type InputDefinition,\n type IndicatorContext,\n type IndicatorInstance,\n type IndicatorConstructor,\n} from './indicator.js';\n\nexport {\n input,\n type InputValue,\n type IntInputOptions,\n type FloatInputOptions,\n type SourceInputOptions,\n type BoolInputOptions,\n type StringInputOptions,\n type TimeInputOptions,\n type SourceType,\n} from './input.js';\n\nexport {\n plot as plotHelper,\n createPlot,\n type Time,\n type TimeValuePair,\n type PlotOptions as PlotHelperOptions,\n type PlotResult,\n} from './plot.js';\n\n// Runtime exports - global context runtime (setContext, plot, hline) drawing through a ChartAdapter\nexport {\n setContext,\n clearContext,\n getContext,\n registerCalculate,\n recalculate,\n plot,\n hline,\n clearPlots,\n} from './runtime/runtime.js';\n\nexport {\n input_int,\n input_float,\n input_bool,\n input_string,\n input_text_area,\n input_source,\n input_timeframe,\n input_session,\n input_symbol,\n input_time,\n} from './runtime/inputs.js';\nexport { isInputActive } from './runtime/input-active.js';\n\nexport type {\n OakScriptContext,\n ChartAdapter,\n InputAdapter,\n SeriesHandle,\n SeriesOptions,\n InputConfig,\n InputCondition,\n InputOptions,\n OhlcvData,\n PlotConfig,\n HLineConfig,\n FillConfig,\n ArrowConfig,\n CandleConfig,\n ShapeConfig,\n BarColorConfig,\n} from './runtime/types.js';\n\n// Strategy types and constants (the script API forwards strategy.* calls to a host engine)\nexport {\n STRATEGY_CONSTANTS,\n STRATEGY_DEFAULTS,\n STRATEGY_NUMBER_VARIABLES,\n STRATEGY_TEXT_VARIABLES,\n} from './strategy/index.js';\nexport type * from './strategy/index.js';\n\nexport { LightweightChartsAdapter } from './runtime/adapters/LightweightChartsAdapter.js';\nexport type { LightweightSeriesDefinitions } from './runtime/adapters/LightweightChartsAdapter.js';\nexport { SimpleInputAdapter } from './runtime/adapters/SimpleInputAdapter.js';\n\n// Version\nexport const VERSION = '0.
|
|
4
|
+
"sourcesContent": ["/**\n * OakScriptJS - Simplified PineScript-like library for JavaScript\n *\n * This library provides Series-based lazy evaluation and technical analysis functions\n * for building trading indicators. The PineScript-style script API is in `oakscriptjs/script`.\n *\n * Key features:\n * - Series class for lazy evaluation and method chaining\n * - Core TA functions (array-based)\n * - TA-Series wrappers (Series-based)\n *\n * @packageDocumentation\n */\n\n// Export all types\nexport * from './types/index.js';\nexport * from './types/metadata.js';\n\n// Export core namespaces (array-based functions)\nimport * as taCore from './ta/index.js';\nimport * as math from './math/index.js';\nimport * as array from './array/index.js';\nimport * as map from './map/index.js';\nimport * as str from './str/index.js';\nimport * as color from './color/index.js';\nimport * as time from './time/index.js';\nimport * as timeframe from './timeframe/index.js';\nimport * as matrix from './matrix/index.js';\nimport * as line from './line/index.js';\nimport * as box from './box/index.js';\nimport * as label from './label/index.js';\nimport * as linefill from './linefill/index.js';\nimport * as chartPoint from './chartpoint/index.js';\nimport * as polyline from './polyline/index.js';\nimport * as table from './table/index.js';\nimport * as text from './text/index.js';\nimport * as compare from './compare/index.js';\nimport * as callsite from './callsite/index.js';\n\nexport { taCore, math, array, map, str, color, time, timeframe, matrix, line, box, label, linefill, chartPoint, polyline, table, text, compare, callsite };\n\n// ta.* one bar at a time (step / commit), for incremental calculations (#196)\nexport { taStep, type BarStep } from './ta/step.js';\n\n// Renderable drawings (IndicatorResult labels, lines, boxes, linefills, polylines, tables) and future bar times\nexport { drawingOutputs, type DrawingOutputs } from './drawing/output.js';\nexport { barInterval, barTime } from './drawing/bar-time.js';\n\n// Drawing registry limits (PineScript indicator(max_lines_count / max_labels_count / max_boxes_count / max_polylines_count)),\n// and the drawing checkpoint of a port with its own bar loop (live updates of the forming bar, #203)\nexport {\n resetDrawings,\n setDrawingLimits,\n setDrawingBar,\n holdDrawing,\n releaseDrawing,\n varDrawing,\n createdDrawingKinds,\n saveDrawingCheckpoint,\n restoreDrawingCheckpoint,\n type DrawingCheckpoint,\n type DrawingKind,\n type DrawingLimits,\n type DrawingVariable,\n} from './drawing/registry.js';\n\n// The session of a chart context without a script run: time(tf, session, timezone), time_close(...), time_tradingday,\n// session.* flags, request.security periods with the session and holidays, and bars after the last bar on the trading\n// calendar\nexport {\n chartSessions,\n sessionPeriods,\n periodTime,\n periodClose,\n tradingDayTime,\n chartSessionFlags,\n resampleSession,\n barTimeAfter,\n barsUntil,\n type SessionContext,\n type ChartSessions,\n type SessionPeriods,\n type SessionResample,\n} from './session/context.js';\nexport { TradingCalendar, type SessionSpec } from './session/calendar.js';\nexport { SessionBars, sessionFlags, type SessionFlags } from './session/bars.js';\n\n// Same-symbol request.security on a higher timeframe (completion and lookahead rules) and ticker.heikinashi\nexport { resample, periodsOf, afterCompletion, mapToChart, heikinAshi, type Resampled } from './security/resample.js';\n// request.security of another symbol: which bar of the other symbol each chart bar shows (#179)\nexport {\n securityOther,\n securityOtherValues,\n securityLowerTf,\n MAX_INTRABARS,\n type OtherSymbolChart,\n type OtherSymbolOptions,\n type SymbolCalendar,\n} from './security/other.js';\n\n// Export Series class (self-contained, no context)\nexport { Series, BarData } from './runtime/series.js';\nexport type { SeriesExtractor } from './runtime/series.js';\n\n// Export TA-Series namespace (Series-based wrappers)\nimport * as ta from './ta-series.js';\nexport { ta };\n\n// Export metadata types for indicator return values\nexport type {\n PlotOptions,\n HLineOptions,\n FillOptions,\n InputMetadata,\n PlotMetadata,\n IndicatorMetadata,\n TimeValue,\n PlotData,\n HLineData,\n FillData,\n FillGradient,\n IndicatorResult,\n IndicatorFactory,\n PlotStyle,\n LineStyle,\n PlotDisplay,\n InputType\n} from './types/metadata.js';\n\n// Re-export commonly used functions for convenience\nexport { sma, ema, rsi, macd, bb, stdev, crossover, crossunder, change, tr, atr, cum, vwap } from './ta-series.js';\nexport { abs, ceil, floor, round, max, min, avg, sum, sqrt, pow, exp, log, sin, cos, tan } from './math/index.js';\nexport { rgb, from_hex as color_from_hex, new_color } from './color/index.js';\n\n// Export chart data utilities\nexport { ohlcFromBars, getClose, getHigh, getLow, getOpen, getSource, getSourceSeries, at, div } from './utils/index.js';\nexport { setSourceResolver, externalSource, BUILTIN_SOURCES, type SourceResolver } from './utils/source-resolver.js';\n\n// Export libraries (ZigZag, etc.)\nexport * from './lib/index.js';\n\n// Export helper functions for generated indicators (PineScript compatibility)\nexport {isNA as na, nz, fixnan} from './utils/index.js';\n\n// Export indicator infrastructure\nexport {\n indicator,\n type IndicatorMetadataConfig,\n type InputDefinition,\n type IndicatorContext,\n type IndicatorInstance,\n type IndicatorConstructor,\n} from './indicator.js';\n\nexport {\n input,\n type InputValue,\n type IntInputOptions,\n type FloatInputOptions,\n type SourceInputOptions,\n type BoolInputOptions,\n type StringInputOptions,\n type TimeInputOptions,\n type SourceType,\n} from './input.js';\n\nexport {\n plot as plotHelper,\n createPlot,\n type Time,\n type TimeValuePair,\n type PlotOptions as PlotHelperOptions,\n type PlotResult,\n} from './plot.js';\n\n// Runtime exports - global context runtime (setContext, plot, hline) drawing through a ChartAdapter\nexport {\n setContext,\n clearContext,\n getContext,\n registerCalculate,\n recalculate,\n plot,\n hline,\n clearPlots,\n} from './runtime/runtime.js';\n\nexport {\n input_int,\n input_float,\n input_bool,\n input_string,\n input_text_area,\n input_source,\n input_timeframe,\n input_session,\n input_symbol,\n input_time,\n} from './runtime/inputs.js';\nexport { isInputActive } from './runtime/input-active.js';\n\nexport type {\n OakScriptContext,\n ChartAdapter,\n InputAdapter,\n SeriesHandle,\n SeriesOptions,\n InputConfig,\n InputCondition,\n InputOptions,\n OhlcvData,\n PlotConfig,\n HLineConfig,\n FillConfig,\n ArrowConfig,\n CandleConfig,\n ShapeConfig,\n BarColorConfig,\n} from './runtime/types.js';\n\n// Strategy types and constants (the script API forwards strategy.* calls to a host engine)\nexport {\n STRATEGY_CONSTANTS,\n STRATEGY_DEFAULTS,\n STRATEGY_NUMBER_VARIABLES,\n STRATEGY_TEXT_VARIABLES,\n} from './strategy/index.js';\nexport type * from './strategy/index.js';\n\nexport { LightweightChartsAdapter } from './runtime/adapters/LightweightChartsAdapter.js';\nexport type { LightweightSeriesDefinitions } from './runtime/adapters/LightweightChartsAdapter.js';\nexport { SimpleInputAdapter } from './runtime/adapters/SimpleInputAdapter.js';\n\n// Version\nexport const VERSION = '0.20.0';\n\n/**\n * Library information\n */\nexport const info = {\n name: 'OakScriptJS',\n version: VERSION,\n description: 'Simplified PineScript-like library - Series + TA functions',\n features: {\n series: 'Lazy evaluation with Series class',\n ta: 'Technical analysis functions (Series and array-based)',\n script: 'PineScript-style script API (oakscriptjs/script): indicator, strategy, inputs, plots, request.security',\n runtime: 'Global context runtime drawing through a ChartAdapter',\n indicator: 'Indicator function with automatic pane management'\n },\n namespaces: {\n core: ['ta', 'math', 'array', 'map', 'str', 'color', 'time', 'timeframe', 'matrix'],\n drawing: ['line', 'box', 'label', 'linefill', 'chartPoint', 'polyline', 'table', 'text'],\n runtime: ['setContext', 'plot', 'hline', 'input_*'],\n indicator: ['indicator', 'input', 'plotHelper', 'createPlot']\n }\n};\n\n// PineScript compatibility stubs - functions that have no runtime effect\n// These are no-ops so that PineScript-style code runs without modification\n\n/**\n * alertcondition() - Stub for PineScript alert configuration\n * In PineScript, this registers an alert condition. In oakscriptjs, it's a no-op\n * since alert configuration is handled by the host application.\n */\nexport function alertcondition(_condition: unknown, _title?: string, _message?: string): void {\n // No-op: Alert conditions are handled by the host application\n}\n"],
|
|
5
5
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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mBAAsG;AACtG,6BAAwF;AAGxF,0BAAc,2BA3Id;AA8IA,IAAAA,gBAAqC;AAGrC,uBAOO;AAEP,mBAUO;AAEP,kBAOO;AAGP,qBASO;AAEP,oBAWO;AACP,0BAA8B;AAsB9B,sBAKO;AAGP,sCAAyC;AAEzC,gCAAmC;AAG5B,MAAM,UAAU;AAKhB,MAAM,OAAO;AAAA,EAClB,MAAM;AAAA,EACN,SAAS;AAAA,EACT,aAAa;AAAA,EACb,UAAU;AAAA,IACR,QAAQ;AAAA,IACR,IAAI;AAAA,IACJ,QAAQ;AAAA,IACR,SAAS;AAAA,IACT,WAAW;AAAA,EACb;AAAA,EACA,YAAY;AAAA,IACV,MAAM,CAAC,MAAM,QAAQ,SAAS,OAAO,OAAO,SAAS,QAAQ,aAAa,QAAQ;AAAA,IAClF,SAAS,CAAC,QAAQ,OAAO,SAAS,YAAY,cAAc,YAAY,SAAS,MAAM;AAAA,IACvF,SAAS,CAAC,cAAc,QAAQ,SAAS,SAAS;AAAA,IAClD,WAAW,CAAC,aAAa,SAAS,cAAc,YAAY;AAAA,EAC9D;AACF;AAUO,SAAS,eAAe,YAAqB,QAAiB,UAAyB;AAE9F;",
|
|
6
6
|
"names": ["import_utils"]
|
|
7
7
|
}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* @version 6
|
|
11
11
|
*/
|
|
12
12
|
import type { ChartPoint, Label, color } from '../types/index.js';
|
|
13
|
-
type LabelXloc = 'bar_index' | 'bar_time';
|
|
13
|
+
type LabelXloc = 'bar_index' | 'bar_time' | 'pane';
|
|
14
14
|
type LabelYloc = 'price' | 'abovebar' | 'belowbar';
|
|
15
15
|
type LabelStyle = NonNullable<Label['style']>;
|
|
16
16
|
/**
|
|
@@ -149,7 +149,7 @@ export declare function set_xy(id: Label, x: number, y: number): Label;
|
|
|
149
149
|
* label.set_xloc(label, 1609459200000, 'bar_time'); // Change to timestamp
|
|
150
150
|
* ```
|
|
151
151
|
*/
|
|
152
|
-
export declare function set_xloc(id: Label, x: number, xloc: 'bar_index' | 'bar_time'): Label;
|
|
152
|
+
export declare function set_xloc(id: Label, x: number, xloc: 'bar_index' | 'bar_time' | 'pane'): Label;
|
|
153
153
|
/**
|
|
154
154
|
* Sets the y-location mode of the label (PineScript `label.set_yloc(id, yloc)`): `price` uses the
|
|
155
155
|
* label's y, `abovebar` / `belowbar` place it above / below the bar.
|