openalgo-script 0.2.0 → 0.4.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.
Files changed (276) hide show
  1. package/CHANGELOG.md +269 -0
  2. package/README.md +65 -31
  3. package/dist/adapters/charts/surfaces.d.ts +17 -0
  4. package/dist/adapters/charts/surfaces.d.ts.map +1 -1
  5. package/dist/adapters/charts/tables.js +82 -0
  6. package/dist/adapters/charts/tables.js.map +1 -1
  7. package/dist/adapters/codemirror/commands.d.ts +14 -0
  8. package/dist/adapters/codemirror/commands.d.ts.map +1 -0
  9. package/dist/adapters/codemirror/commands.js +52 -0
  10. package/dist/adapters/codemirror/commands.js.map +1 -0
  11. package/dist/adapters/codemirror/completion.d.ts +15 -0
  12. package/dist/adapters/codemirror/completion.d.ts.map +1 -0
  13. package/dist/adapters/codemirror/completion.js +64 -0
  14. package/dist/adapters/codemirror/completion.js.map +1 -0
  15. package/dist/adapters/codemirror/contract.d.ts +156 -0
  16. package/dist/adapters/codemirror/contract.d.ts.map +1 -0
  17. package/dist/adapters/codemirror/contract.js +42 -0
  18. package/dist/adapters/codemirror/contract.js.map +1 -0
  19. package/dist/adapters/codemirror/index.d.ts +43 -0
  20. package/dist/adapters/codemirror/index.d.ts.map +1 -0
  21. package/dist/adapters/codemirror/index.js +8 -0
  22. package/dist/adapters/codemirror/index.js.map +1 -0
  23. package/dist/adapters/codemirror/lint.d.ts +17 -0
  24. package/dist/adapters/codemirror/lint.d.ts.map +1 -0
  25. package/dist/adapters/codemirror/lint.js +62 -0
  26. package/dist/adapters/codemirror/lint.js.map +1 -0
  27. package/dist/adapters/codemirror/positions.d.ts +16 -0
  28. package/dist/adapters/codemirror/positions.d.ts.map +1 -0
  29. package/dist/adapters/codemirror/positions.js +65 -0
  30. package/dist/adapters/codemirror/positions.js.map +1 -0
  31. package/dist/adapters/codemirror/stream.d.ts +23 -0
  32. package/dist/adapters/codemirror/stream.d.ts.map +1 -0
  33. package/dist/adapters/codemirror/stream.js +70 -0
  34. package/dist/adapters/codemirror/stream.js.map +1 -0
  35. package/dist/adapters/codemirror/tokens.d.ts +44 -0
  36. package/dist/adapters/codemirror/tokens.d.ts.map +1 -0
  37. package/dist/adapters/codemirror/tokens.js +34 -0
  38. package/dist/adapters/codemirror/tokens.js.map +1 -0
  39. package/dist/adapters/codemirror/tooltips.d.ts +35 -0
  40. package/dist/adapters/codemirror/tooltips.d.ts.map +1 -0
  41. package/dist/adapters/codemirror/tooltips.js +108 -0
  42. package/dist/adapters/codemirror/tooltips.js.map +1 -0
  43. package/dist/core/accounting/charges.d.ts +136 -0
  44. package/dist/core/accounting/charges.d.ts.map +1 -0
  45. package/dist/core/accounting/charges.js +362 -0
  46. package/dist/core/accounting/charges.js.map +1 -0
  47. package/dist/core/accounting/equity.d.ts +158 -0
  48. package/dist/core/accounting/equity.d.ts.map +1 -0
  49. package/dist/core/accounting/equity.js +155 -0
  50. package/dist/core/accounting/equity.js.map +1 -0
  51. package/dist/core/accounting/index.d.ts +44 -0
  52. package/dist/core/accounting/index.d.ts.map +1 -0
  53. package/dist/core/accounting/index.js +36 -0
  54. package/dist/core/accounting/index.js.map +1 -0
  55. package/dist/core/accounting/markers.d.ts +43 -0
  56. package/dist/core/accounting/markers.d.ts.map +1 -0
  57. package/dist/core/accounting/markers.js +64 -0
  58. package/dist/core/accounting/markers.js.map +1 -0
  59. package/dist/core/accounting/monthly.d.ts +52 -0
  60. package/dist/core/accounting/monthly.d.ts.map +1 -0
  61. package/dist/core/accounting/monthly.js +99 -0
  62. package/dist/core/accounting/monthly.js.map +1 -0
  63. package/dist/core/accounting/report.d.ts +38 -0
  64. package/dist/core/accounting/report.d.ts.map +1 -0
  65. package/dist/core/accounting/report.js +63 -0
  66. package/dist/core/accounting/report.js.map +1 -0
  67. package/dist/core/accounting/shapes.d.ts +70 -0
  68. package/dist/core/accounting/shapes.d.ts.map +1 -0
  69. package/dist/core/accounting/shapes.js +21 -0
  70. package/dist/core/accounting/shapes.js.map +1 -0
  71. package/dist/core/accounting/statistics.d.ts +75 -0
  72. package/dist/core/accounting/statistics.d.ts.map +1 -0
  73. package/dist/core/accounting/statistics.js +246 -0
  74. package/dist/core/accounting/statistics.js.map +1 -0
  75. package/dist/core/accounting/trades.d.ts +118 -0
  76. package/dist/core/accounting/trades.d.ts.map +1 -0
  77. package/dist/core/accounting/trades.js +186 -0
  78. package/dist/core/accounting/trades.js.map +1 -0
  79. package/dist/core/backtest/compare.d.ts +38 -0
  80. package/dist/core/backtest/compare.d.ts.map +1 -0
  81. package/dist/core/backtest/compare.js +189 -0
  82. package/dist/core/backtest/compare.js.map +1 -0
  83. package/dist/core/backtest/declaration.d.ts +52 -0
  84. package/dist/core/backtest/declaration.d.ts.map +1 -0
  85. package/dist/core/backtest/declaration.js +48 -0
  86. package/dist/core/backtest/declaration.js.map +1 -0
  87. package/dist/core/backtest/drive.d.ts +29 -0
  88. package/dist/core/backtest/drive.d.ts.map +1 -0
  89. package/dist/core/backtest/drive.js +262 -0
  90. package/dist/core/backtest/drive.js.map +1 -0
  91. package/dist/core/backtest/index.d.ts +46 -0
  92. package/dist/core/backtest/index.d.ts.map +1 -0
  93. package/dist/core/backtest/index.js +36 -0
  94. package/dist/core/backtest/index.js.map +1 -0
  95. package/dist/core/backtest/range.d.ts +84 -0
  96. package/dist/core/backtest/range.d.ts.map +1 -0
  97. package/dist/core/backtest/range.js +90 -0
  98. package/dist/core/backtest/range.js.map +1 -0
  99. package/dist/core/backtest/record.d.ts +238 -0
  100. package/dist/core/backtest/record.d.ts.map +1 -0
  101. package/dist/core/backtest/record.js +176 -0
  102. package/dist/core/backtest/record.js.map +1 -0
  103. package/dist/core/backtest/replay.d.ts +48 -0
  104. package/dist/core/backtest/replay.d.ts.map +1 -0
  105. package/dist/core/backtest/replay.js +127 -0
  106. package/dist/core/backtest/replay.js.map +1 -0
  107. package/dist/core/backtest/resting.d.ts +62 -0
  108. package/dist/core/backtest/resting.d.ts.map +1 -0
  109. package/dist/core/backtest/resting.js +59 -0
  110. package/dist/core/backtest/resting.js.map +1 -0
  111. package/dist/core/backtest/settings.d.ts +117 -0
  112. package/dist/core/backtest/settings.d.ts.map +1 -0
  113. package/dist/core/backtest/settings.js +207 -0
  114. package/dist/core/backtest/settings.js.map +1 -0
  115. package/dist/core/backtest/simulate.d.ts +146 -0
  116. package/dist/core/backtest/simulate.d.ts.map +1 -0
  117. package/dist/core/backtest/simulate.js +217 -0
  118. package/dist/core/backtest/simulate.js.map +1 -0
  119. package/dist/core/catalogue/catalogue.generated.d.ts +66 -0
  120. package/dist/core/catalogue/catalogue.generated.d.ts.map +1 -1
  121. package/dist/core/catalogue/catalogue.generated.js +6 -0
  122. package/dist/core/catalogue/catalogue.generated.js.map +1 -1
  123. package/dist/core/catalogue/values.generated.d.ts +24 -0
  124. package/dist/core/catalogue/values.generated.d.ts.map +1 -1
  125. package/dist/core/check/index.d.ts +2 -1
  126. package/dist/core/check/index.d.ts.map +1 -1
  127. package/dist/core/check/index.js +1 -1
  128. package/dist/core/check/index.js.map +1 -1
  129. package/dist/core/check/library-prose.generated.d.ts +16 -0
  130. package/dist/core/check/library-prose.generated.d.ts.map +1 -0
  131. package/dist/core/check/library-prose.generated.js +353 -0
  132. package/dist/core/check/library-prose.generated.js.map +1 -0
  133. package/dist/core/check/surface.d.ts +24 -0
  134. package/dist/core/check/surface.d.ts.map +1 -1
  135. package/dist/core/check/surface.js +29 -0
  136. package/dist/core/check/surface.js.map +1 -1
  137. package/dist/core/emit/defaults.d.ts +35 -16
  138. package/dist/core/emit/defaults.d.ts.map +1 -1
  139. package/dist/core/emit/defaults.js +66 -0
  140. package/dist/core/emit/defaults.js.map +1 -1
  141. package/dist/core/emit/index.d.ts +2 -0
  142. package/dist/core/emit/index.d.ts.map +1 -1
  143. package/dist/core/emit/index.js +2 -0
  144. package/dist/core/emit/index.js.map +1 -1
  145. package/dist/core/engine/index.d.ts +1 -1
  146. package/dist/core/engine/index.d.ts.map +1 -1
  147. package/dist/core/engine/index.js +1 -1
  148. package/dist/core/engine/index.js.map +1 -1
  149. package/dist/core/engine/load.d.ts +15 -1
  150. package/dist/core/engine/load.d.ts.map +1 -1
  151. package/dist/core/engine/load.js +1 -0
  152. package/dist/core/engine/load.js.map +1 -1
  153. package/dist/core/index.d.ts +37 -3
  154. package/dist/core/index.d.ts.map +1 -1
  155. package/dist/core/index.js +17 -1
  156. package/dist/core/index.js.map +1 -1
  157. package/dist/core/version/version.generated.d.ts +1 -1
  158. package/dist/core/version/version.generated.js +1 -1
  159. package/dist/editor/complete.d.ts +40 -0
  160. package/dist/editor/complete.d.ts.map +1 -0
  161. package/dist/editor/complete.js +206 -0
  162. package/dist/editor/complete.js.map +1 -0
  163. package/dist/editor/diagnose.d.ts +18 -0
  164. package/dist/editor/diagnose.d.ts.map +1 -0
  165. package/dist/editor/diagnose.js +70 -0
  166. package/dist/editor/diagnose.js.map +1 -0
  167. package/dist/editor/format.d.ts +11 -0
  168. package/dist/editor/format.d.ts.map +1 -0
  169. package/dist/editor/format.js +50 -0
  170. package/dist/editor/format.js.map +1 -0
  171. package/dist/editor/highlight.d.ts +28 -0
  172. package/dist/editor/highlight.d.ts.map +1 -0
  173. package/dist/editor/highlight.js +65 -0
  174. package/dist/editor/highlight.js.map +1 -0
  175. package/dist/editor/hover.d.ts +40 -0
  176. package/dist/editor/hover.d.ts.map +1 -0
  177. package/dist/editor/hover.js +147 -0
  178. package/dist/editor/hover.js.map +1 -0
  179. package/dist/editor/index.d.ts +60 -0
  180. package/dist/editor/index.d.ts.map +1 -0
  181. package/dist/editor/index.js +7 -0
  182. package/dist/editor/index.js.map +1 -0
  183. package/dist/editor/kinds.d.ts +27 -0
  184. package/dist/editor/kinds.d.ts.map +1 -0
  185. package/dist/editor/kinds.js +118 -0
  186. package/dist/editor/kinds.js.map +1 -0
  187. package/dist/editor/layout.d.ts +47 -0
  188. package/dist/editor/layout.d.ts.map +1 -0
  189. package/dist/editor/layout.js +135 -0
  190. package/dist/editor/layout.js.map +1 -0
  191. package/dist/editor/manifest.d.ts +47 -0
  192. package/dist/editor/manifest.d.ts.map +1 -0
  193. package/dist/editor/manifest.js +93 -0
  194. package/dist/editor/manifest.js.map +1 -0
  195. package/dist/editor/reading.d.ts +41 -0
  196. package/dist/editor/reading.d.ts.map +1 -0
  197. package/dist/editor/reading.js +51 -0
  198. package/dist/editor/reading.js.map +1 -0
  199. package/dist/editor/scan.d.ts +26 -0
  200. package/dist/editor/scan.d.ts.map +1 -0
  201. package/dist/editor/scan.js +139 -0
  202. package/dist/editor/scan.js.map +1 -0
  203. package/dist/editor/scope.d.ts +19 -0
  204. package/dist/editor/scope.d.ts.map +1 -0
  205. package/dist/editor/scope.js +99 -0
  206. package/dist/editor/scope.js.map +1 -0
  207. package/dist/editor/signature.d.ts +38 -0
  208. package/dist/editor/signature.d.ts.map +1 -0
  209. package/dist/editor/signature.js +112 -0
  210. package/dist/editor/signature.js.map +1 -0
  211. package/dist/editor/site.d.ts +46 -0
  212. package/dist/editor/site.d.ts.map +1 -0
  213. package/dist/editor/site.js +184 -0
  214. package/dist/editor/site.js.map +1 -0
  215. package/dist/editor/spacing.d.ts +29 -0
  216. package/dist/editor/spacing.d.ts.map +1 -0
  217. package/dist/editor/spacing.js +116 -0
  218. package/dist/editor/spacing.js.map +1 -0
  219. package/package.json +30 -3
  220. package/spec/errors.json +140 -0
  221. package/src/adapters/charts/surfaces.ts +17 -0
  222. package/src/adapters/charts/tables.ts +88 -0
  223. package/src/adapters/codemirror/commands.ts +53 -0
  224. package/src/adapters/codemirror/completion.ts +74 -0
  225. package/src/adapters/codemirror/contract.ts +156 -0
  226. package/src/adapters/codemirror/index.ts +66 -0
  227. package/src/adapters/codemirror/lint.ts +66 -0
  228. package/src/adapters/codemirror/positions.ts +79 -0
  229. package/src/adapters/codemirror/stream.ts +87 -0
  230. package/src/adapters/codemirror/tokens.ts +64 -0
  231. package/src/adapters/codemirror/tooltips.ts +113 -0
  232. package/src/core/accounting/charges.ts +452 -0
  233. package/src/core/accounting/equity.ts +276 -0
  234. package/src/core/accounting/index.ts +49 -0
  235. package/src/core/accounting/markers.ts +95 -0
  236. package/src/core/accounting/monthly.ts +137 -0
  237. package/src/core/accounting/report.ts +89 -0
  238. package/src/core/accounting/shapes.ts +73 -0
  239. package/src/core/accounting/statistics.ts +350 -0
  240. package/src/core/accounting/trades.ts +313 -0
  241. package/src/core/backtest/compare.ts +244 -0
  242. package/src/core/backtest/declaration.ts +97 -0
  243. package/src/core/backtest/drive.ts +364 -0
  244. package/src/core/backtest/index.ts +52 -0
  245. package/src/core/backtest/range.ts +137 -0
  246. package/src/core/backtest/record.ts +341 -0
  247. package/src/core/backtest/replay.ts +158 -0
  248. package/src/core/backtest/resting.ts +125 -0
  249. package/src/core/backtest/settings.ts +280 -0
  250. package/src/core/backtest/simulate.ts +304 -0
  251. package/src/core/catalogue/catalogue.generated.ts +6 -0
  252. package/src/core/catalogue/values.generated.ts +6 -0
  253. package/src/core/check/index.ts +3 -0
  254. package/src/core/check/library-prose.generated.ts +367 -0
  255. package/src/core/check/surface.ts +34 -0
  256. package/src/core/emit/defaults.ts +70 -0
  257. package/src/core/emit/index.ts +2 -0
  258. package/src/core/engine/index.ts +1 -1
  259. package/src/core/engine/load.ts +16 -2
  260. package/src/core/index.ts +85 -1
  261. package/src/core/version/version.generated.ts +1 -1
  262. package/src/editor/complete.ts +266 -0
  263. package/src/editor/diagnose.ts +71 -0
  264. package/src/editor/format.ts +85 -0
  265. package/src/editor/highlight.ts +110 -0
  266. package/src/editor/hover.ts +199 -0
  267. package/src/editor/index.ts +65 -0
  268. package/src/editor/kinds.ts +157 -0
  269. package/src/editor/layout.ts +189 -0
  270. package/src/editor/manifest.ts +119 -0
  271. package/src/editor/reading.ts +69 -0
  272. package/src/editor/scan.ts +162 -0
  273. package/src/editor/scope.ts +122 -0
  274. package/src/editor/signature.ts +150 -0
  275. package/src/editor/site.ts +233 -0
  276. package/src/editor/spacing.ts +132 -0
