@hoox-sh/pynets 0.2.0 → 0.3.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.
@@ -32,6 +32,7 @@ import {
32
32
  mathMin,
33
33
  mathPow,
34
34
  mathRound,
35
+ mathRoundToMintick,
35
36
  mathSign,
36
37
  mathSin,
37
38
  mathSqrt,
@@ -58,7 +59,8 @@ import { LogBook, formatLogParts } from "../log.ts";
58
59
  import { resolveCurrencyRate } from "../request.ts";
59
60
  import { TaEngine } from "../ta.ts";
60
61
  import { utcPartsFromMs, timestamp, weekOfYear, timeTradingDay, type UtcParts } from "../time.ts";
61
- import { timeframeInSeconds } from "../timeframe.ts";
62
+ import { TickerId } from "../ticker.ts";
63
+ import { timeframeInSeconds, timeframePeriodChanged } from "../timeframe.ts";
62
64
  import { compileArray, compileMap, compileMatrix } from "./collections.ts";
63
65
  import { createCompileDraw } from "./draw.ts";
64
66
  import {
@@ -94,6 +96,11 @@ export function createCompileHelpers(opts?: CompileHelperOpts) {
94
96
  const ta = new TaEngine();
95
97
  const inputs = opts?.inputs;
96
98
  const book = new LogBook();
99
+ // Python `timeframe_in_seconds` defaults None / "" to "D" (daily, 86400)
100
+ // before parsing — builtins/timeframe.py:189-190. The shared helper in
101
+ // timeframe.ts maps na / empty → null, so compile wraps it here to match.
102
+ const timeframeInSecondsOrDaily = (p: string | null): number | null =>
103
+ timeframeInSeconds(p == null || p === "" ? "D" : p);
97
104
  return {
98
105
  na: NA_FN,
99
106
  nz,
@@ -174,7 +181,11 @@ export function createCompileHelpers(opts?: CompileHelperOpts) {
174
181
  timestamp,
175
182
  weekOfYear,
176
183
  timeTradingDay,
177
- timeframeInSeconds,
184
+ timeframeInSeconds: timeframeInSecondsOrDaily,
185
+ timeframeChange,
186
+ timeClose,
187
+ roundToMintick,
188
+ syminfoPrefix,
178
189
  strLength,
179
190
  strContains,
180
191
  strStartsWith,
@@ -295,3 +306,52 @@ function calendarDayofweek(t: unknown): number | null {
295
306
  function logBar(bar: unknown): number {
296
307
  return typeof bar === "number" && Number.isFinite(bar) ? bar : 0;
297
308
  }
309
+
310
+ /** `timeframe.change`: bar 0 is a new period; empty / unknown tf → false. */
311
+ function timeframeChange(tf: unknown, curr: unknown, prev: unknown, barIndex: unknown): number {
312
+ const s =
313
+ typeof tf === "string"
314
+ ? tf
315
+ : typeof tf === "number" && Number.isFinite(tf)
316
+ ? String(tf)
317
+ : null;
318
+ if (s == null || s.trim() === "") return 0;
319
+ if (typeof curr !== "number" || !Number.isFinite(curr)) return 0;
320
+ const idx = typeof barIndex === "number" && Number.isFinite(barIndex) ? barIndex : null;
321
+ return timeframePeriodChanged(curr, prev, s, idx) ? 1 : 0;
322
+ }
323
+
324
+ /**
325
+ * Next bar open, last bar `time + 86400000`. `0` next-open counts as missing
326
+ * (interpret beginBar). Compile has no per-bar `time_close` column.
327
+ */
328
+ function timeClose(barIdx: unknown, timeArr: unknown): number {
329
+ const i = typeof barIdx === "number" && Number.isFinite(barIdx) ? Math.trunc(barIdx) : 0;
330
+ const arr = Array.isArray(timeArr) ? (timeArr as Array<number | null | undefined>) : [];
331
+ const t = arr[i];
332
+ const tNum = typeof t === "number" && Number.isFinite(t) ? t : 0;
333
+ if (i + 1 < arr.length) {
334
+ const next = arr[i + 1] ?? 0;
335
+ return next !== 0 ? next : tNum;
336
+ }
337
+ return Math.trunc(tNum) + 86_400_000;
338
+ }
339
+
340
+ function roundToMintick(x: unknown): number | null {
341
+ return mathRoundToMintick(naNum(x), 0.01);
342
+ }
343
+
344
+ /** Python `split_symbol` / `extract_prefix`: text before the first `:`, else `""`. */
345
+ function extractPrefix(symbol: string): string {
346
+ const s = symbol.trim();
347
+ const i = s.indexOf(":");
348
+ return i < 0 ? "" : s.slice(0, i);
349
+ }
350
+
351
+ function syminfoPrefix(tickerid?: unknown): string {
352
+ if (arguments.length === 0 || tickerid === undefined) return extractPrefix("SYMBOL");
353
+ if (tickerid instanceof TickerId) return extractPrefix(tickerid.symbol);
354
+ if (typeof tickerid === "string") return extractPrefix(tickerid);
355
+ if (typeof tickerid === "number" && Number.isFinite(tickerid)) return extractPrefix(String(tickerid));
356
+ return "";
357
+ }
@@ -7,8 +7,10 @@
7
7
  */
8
8
  import {
9
9
  StrategyBook,
10
+ type BarOhlc,
10
11
  type BrokerSettings,
11
12
  type PlaceEntryOpts,
13
+ type PlaceExitOpts,
12
14
  type StrategyDirection,
13
15
  type StrategyEvent,
14
16
  type StrategySummary,
@@ -36,16 +38,68 @@ function str(v: unknown, fallback = ""): string {
36
38
  return String(v);
37
39
  }
38
40
 
41
+ function optNum(v: unknown): number | null {
42
+ if (typeof v === "number" && Number.isFinite(v)) return v;
43
+ return null;
44
+ }
45
+
46
+ function asExitOpts(v: unknown): PlaceExitOpts {
47
+ if (v == null || typeof v !== "object" || Array.isArray(v)) return {};
48
+ const rec = v as Record<string, unknown>;
49
+ return {
50
+ from_entry: rec.from_entry == null || rec.from_entry === "" ? null : String(rec.from_entry),
51
+ qty: optNum(rec.qty),
52
+ qty_percent: optNum(rec.qty_percent),
53
+ profit: optNum(rec.profit),
54
+ limit: optNum(rec.limit),
55
+ loss: optNum(rec.loss),
56
+ stop: optNum(rec.stop),
57
+ trail_price: optNum(rec.trail_price),
58
+ trail_points: optNum(rec.trail_points),
59
+ trail_offset: optNum(rec.trail_offset),
60
+ comment: rec.comment == null ? undefined : String(rec.comment),
61
+ };
62
+ }
63
+
39
64
  export class CompileStrategy {
40
65
  readonly book: StrategyBook;
41
66
  private bar = 0;
42
67
  private mark = 0;
43
68
  private time = 0;
69
+ private ohlc: BarOhlc = {};
44
70
 
45
71
  constructor(settings?: BrokerSettings) {
46
72
  this.book = new StrategyBook(settings);
47
73
  }
48
74
 
75
+ /** Apply `strategy(...)` declaration kwargs (every bar, same as interpret). */
76
+ configure(settings?: unknown): void {
77
+ if (settings == null || typeof settings !== "object" || Array.isArray(settings)) return;
78
+ const rec = settings as Record<string, unknown>;
79
+ const broker: BrokerSettings = {};
80
+ const commission = optNum(rec.commission);
81
+ if (commission != null) broker.commission = commission;
82
+ const slippage = optNum(rec.slippage);
83
+ if (slippage != null) broker.slippage = slippage;
84
+ if (rec.pyramiding !== undefined) {
85
+ const pyr = optNum(rec.pyramiding);
86
+ broker.pyramiding = pyr == null ? undefined : Math.trunc(pyr);
87
+ }
88
+ if (typeof rec.avg_price_model === "string") broker.avg_price_model = rec.avg_price_model;
89
+ const leverage = optNum(rec.leverage);
90
+ if (leverage != null) broker.leverage = leverage;
91
+ const ml = optNum(rec.margin_long);
92
+ if (ml != null) broker.margin_long = ml;
93
+ const ms = optNum(rec.margin_short);
94
+ if (ms != null) broker.margin_short = ms;
95
+ if (typeof rec.default_qty_type === "string") broker.default_qty_type = rec.default_qty_type;
96
+ const dqv = optNum(rec.default_qty_value);
97
+ if (dqv != null) broker.default_qty_value = dqv;
98
+ if (Object.keys(broker).length) this.book.configure(broker);
99
+ const capital = optNum(rec.initial_capital);
100
+ if (capital != null) this.book.initialCapital = capital;
101
+ }
102
+
49
103
  beginBar(
50
104
  bar: unknown,
51
105
  open: unknown,
@@ -63,14 +117,16 @@ export class CompileStrategy {
63
117
  low: num(low, this.mark),
64
118
  close: this.mark,
65
119
  };
120
+ this.ohlc = ohlc;
66
121
  this.book.processPending(this.bar, ohlc);
67
122
  this.book.markOpenTrades(ohlc.high, ohlc.low, ohlc.close);
68
123
  }
69
124
 
70
125
  entry(id?: unknown, direction?: unknown, qty?: unknown, opts?: PlaceEntryOpts): void {
71
- const q = qty == null ? 1 : num(qty, 1);
126
+ const fillPrice = opts?.price ?? this.mark;
127
+ const q = qty == null ? this.book.resolveDefaultQty(fillPrice) : num(qty, 1);
72
128
  this.book.placeEntry(this.bar, str(id, "entry"), asDir(direction), q, {
73
- price: opts?.price ?? this.mark,
129
+ price: fillPrice,
74
130
  time: opts?.time ?? this.time,
75
131
  limit: opts?.limit,
76
132
  stop: opts?.stop,
@@ -80,8 +136,11 @@ export class CompileStrategy {
80
136
  });
81
137
  }
82
138
 
83
- close(id?: unknown, _qty?: unknown): void {
84
- this.book.fillClose(this.bar, str(id, ""), this.mark, { time: this.time });
139
+ close(id?: unknown, qty?: unknown): void {
140
+ this.book.fillClose(this.bar, str(id, ""), this.mark, {
141
+ time: this.time,
142
+ qty: optNum(qty),
143
+ });
85
144
  }
86
145
 
87
146
  close_all(_comment?: unknown): void {
@@ -100,8 +159,14 @@ export class CompileStrategy {
100
159
  this.book.cancelAll(this.bar);
101
160
  }
102
161
 
103
- exit(from_entry?: unknown, _qty?: unknown): void {
104
- this.book.fillClose(this.bar, str(from_entry, ""), this.mark, { time: this.time });
162
+ exit(id?: unknown, opts?: unknown): void {
163
+ const parsed = asExitOpts(opts);
164
+ this.book.placeExit(this.bar, str(id, "exit"), {
165
+ ...parsed,
166
+ price: this.mark,
167
+ time: this.time,
168
+ ohlc: this.ohlc,
169
+ });
105
170
  }
106
171
 
107
172
  position_size(): number {
@@ -131,6 +196,22 @@ export class CompileStrategy {
131
196
  return this.book.closedtrades;
132
197
  }
133
198
 
199
+ leverage(): number {
200
+ return this.book.leverage;
201
+ }
202
+
203
+ margin_liquidation_price(): number | null {
204
+ return this.book.marginLiquidationPrice();
205
+ }
206
+
207
+ position_avg_price(): number | null {
208
+ return this.book.position.avgPrice;
209
+ }
210
+
211
+ initial_capital(): number {
212
+ return this.book.initialCapital;
213
+ }
214
+
134
215
  risk_allow_entry_in(value?: unknown): void {
135
216
  this.book.riskAllowEntryIn(value);
136
217
  }
@@ -58,6 +58,8 @@ export interface EmitCtx {
58
58
  usesStrategy: boolean;
59
59
  nextSite: number;
60
60
  errors: string[];
61
+ /** `once`-structure fired flags, declared in the bar-loop frame. */
62
+ onceFlags: string[];
61
63
  /** Pine UDF name currently being emitted (null at script scope). */
62
64
  currentFunc: string | null;
63
65
  /** Formal names of the current UDF. */
@@ -69,6 +69,37 @@ function cellKey(column: unknown, row: unknown): string | undefined {
69
69
  return `${column},${row}`;
70
70
  }
71
71
 
72
+ function asIndex(value: unknown): number | null {
73
+ if (!isFiniteNumber(value)) return null;
74
+ return Math.trunc(value);
75
+ }
76
+
77
+ function parseCellKey(key: string): { col: number; row: number } | undefined {
78
+ const comma = key.indexOf(",");
79
+ if (comma < 0) return undefined;
80
+ const col = Number(key.slice(0, comma));
81
+ const row = Number(key.slice(comma + 1));
82
+ if (!isFiniteNumber(col) || !isFiniteNumber(row)) return undefined;
83
+ return { col, row };
84
+ }
85
+
86
+ function cloneExtra(extra?: Record<string, unknown>): Record<string, unknown> | undefined {
87
+ if (extra == null) return undefined;
88
+ const out: Record<string, unknown> = { ...extra };
89
+ if (out.cells != null && typeof out.cells === "object" && !Array.isArray(out.cells)) {
90
+ const cells: Record<string, unknown> = {};
91
+ for (const [k, v] of Object.entries(out.cells as Record<string, unknown>)) {
92
+ cells[k] = v != null && typeof v === "object" && !Array.isArray(v) ? { ...(v as Record<string, unknown>) } : v;
93
+ }
94
+ out.cells = cells;
95
+ }
96
+ if (Array.isArray(out.points)) {
97
+ out.points = out.points.map((p) => (p != null && typeof p === "object" ? { ...(p as Record<string, unknown>) } : p));
98
+ }
99
+ if (Array.isArray(out.merged)) out.merged = out.merged.slice();
100
+ return out;
101
+ }
102
+
72
103
  export class DrawingBook {
73
104
  readonly items: DrawingEvent[] = [];
74
105
  private readonly byId = new Map<number, DrawingEvent>();
@@ -110,24 +141,33 @@ export class DrawingBook {
110
141
  return this.items.filter((e) => e.kind === kind && !e.deleted);
111
142
  }
112
143
 
144
+ /** Insertion-order ids of non-deleted objects of *kind* (Python `*.all`). */
145
+ allIds(kind: DrawingKind): number[] {
146
+ const ids: number[] = [];
147
+ for (const [id, ev] of this.byId) {
148
+ if (ev.kind === kind && !ev.deleted) ids.push(id);
149
+ }
150
+ return ids;
151
+ }
152
+
113
153
  lineNew(bar: number, extra?: Record<string, unknown>): number {
114
154
  return this.push("line", bar, { extra, cap: this.maxLines });
115
155
  }
116
156
 
117
- labelNew(bar: number, text?: string): number {
118
- return this.push("label", bar, { text, cap: this.maxLabels });
157
+ labelNew(bar: number, text?: string, extra?: Record<string, unknown>): number {
158
+ return this.push("label", bar, { text, extra, cap: this.maxLabels });
119
159
  }
120
160
 
121
- boxNew(bar: number): number {
122
- return this.push("box", bar, { cap: this.maxBoxes });
161
+ boxNew(bar: number, extra?: Record<string, unknown>): number {
162
+ return this.push("box", bar, { extra, cap: this.maxBoxes });
123
163
  }
124
164
 
125
- tableNew(bar: number): number {
126
- return this.push("table", bar);
165
+ tableNew(bar: number, extra?: Record<string, unknown>): number {
166
+ return this.push("table", bar, { extra });
127
167
  }
128
168
 
129
- polylineNew(bar: number): number {
130
- return this.push("polyline", bar, { cap: this.maxPolylines });
169
+ polylineNew(bar: number, extra?: Record<string, unknown>): number {
170
+ return this.push("polyline", bar, { extra, cap: this.maxPolylines });
131
171
  }
132
172
 
133
173
  linefillNew(bar: number, extraOrId1?: Record<string, unknown> | number, id2?: number): number {
@@ -364,6 +404,326 @@ export class DrawingBook {
364
404
  setAny(extra, "color", color);
365
405
  }
366
406
 
407
+ lineSetX1(id: number, x1: unknown): void {
408
+ this.setKindNum(id, "line", "x1", x1);
409
+ }
410
+
411
+ lineSetY1(id: number, y1: unknown): void {
412
+ this.setKindNum(id, "line", "y1", y1);
413
+ }
414
+
415
+ lineSetX2(id: number, x2: unknown): void {
416
+ this.setKindNum(id, "line", "x2", x2);
417
+ }
418
+
419
+ lineSetY2(id: number, y2: unknown): void {
420
+ this.setKindNum(id, "line", "y2", y2);
421
+ }
422
+
423
+ lineSetXloc(id: number, xloc: unknown): void {
424
+ this.setKindAny(id, "line", "xloc", xloc);
425
+ }
426
+
427
+ boxGetLeft(id: number): number | null {
428
+ return this.kindNum(id, "box", "left");
429
+ }
430
+
431
+ boxGetRight(id: number): number | null {
432
+ return this.kindNum(id, "box", "right");
433
+ }
434
+
435
+ boxGetTop(id: number): number | null {
436
+ return this.kindNum(id, "box", "top");
437
+ }
438
+
439
+ boxGetBottom(id: number): number | null {
440
+ return this.kindNum(id, "box", "bottom");
441
+ }
442
+
443
+ boxSetLeft(id: number, left: unknown): void {
444
+ this.setKindNum(id, "box", "left", left);
445
+ }
446
+
447
+ boxSetRight(id: number, right: unknown): void {
448
+ this.setKindNum(id, "box", "right", right);
449
+ }
450
+
451
+ boxSetTop(id: number, top: unknown): void {
452
+ this.setKindNum(id, "box", "top", top);
453
+ }
454
+
455
+ boxSetBottom(id: number, bottom: unknown): void {
456
+ this.setKindNum(id, "box", "bottom", bottom);
457
+ }
458
+
459
+ boxSetLeftTop(id: number, left: unknown, top: unknown): void {
460
+ const extra = this.extraOf(id, "box");
461
+ if (!extra) return;
462
+ setNum(extra, "left", left);
463
+ setNum(extra, "top", top);
464
+ }
465
+
466
+ boxSetRightBottom(id: number, right: unknown, bottom: unknown): void {
467
+ const extra = this.extraOf(id, "box");
468
+ if (!extra) return;
469
+ setNum(extra, "right", right);
470
+ setNum(extra, "bottom", bottom);
471
+ }
472
+
473
+ boxSetBorderWidth(id: number, width: unknown): void {
474
+ this.setKindNum(id, "box", "border_width", width);
475
+ }
476
+
477
+ boxSetBorderStyle(id: number, style: unknown): void {
478
+ this.setKindAny(id, "box", "border_style", style);
479
+ }
480
+
481
+ boxSetXloc(id: number, xloc: unknown): void {
482
+ this.setKindAny(id, "box", "xloc", xloc);
483
+ }
484
+
485
+ boxSetClosed(id: number, closed: unknown): void {
486
+ this.setKindAny(id, "box", "closed", closed);
487
+ }
488
+
489
+ boxSetTextColor(id: number, color: unknown): void {
490
+ this.setKindAny(id, "box", "text_color", color);
491
+ }
492
+
493
+ boxSetTextFontFamily(id: number, font: unknown): void {
494
+ this.setKindAny(id, "box", "text_font_family", font);
495
+ }
496
+
497
+ boxSetTextHalign(id: number, halign: unknown): void {
498
+ this.setKindAny(id, "box", "text_halign", halign);
499
+ }
500
+
501
+ boxSetTextValign(id: number, valign: unknown): void {
502
+ this.setKindAny(id, "box", "text_valign", valign);
503
+ }
504
+
505
+ boxSetTextSize(id: number, size: unknown): void {
506
+ this.setKindAny(id, "box", "text_size", size);
507
+ }
508
+
509
+ boxSetTextFormatting(id: number, formatting: unknown): void {
510
+ this.setKindAny(id, "box", "text_formatting", formatting);
511
+ }
512
+
513
+ boxSetTextWrap(id: number, wrap: unknown): void {
514
+ this.setKindAny(id, "box", "text_wrap", wrap);
515
+ }
516
+
517
+ labelSetX(id: number, x: unknown): void {
518
+ this.setKindNum(id, "label", "x", x);
519
+ }
520
+
521
+ labelSetY(id: number, y: unknown): void {
522
+ this.setKindNum(id, "label", "y", y);
523
+ }
524
+
525
+ labelSetTextcolor(id: number, color: unknown): void {
526
+ this.setKindAny(id, "label", "textcolor", color);
527
+ }
528
+
529
+ labelSetTextFontFamily(id: number, font: unknown): void {
530
+ this.setKindAny(id, "label", "text_font_family", font);
531
+ }
532
+
533
+ labelSetTextHalign(id: number, halign: unknown): void {
534
+ this.setKindAny(id, "label", "text_halign", halign);
535
+ }
536
+
537
+ labelSetTextValign(id: number, valign: unknown): void {
538
+ this.setKindAny(id, "label", "text_valign", valign);
539
+ }
540
+
541
+ labelSetTextSize(id: number, size: unknown): void {
542
+ this.setKindAny(id, "label", "text_size", size);
543
+ }
544
+
545
+ labelSetTextFormatting(id: number, formatting: unknown): void {
546
+ this.setKindAny(id, "label", "text_formatting", formatting);
547
+ }
548
+
549
+ labelSetBorderColor(id: number, color: unknown): void {
550
+ this.setKindAny(id, "label", "border_color", color);
551
+ }
552
+
553
+ labelSetBorderWidth(id: number, width: unknown): void {
554
+ this.setKindNum(id, "label", "border_width", width);
555
+ }
556
+
557
+ labelSetBorderStyle(id: number, style: unknown): void {
558
+ this.setKindAny(id, "label", "border_style", style);
559
+ }
560
+
561
+ labelSetXloc(id: number, xloc: unknown): void {
562
+ this.setKindAny(id, "label", "xloc", xloc);
563
+ }
564
+
565
+ labelSetYloc(id: number, yloc: unknown): void {
566
+ this.setKindAny(id, "label", "yloc", yloc);
567
+ }
568
+
569
+ tableCellGetText(id: number, column: unknown, row: unknown): string | null {
570
+ const rec = this.cellRec(id, column, row);
571
+ if (!rec) return null;
572
+ if (rec.text === undefined) return null;
573
+ return rec.text == null ? "" : String(rec.text);
574
+ }
575
+
576
+ tableCellSetField(id: number, column: unknown, row: unknown, field: string, value: unknown): void {
577
+ this.upsertCell(id, column, row, undefined, false);
578
+ const rec = this.cellRec(id, column, row);
579
+ if (!rec) return;
580
+ rec[field] = value;
581
+ }
582
+
583
+ tableSetBgcolor(id: number, color: unknown): void {
584
+ this.setKindAny(id, "table", "bgcolor", color);
585
+ }
586
+
587
+ tableSetBorderColor(id: number, color: unknown): void {
588
+ this.setKindAny(id, "table", "border_color", color);
589
+ }
590
+
591
+ tableSetBorderWidth(id: number, width: unknown): void {
592
+ this.setKindNum(id, "table", "border_width", width);
593
+ }
594
+
595
+ tableSetFrameColor(id: number, color: unknown): void {
596
+ this.setKindAny(id, "table", "frame_color", color);
597
+ }
598
+
599
+ tableSetFrameWidth(id: number, width: unknown): void {
600
+ this.setKindNum(id, "table", "frame_width", width);
601
+ }
602
+
603
+ tableClear(
604
+ id: number,
605
+ startRow?: unknown,
606
+ startCol?: unknown,
607
+ endRow?: unknown,
608
+ endCol?: unknown,
609
+ ): void {
610
+ const extra = this.extraOf(id, "table");
611
+ if (!extra) return;
612
+ if (startRow === undefined) {
613
+ extra.cells = {};
614
+ return;
615
+ }
616
+ const r0 = asIndex(startRow);
617
+ const c0 = asIndex(startCol);
618
+ const r1 = asIndex(endRow);
619
+ const c1 = asIndex(endCol);
620
+ if (r0 == null || c0 == null || r1 == null || c1 == null) return;
621
+ const prev = extra.cells;
622
+ if (prev == null || typeof prev !== "object" || Array.isArray(prev)) return;
623
+ const cells = prev as Record<string, unknown>;
624
+ for (const key of Object.keys(cells)) {
625
+ const parsed = parseCellKey(key);
626
+ if (parsed == null) continue;
627
+ if (r0 <= parsed.row && parsed.row <= r1 && c0 <= parsed.col && parsed.col <= c1) {
628
+ delete cells[key];
629
+ }
630
+ }
631
+ }
632
+
633
+ tableMergeCells(
634
+ id: number,
635
+ startRow: unknown,
636
+ startCol: unknown,
637
+ endRow: unknown,
638
+ endCol: unknown,
639
+ ): void {
640
+ const extra = this.extraOf(id, "table");
641
+ if (!extra) return;
642
+ const r0 = asIndex(startRow);
643
+ const c0 = asIndex(startCol);
644
+ const r1 = asIndex(endRow);
645
+ const c1 = asIndex(endCol);
646
+ if (r0 == null || c0 == null || r1 == null || c1 == null) return;
647
+ if (r1 < r0 || c1 < c0) return;
648
+ const prev = extra.merged;
649
+ const merged = Array.isArray(prev) ? prev : [];
650
+ if (merged !== prev) extra.merged = merged;
651
+ merged.push([r0, c0, r1, c1]);
652
+ }
653
+
654
+ polylineGetPoints(id: number): unknown[] {
655
+ const ev = this.byId.get(id);
656
+ if (!ev || ev.kind !== "polyline" || ev.deleted) return [];
657
+ const pts = ev.extra?.points;
658
+ return Array.isArray(pts) ? pts.slice() : [];
659
+ }
660
+
661
+ polylineSetPoints(id: number, points: unknown): void {
662
+ const extra = this.extraOf(id, "polyline");
663
+ if (!extra) return;
664
+ extra.points = Array.isArray(points) ? points.filter((p) => p != null) : [];
665
+ }
666
+
667
+ polylineSetLineColor(id: number, color: unknown): void {
668
+ this.setKindAny(id, "polyline", "color", color);
669
+ }
670
+
671
+ polylineSetLineWidth(id: number, width: unknown): void {
672
+ this.setKindNum(id, "polyline", "width", width);
673
+ }
674
+
675
+ polylineSetLineStyle(id: number, style: unknown): void {
676
+ this.setKindAny(id, "polyline", "style", style);
677
+ }
678
+
679
+ polylineSetFillColor(id: number, color: unknown): void {
680
+ this.setKindAny(id, "polyline", "fill_color", color);
681
+ }
682
+
683
+ polylineSetCurved(id: number, curved: unknown): void {
684
+ this.setKindAny(id, "polyline", "curved", curved);
685
+ }
686
+
687
+ polylineSetForceOverlay(id: number, force: unknown): void {
688
+ this.setKindAny(id, "polyline", "force_overlay", force);
689
+ }
690
+
691
+ polylineSetClosed(id: number, closed: unknown): void {
692
+ this.setKindAny(id, "polyline", "closed", closed);
693
+ }
694
+
695
+ polylineSetXloc(id: number, xloc: unknown): void {
696
+ this.setKindAny(id, "polyline", "xloc", xloc);
697
+ }
698
+
699
+ linefillGetLine1(id: number): number | null {
700
+ return this.kindNum(id, "linefill", "id1");
701
+ }
702
+
703
+ linefillGetLine2(id: number): number | null {
704
+ return this.kindNum(id, "linefill", "id2");
705
+ }
706
+
707
+ tableDelete(id: number): void {
708
+ this.markDeleted(id);
709
+ }
710
+
711
+ polylineDelete(id: number): void {
712
+ this.markDeleted(id);
713
+ }
714
+
715
+ linefillDelete(id: number): void {
716
+ this.markDeleted(id);
717
+ }
718
+
719
+ /** Clone a drawing; missing id → null. New object is not marked deleted. */
720
+ copy(id: number): number | null {
721
+ const ev = this.byId.get(id);
722
+ if (!ev) return null;
723
+ const extra = cloneExtra(ev.extra);
724
+ return this.push(ev.kind, ev.bar, { text: ev.text, extra, cap: this.capFor(ev.kind) });
725
+ }
726
+
367
727
  /** Compact non-deleted items for RuntimeResult.drawings. */
368
728
  exportForApi(): Array<{
369
729
  kind: DrawingKind;
@@ -420,6 +780,43 @@ export class DrawingBook {
420
780
  return id;
421
781
  }
422
782
 
783
+ private capFor(kind: DrawingKind): number | undefined {
784
+ if (kind === "line") return this.maxLines;
785
+ if (kind === "label") return this.maxLabels;
786
+ if (kind === "box") return this.maxBoxes;
787
+ if (kind === "polyline") return this.maxPolylines;
788
+ return undefined;
789
+ }
790
+
791
+ private setKindNum(id: number, kind: DrawingKind, key: string, value: unknown): void {
792
+ const extra = this.extraOf(id, kind);
793
+ if (!extra) return;
794
+ setNum(extra, key, value);
795
+ }
796
+
797
+ private setKindAny(id: number, kind: DrawingKind, key: string, value: unknown): void {
798
+ const extra = this.extraOf(id, kind);
799
+ if (!extra) return;
800
+ setAny(extra, key, value);
801
+ }
802
+
803
+ private kindNum(id: number, kind: DrawingKind, key: string): number | null {
804
+ const ev = this.byId.get(id);
805
+ if (!ev || ev.kind !== kind) return null;
806
+ return this.extraNum(id, key);
807
+ }
808
+
809
+ private cellRec(id: number, column: unknown, row: unknown): Record<string, unknown> | undefined {
810
+ const extra = this.extraOf(id, "table");
811
+ const key = cellKey(column, row);
812
+ if (!extra || key == null) return undefined;
813
+ const prev = extra.cells;
814
+ if (prev == null || typeof prev !== "object" || Array.isArray(prev)) return undefined;
815
+ const cur = (prev as Record<string, unknown>)[key];
816
+ if (cur == null || typeof cur !== "object" || Array.isArray(cur)) return undefined;
817
+ return cur as Record<string, unknown>;
818
+ }
819
+
423
820
  private extraOf(id: number, kind?: DrawingKind): Record<string, unknown> | undefined {
424
821
  const ev = this.byId.get(id);
425
822
  if (!ev) return undefined;