@@ -0,0 +1,341 @@
1
+ /**
2
+ * The run record: a whole run as a plain JSON document.
3
+ *
4
+ * **The record is the conformance case.** That is the one decision this module
5
+ * exists to hold, and everything in it follows from it: no object reference, no
6
+ * function, no dependence on this implementation's internals, and nothing that
7
+ * only this engine can read. A record carries the script revision, the compiled
8
+ * program, the bars, the settings the host chose, the frames the destination
9
+ * answered in delivery order, the fills the engine folded in fold order, the
10
+ * ledger the run ended with, the diagnostics and the report.
11
+ *
12
+ * **The bars are inline or referenced, and both carry the same hash.** Inline is
13
+ * the conformance form, because a case has to hold every byte of its own input.
14
+ * Referenced is the operational form, because the smallest deployment has a one
15
+ * megabyte request body and nothing that grows with history may travel in one.
16
+ * A replay whose bars do not hash to the record's hash is OS6022 rather than a
17
+ * silently different study.
18
+ *
19
+ * **The frames name an intent by ordinal and never by an engine's own id**,
20
+ * because a case cannot know what id another engine minted. The same reason the
21
+ * ledger rows here are flat words rather than this engine's own types.
22
+ *
23
+ * The record is written through the existing canonical encoding, so there is one
24
+ * canonical writer in the repository and key order and number form are fixed for
25
+ * everybody.
26
+ */
27
+ import type { RecordedFill, Report } from '../accounting/index.js';
28
+ import type { Diagnostic } from '../diagnostics/index.js';
29
+ import { canonicalise, programHash, sha256 } from '../emit/index.js';
30
+ import type { CompiledProgram, SourceStamp } from '../emit/index.js';
31
+ import type { LedgerRow } from '../engine/index.js';
32
+ import { VERSION } from '../version/index.js';
33
+ import type { BacktestSettings } from './settings.js';
34
+
35
+ /** One bar as a record holds it. */
36
+ export interface RecordedBar {
37
+ readonly time: number | null;
38
+ readonly open: number | null;
39
+ readonly high: number | null;
40
+ readonly low: number | null;
41
+ readonly close: number | null;
42
+ readonly volume: number | null;
43
+ readonly oi: number | null;
44
+ }
45
+
46
+ /**
47
+ * The bars, held or pointed at.
48
+ *
49
+ * Both forms carry the same hash, computed the same way over the canonical
50
+ * tuple of each bar, so a referenced record can be turned into an inline one by
51
+ * whoever holds the bars and the result is the same case.
52
+ */
53
+ export type BarsInRecord =
54
+ | {
55
+ readonly form: 'inline';
56
+ readonly hash: string;
57
+ readonly count: number;
58
+ readonly rows: readonly RecordedBar[];
59
+ }
60
+ | {
61
+ readonly form: 'referenced';
62
+ readonly hash: string;
63
+ readonly count: number;
64
+ readonly firstTime: number | null;
65
+ readonly lastTime: number | null;
66
+ };
67
+
68
+ /** The columns of `conformance.md`'s frames.csv, in its order and with its names. */
69
+ export interface RecordedFrame {
70
+ readonly afterBar: number;
71
+ /** An ordinal, 1-based, never an engine's own id. */
72
+ readonly intent: number;
73
+ readonly status: string;
74
+ readonly filledQty: number;
75
+ readonly avgFillPrice: number | null;
76
+ readonly orderRef: string | null;
77
+ readonly text: string | null;
78
+ }
79
+
80
+ /** A ledger row of `stdlib.md` 17.7, flattened: the `orders` channel of expected.json. */
81
+ export interface RecordedOrder {
82
+ readonly intent: number;
83
+ readonly orderRef: string;
84
+ readonly tag: string;
85
+ readonly leg: string;
86
+ readonly positionRef: number;
87
+ readonly symbol: string | null;
88
+ readonly exchange: string | null;
89
+ readonly product: string;
90
+ readonly side: string;
91
+ readonly qty: number | null;
92
+ readonly qtyType: string;
93
+ readonly type: string | null;
94
+ readonly price: number | null;
95
+ readonly trigger: number | null;
96
+ readonly status: string;
97
+ readonly filledQty: number;
98
+ readonly avgFillPrice: number | null;
99
+ readonly rejection: string | null;
100
+ readonly placedAt: number | null;
101
+ readonly updatedAt: number | null;
102
+ readonly units: number | null;
103
+ }
104
+
105
+ /** A diagnostic as a record holds it: the code, the span and the bar. */
106
+ export interface RecordedDiagnostic {
107
+ readonly code: string;
108
+ readonly line: number;
109
+ readonly column: number;
110
+ readonly severity: string;
111
+ readonly barIndex: number | null;
112
+ }
113
+
114
+ /** One run, whole, and readable by an engine that is not this one. */
115
+ export interface RunRecord {
116
+ readonly recordVersion: number;
117
+ readonly engine: { readonly name: string; readonly version: string };
118
+ readonly languageVersion: string;
119
+ /** Already plain data. */
120
+ readonly program: CompiledProgram;
121
+ readonly programHash: string;
122
+ /** Hash, lines, file: the script revision. */
123
+ readonly source: SourceStamp;
124
+ readonly settings: BacktestSettings;
125
+ readonly bars: BarsInRecord;
126
+ /** What the destination answered, in delivery order. */
127
+ readonly frames: readonly RecordedFrame[];
128
+ /** What the engine folded, in fold order. */
129
+ readonly fills: readonly RecordedFill[];
130
+ /** The ledger at the end, oldest first. */
131
+ readonly orders: readonly RecordedOrder[];
132
+ readonly diagnostics: readonly RecordedDiagnostic[];
133
+ readonly report: Report;
134
+ }
135
+
136
+ /**
137
+ * The revision of this document's own shape.
138
+ *
139
+ * A reader is handed a record and has to know what it is looking at before it
140
+ * reads a field, so the number is first in the document and is written by this
141
+ * file alone. It moves when a channel is added or a meaning changes, never when
142
+ * a figure in a report does.
143
+ */
144
+ export const RECORD_VERSION = 1;
145
+
146
+ /** What this engine calls itself in a record it wrote. */
147
+ const ENGINE_NAME = 'openscript';
148
+
149
+ /** The parts a run hands over, each already in the shape the record holds. */
150
+ export interface RecordParts {
151
+ readonly program: CompiledProgram;
152
+ readonly settings: BacktestSettings;
153
+ readonly bars: readonly RecordedBar[];
154
+ /**
155
+ * Whether the bars travel in the record or are pointed at.
156
+ *
157
+ * Inline is the conformance form, because a case holds every byte of its own
158
+ * input. Referenced is the operational form, because nothing that grows with
159
+ * history may travel in a request body. Both carry the same hash over the
160
+ * same canonical tuples, so one becomes the other without becoming a
161
+ * different case.
162
+ */
163
+ readonly form: 'inline' | 'referenced';
164
+ readonly frames: readonly RecordedFrame[];
165
+ readonly fills: readonly RecordedFill[];
166
+ readonly orders: readonly RecordedOrder[];
167
+ readonly diagnostics: readonly RecordedDiagnostic[];
168
+ readonly report: Report;
169
+ }
170
+
171
+ /**
172
+ * One run, as the document another engine is handed.
173
+ *
174
+ * Nothing is computed here. Every channel arrives folded, because what a record
175
+ * says has to be what the run did rather than what a second fold of the same
176
+ * inputs came to: a record that recomputed its own report would agree with
177
+ * itself whatever the engine had actually done.
178
+ */
179
+ export function recordOf(parts: RecordParts): RunRecord {
180
+ return {
181
+ recordVersion: RECORD_VERSION,
182
+ engine: { name: ENGINE_NAME, version: VERSION },
183
+ languageVersion: String(parts.program.openscript.language),
184
+ program: parts.program,
185
+ programHash: programHash(parts.program),
186
+ source: parts.program.source,
187
+ settings: parts.settings,
188
+ bars: barsIn(parts.bars, parts.form),
189
+ frames: parts.frames,
190
+ fills: parts.fills,
191
+ orders: parts.orders,
192
+ diagnostics: parts.diagnostics,
193
+ report: parts.report,
194
+ };
195
+ }
196
+
197
+ /**
198
+ * The bars, held or pointed at, and the same hash either way.
199
+ *
200
+ * The referenced form keeps the first and last times so that a reader can say
201
+ * which bars are wanted without holding them, and the count so that a set of
202
+ * the wrong length is known to be wrong before it is hashed.
203
+ */
204
+ export function barsIn(bars: readonly RecordedBar[], form: 'inline' | 'referenced'): BarsInRecord {
205
+ const hash = barsHash(bars);
206
+ if (form === 'inline') {
207
+ return { form: 'inline', hash, count: bars.length, rows: bars };
208
+ }
209
+ return {
210
+ form: 'referenced',
211
+ hash,
212
+ count: bars.length,
213
+ firstTime: bars[0]?.time ?? null,
214
+ lastTime: bars[bars.length - 1]?.time ?? null,
215
+ };
216
+ }
217
+
218
+ /**
219
+ * The hash a record names its bars by.
220
+ *
221
+ * Over the canonical tuple of each bar, in the order they were supplied, and
222
+ * through the canonical encoding the compiled program is hashed with, so there
223
+ * is one canonical writer in the repository rather than two that agree until
224
+ * one of them is changed. A tuple rather than an object, because the field
225
+ * order is then the specification's and not a sort's.
226
+ */
227
+ export function barsHash(bars: readonly RecordedBar[]): string {
228
+ const tuples = bars.map((bar) => [
229
+ bar.time,
230
+ bar.open,
231
+ bar.high,
232
+ bar.low,
233
+ bar.close,
234
+ bar.volume,
235
+ bar.oi,
236
+ ]);
237
+ return 'sha256:' + sha256(canonicalise(tuples));
238
+ }
239
+
240
+ /**
241
+ * The record as the bytes another engine reads.
242
+ *
243
+ * Through the canonical encoding, so key order is fixed, every number is in the
244
+ * shortest decimal form that reads back as itself, and two runs of the same
245
+ * record produce the same bytes on every machine. That is what makes the
246
+ * reproducibility test a byte comparison rather than a tour of the fields.
247
+ */
248
+ export function recordToJson(record: RunRecord): string {
249
+ return canonicalise(record);
250
+ }
251
+
252
+ /**
253
+ * The run, without who produced it.
254
+ *
255
+ * **`engine` is provenance, and provenance is not part of the run.** The claim
256
+ * a rerun makes is that the run is a function of the record, and that claim has
257
+ * to survive the engine it runs on being upgraded: a record stored under
258
+ * `0.3.0` and rerun under `0.4.0` produces the same trades, the same fills and
259
+ * the same money, and a document carrying the version stamp inside the bytes
260
+ * being compared says it does not.
261
+ *
262
+ * It was compared as whole bytes until the first version bump would have broken
263
+ * it, which is a test that passes for exactly as long as nothing changes and
264
+ * then fails for the one reason that is not a defect. So the stamp stays in the
265
+ * record, because knowing which engine wrote a run is worth keeping, and the
266
+ * comparison is made over everything else.
267
+ */
268
+ export function runBytes(record: RunRecord): string {
269
+ const { engine: _engine, ...run } = record;
270
+ return canonicalise(run);
271
+ }
272
+
273
+ /**
274
+ * A record read back from those bytes.
275
+ *
276
+ * A parse and not a validation: what comes back is the document as it was
277
+ * written, and a document this engine did not write is the caller's to trust or
278
+ * not. The one thing asserted is the revision, because reading a later
279
+ * revision's fields under this one's rules is how a record silently becomes a
280
+ * different run.
281
+ */
282
+ export function recordFromJson(text: string): RunRecord | null {
283
+ const parsed: unknown = JSON.parse(text);
284
+ if (parsed === null || typeof parsed !== 'object') return null;
285
+ const record = parsed as RunRecord;
286
+ return record.recordVersion === RECORD_VERSION ? record : null;
287
+ }
288
+
289
+ /**
290
+ * One ledger row, flattened into the words a case file prints.
291
+ *
292
+ * The engine's own types do not cross: a second engine has its own, and a
293
+ * channel written in this one's would be a case only this one could read. The
294
+ * intent is an ordinal for the same reason, because no engine can know what id
295
+ * another minted.
296
+ *
297
+ * `qtyType` comes from the intent rather than from the row, because the unit a
298
+ * quantity is counted in is per order and not per leg: an order the engine
299
+ * sized itself is in units whatever the declaration counts in, and a row that
300
+ * printed the declaration's unit for it would state a quantity in a unit it was
301
+ * never measured in.
302
+ */
303
+ export function orderIn(row: LedgerRow, intent: number, qtyType: string): RecordedOrder {
304
+ return {
305
+ intent,
306
+ orderRef: row.orderRef,
307
+ tag: row.tag,
308
+ leg: row.leg,
309
+ positionRef: row.positionRef,
310
+ symbol: row.instrument.symbol,
311
+ exchange: row.instrument.exchange,
312
+ product: row.product,
313
+ side: row.side,
314
+ qty: row.qty,
315
+ qtyType,
316
+ type: row.type,
317
+ price: row.price,
318
+ trigger: row.trigger,
319
+ status: row.status,
320
+ filledQty: row.filledQty,
321
+ avgFillPrice: row.avgFillPrice,
322
+ rejection: row.rejection === '' ? null : row.rejection,
323
+ placedAt: row.placedAt,
324
+ updatedAt: row.updatedAt,
325
+ units: row.units,
326
+ };
327
+ }
328
+
329
+ /** One diagnostic, as a record holds it: the code, the span and the bar. */
330
+ export function diagnosticIn(
331
+ diagnostic: Diagnostic,
332
+ barIndex: number | null,
333
+ ): RecordedDiagnostic {
334
+ return {
335
+ code: diagnostic.code,
336
+ line: diagnostic.span.line,
337
+ column: diagnostic.span.column,
338
+ severity: diagnostic.severity,
339
+ barIndex,
340
+ };
341
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * A stored run, reported again and run again.
3
+ *
4
+ * Two questions, and they are different questions, which is why they are two
5
+ * calls:
6
+ *
7
+ * - **`replay` asks whether the report is a function of the fills.** It folds
8
+ * the money again from the record's own fills and its own bar closes, with no
9
+ * bar executed and no order placed, and what comes back has to equal the
10
+ * report the record carries. If it does not, the report was reading something
11
+ * the engine happened to be holding rather than what the run settled, and
12
+ * nobody could reproduce it from the document.
13
+ * - **`rerun` asks whether the engine still does what it did.** It executes the
14
+ * record's program over the record's bars under the record's settings, and
15
+ * the two records are compared as bytes. A rerun of one record on this engine
16
+ * is bit-identical or it is a defect: the tolerance on the record is for a
17
+ * second implementation and is never this one's excuse.
18
+ *
19
+ * **The bars are proved before either is attempted.** A record names the bars it
20
+ * was made from by a hash, and bars are revised: a feed corrects a print, a
21
+ * session is extended, a split is applied to history. A replay over revised bars
22
+ * reporting the original figures is the most convincing wrong answer this system
23
+ * can produce, so a set that does not hash to the record's is OS6022.
24
+ *
25
+ * **One engine call is made, and nothing is executed by it.** A declaration
26
+ * field may be written by an `input()`, and what an input resolved to is the
27
+ * engine's rule; asking it here rather than resolving a second time is what
28
+ * keeps the replayed capital and commission the ones the run used. No bar is
29
+ * appended, so no value is computed and no order is placed: the load is a
30
+ * question about the program, not a run of it.
31
+ */
32
+ import { reportOf, scheduleFromDeclaration } from '../accounting/index.js';
33
+ import type { ChargeSchedule, Report } from '../accounting/index.js';
34
+ import { diagnosticFor } from '../diagnostics/index.js';
35
+ import type { Diagnostic } from '../diagnostics/index.js';
36
+ import { load } from '../engine/index.js';
37
+ import { backtest } from './drive.js';
38
+ import type { BacktestResult } from './drive.js';
39
+ import { declarationOf } from './declaration.js';
40
+ import type { RunDeclaration } from './declaration.js';
41
+ import { marksFor, windowFor } from './range.js';
42
+ import { barsHash } from './record.js';
43
+ import type { RecordedBar, RunRecord } from './record.js';
44
+
45
+ /** The report a record folds to, or why it could not be folded. */
46
+ export type ReplayResult =
47
+ | { readonly ok: true; readonly report: Report }
48
+ | { readonly ok: false; readonly diagnostic: Diagnostic };
49
+
50
+ /**
51
+ * The record's own report, computed again from its own fills.
52
+ *
53
+ * The bars are the record's where it carries them and the caller's where it
54
+ * points at them, and either way they are hashed against what the record names
55
+ * before a figure is computed from them.
56
+ */
57
+ export function replay(record: RunRecord, bars: readonly RecordedBar[] | null = null): ReplayResult {
58
+ const held = barsOf(record, bars);
59
+ if (!held.ok) return { ok: false, diagnostic: held.diagnostic };
60
+
61
+ const framed = windowFor(held.bars, record.settings.range);
62
+ if (!framed.ok) return { ok: false, diagnostic: framed.diagnostic };
63
+
64
+ const declared = declarationIn(record);
65
+ if (!declared.ok) return { ok: false, diagnostic: declared.diagnostic };
66
+
67
+ return {
68
+ ok: true,
69
+ report: reportOf(
70
+ record.fills,
71
+ marksFor(held.bars, framed.covered),
72
+ scheduleIn(record, declared.declaration),
73
+ record.settings.contract,
74
+ declared.declaration.capital,
75
+ ),
76
+ };
77
+ }
78
+
79
+ /**
80
+ * The same run, executed again.
81
+ *
82
+ * Everything the run depended on is in the record: the program, the bars, the
83
+ * settings and the inputs. So a rerun takes no argument the record does not
84
+ * already hold, except the bars a referenced record points at rather than
85
+ * carries, and the record it produces is comparable with the original field for
86
+ * field and byte for byte.
87
+ */
88
+ export function rerun(record: RunRecord, bars: readonly RecordedBar[] | null = null): BacktestResult {
89
+ const held = barsOf(record, bars);
90
+ if (!held.ok) return { ok: false, diagnostic: held.diagnostic };
91
+ return backtest(record.program, held.bars, record.settings, { form: record.bars.form });
92
+ }
93
+
94
+ type BarsResult =
95
+ | { readonly ok: true; readonly bars: readonly RecordedBar[] }
96
+ | { readonly ok: false; readonly diagnostic: Diagnostic };
97
+
98
+ /**
99
+ * The bars a record was made from, proved to be those bars.
100
+ *
101
+ * A record carrying its own bars is still checked against any that are supplied
102
+ * beside them, because supplying a different set is exactly the mistake worth
103
+ * catching: the caller believes they are replaying this run and they are
104
+ * studying another one.
105
+ */
106
+ export function barsOf(record: RunRecord, supplied: readonly RecordedBar[] | null): BarsResult {
107
+ if (supplied !== null) {
108
+ const hash = barsHash(supplied);
109
+ if (hash !== record.bars.hash) return { ok: false, diagnostic: mismatch(hash, record) };
110
+ return { ok: true, bars: supplied };
111
+ }
112
+ if (record.bars.form === 'inline') return { ok: true, bars: record.bars.rows };
113
+ // A referenced record points at bars it does not hold, so there is nothing to
114
+ // replay until whoever holds them supplies them. It is the same refusal as a
115
+ // wrong set, because the question it answers is the same one: are these the
116
+ // bars the record was made from.
117
+ return { ok: false, diagnostic: mismatch('no bars supplied', record) };
118
+ }
119
+
120
+ function mismatch(found: string, record: RunRecord): Diagnostic {
121
+ return diagnosticFor('OS6022', NO_POSITION, { found, expected: record.bars.hash });
122
+ }
123
+
124
+ type DeclarationResult =
125
+ | { readonly ok: true; readonly declaration: RunDeclaration }
126
+ | { readonly ok: false; readonly diagnostic: Diagnostic };
127
+
128
+ /**
129
+ * What the record's own program declares, after the record's own inputs.
130
+ *
131
+ * The destination handed to the load is one that answers nothing, because
132
+ * nothing is placed: a strategy declares the orders capability and a host that
133
+ * did not offer it would be refused at load for a reason that has nothing to do
134
+ * with the record.
135
+ */
136
+ function declarationIn(record: RunRecord): DeclarationResult {
137
+ const loaded = load(record.program, {
138
+ settings: record.settings.inputs,
139
+ host: { route: () => undefined },
140
+ });
141
+ if (!loaded.ok) return { ok: false, diagnostic: loaded.diagnostic };
142
+ return { ok: true, declaration: declarationOf(loaded.engine.program, loaded.inputs) };
143
+ }
144
+
145
+ /** The cost model the record was carried out under, derived where it was derived. */
146
+ function scheduleIn(record: RunRecord, declared: RunDeclaration): ChargeSchedule {
147
+ if (record.settings.costs !== null) return record.settings.costs;
148
+ return scheduleFromDeclaration(
149
+ declared.commission,
150
+ declared.commissionType,
151
+ declared.slippage,
152
+ record.settings.contract.currency,
153
+ record.settings.contract.digits,
154
+ );
155
+ }
156
+
157
+ /** Where a refusal about a record points: nowhere in anybody's script. */
158
+ const NO_POSITION: Diagnostic['span'] = { offset: 0, length: 0, line: 0, column: 0 };
@@ -0,0 +1,125 @@
1
+ /**
2
+ * One resting order against one bar: did it trade, and at what price.
3
+ *
4
+ * **A bar is four prices and no path.** Whether the high came before the low is
5
+ * not in the data, so every rule here is one that does not need to know, and
6
+ * the places where knowing would matter are decided against the strategy rather
7
+ * than guessed in its favour. That is the whole discipline of this file: a
8
+ * backtest that is generous about fills is a backtest that reports money the
9
+ * market never offered.
10
+ *
11
+ * Three rules, each with the case it exists for:
12
+ *
13
+ * - **Touched is not traded through.** A limit resting exactly at the low of a
14
+ * bar may or may not have been filled: the print happened, somebody was
15
+ * filled at that price, and whether it was this order depends on a queue no
16
+ * bar records. The default is that it was not (`limitNeedsThrough`), and a
17
+ * host that has decided otherwise for its own market says so in the policy.
18
+ * - **A gap fills at the open, not at the level.** A stop triggered by a bar
19
+ * that opened beyond it was not filled at its trigger, and a backtest that
20
+ * says it was is reporting the one price that was never available. The open
21
+ * is the first price there was.
22
+ * - **A limit fills at its own price or better, and never worse.** Where the
23
+ * bar opened already through a limit, the open is the better price and the
24
+ * fill is there; a limit is never worsened by slippage, because a limit that
25
+ * is worsened is not a limit.
26
+ *
27
+ * A stop limit is both, in one bar and in that order: the trigger has to be
28
+ * reached and the limit has to be traded through, and where only the trigger is
29
+ * reached the order becomes a resting limit and waits.
30
+ */
31
+ import type { OrderSide, OrderType } from '../engine/index.js';
32
+ import type { FillPolicy } from './settings.js';
33
+ import type { RecordedBar } from './record.js';
34
+
35
+ /** A resting order, as the venue holds one. */
36
+ export interface RestingOrder {
37
+ readonly side: OrderSide;
38
+ readonly type: OrderType;
39
+ /** The price a limit may not be worse than, absent on a plain stop. */
40
+ readonly limit: number | null;
41
+ /** The price a stop is triggered at, absent on a plain limit. */
42
+ readonly trigger: number | null;
43
+ }
44
+
45
+ /** What one bar did to one resting order. */
46
+ export type RestOutcome =
47
+ | { readonly filled: false; readonly triggered: boolean }
48
+ | {
49
+ readonly filled: true;
50
+ readonly price: number;
51
+ /** Whether the price is the bar's open, which is a gap through the level. */
52
+ readonly atOpen: boolean;
53
+ /** Whether slippage applies, which a limit never takes. */
54
+ readonly slips: boolean;
55
+ };
56
+
57
+ const NOTHING: RestOutcome = { filled: false, triggered: false };
58
+
59
+ /**
60
+ * One order against one bar.
61
+ *
62
+ * A bar missing any of the four prices decides nothing: an incomplete bar is
63
+ * not evidence that a level was reached and it is not evidence that it was not.
64
+ */
65
+ export function testResting(
66
+ order: RestingOrder,
67
+ bar: RecordedBar,
68
+ policy: FillPolicy,
69
+ ): RestOutcome {
70
+ const open = bar.open;
71
+ const high = bar.high;
72
+ const low = bar.low;
73
+ if (open === null || high === null || low === null || bar.close === null) return NOTHING;
74
+
75
+ if (order.type === 'limit') return limitAgainst(order, open, high, low, policy);
76
+
77
+ const trigger = order.trigger;
78
+ if (trigger === null) return NOTHING;
79
+ const reached = order.side === 'buy' ? high >= trigger : low <= trigger;
80
+ if (!reached) return NOTHING;
81
+
82
+ if (order.type === 'stop') {
83
+ const gapped = order.side === 'buy' ? open >= trigger : open <= trigger;
84
+ const price = gapped && policy.stopFillsAtOpenOnGap ? open : trigger;
85
+ return { filled: true, price, atOpen: gapped && policy.stopFillsAtOpenOnGap, slips: true };
86
+ }
87
+
88
+ // A stop limit that triggered is a limit for the rest of this bar. Where the
89
+ // limit is not traded through it keeps resting, and the caller is told the
90
+ // trigger was reached so that the order rests as a limit from here on.
91
+ const asLimit = limitAgainst(order, open, high, low, policy);
92
+ return asLimit.filled ? asLimit : { filled: false, triggered: true };
93
+ }
94
+
95
+ /**
96
+ * A limit against one bar.
97
+ *
98
+ * `limitNeedsThrough` is the difference between a strict comparison and a loose
99
+ * one, and it is the only knob in this file that changes a fill into no fill
100
+ * rather than one price into another.
101
+ */
102
+ function limitAgainst(
103
+ order: RestingOrder,
104
+ open: number,
105
+ high: number,
106
+ low: number,
107
+ policy: FillPolicy,
108
+ ): RestOutcome {
109
+ const limit = order.limit;
110
+ if (limit === null) return NOTHING;
111
+
112
+ if (order.side === 'buy') {
113
+ const traded = policy.limitNeedsThrough ? low < limit : low <= limit;
114
+ if (!traded) return NOTHING;
115
+ // The open already below the limit is the better price, and it is the first
116
+ // price the bar had.
117
+ const gapped = open < limit;
118
+ return { filled: true, price: gapped ? open : limit, atOpen: gapped, slips: false };
119
+ }
120
+
121
+ const traded = policy.limitNeedsThrough ? high > limit : high >= limit;
122
+ if (!traded) return NOTHING;
123
+ const gapped = open > limit;
124
+ return { filled: true, price: gapped ? open : limit, atOpen: gapped, slips: false };
125
+ }