@lumencharts/trading-platform 0.0.0-stage → 0.1.1

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 (236) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/LICENSE +55 -0
  3. package/README.md +53 -2
  4. package/dist/asset-entry.d.ts +3 -0
  5. package/dist/asset.d.ts +3 -0
  6. package/dist/asset.js +21689 -0
  7. package/dist/chart/bracket-links.d.ts +8 -0
  8. package/dist/chart/context-actions.d.ts +7 -0
  9. package/dist/chart/edit-presentation.d.ts +32 -0
  10. package/dist/chart/edit-preview.d.ts +26 -0
  11. package/dist/chart/exit-profit.d.ts +32 -0
  12. package/dist/chart/frame-batch.d.ts +15 -0
  13. package/dist/chart/overlay-coordinator.d.ts +18 -0
  14. package/dist/chart/overlay-events.d.ts +3 -0
  15. package/dist/chart/overlay-gesture.d.ts +40 -0
  16. package/dist/chart/overlay-index.d.ts +30 -0
  17. package/dist/chart/overlay-projection.d.ts +51 -0
  18. package/dist/chart/overlay-types.d.ts +42 -0
  19. package/dist/chart/parent-links.d.ts +33 -0
  20. package/dist/chart/position-profit.d.ts +15 -0
  21. package/dist/chart/review-lock.d.ts +14 -0
  22. package/dist/chart/ticket-projection.d.ts +36 -0
  23. package/dist/compat/default-formatters.d.ts +6 -0
  24. package/dist/compat/delegate.d.ts +11 -0
  25. package/dist/compat/factory.d.ts +5 -0
  26. package/dist/compat/formatters.d.ts +26 -0
  27. package/dist/compat/host-dialogs.d.ts +5 -0
  28. package/dist/compat/host-preferences.d.ts +8 -0
  29. package/dist/compat/host.d.ts +39 -0
  30. package/dist/compat/watched-value.d.ts +25 -0
  31. package/dist/conformance/index.d.ts +78 -0
  32. package/dist/conformance/index.js +6859 -0
  33. package/dist/conformance/replay.d.ts +35 -0
  34. package/dist/contracts/broker.d.ts +1122 -0
  35. package/dist/contracts/broker.js +168 -0
  36. package/dist/contracts/index.d.ts +3 -0
  37. package/dist/contracts/index.js +168 -0
  38. package/dist/contracts/market-data.d.ts +289 -0
  39. package/dist/contracts/market-data.js +11 -0
  40. package/dist/contracts/ports.d.ts +469 -0
  41. package/dist/contracts/ports.js +5 -0
  42. package/dist/core/account-datasets.d.ts +29 -0
  43. package/dist/core/account-lifecycle.d.ts +70 -0
  44. package/dist/core/account-types.d.ts +6 -0
  45. package/dist/core/bounded-map.d.ts +12 -0
  46. package/dist/core/bracket-input.d.ts +32 -0
  47. package/dist/core/bracket-modification.d.ts +6 -0
  48. package/dist/core/bracket-parent.d.ts +11 -0
  49. package/dist/core/broker-debug.d.ts +10 -0
  50. package/dist/core/capabilities.d.ts +34 -0
  51. package/dist/core/capability-metadata.d.ts +60 -0
  52. package/dist/core/capability-policy.d.ts +32 -0
  53. package/dist/core/chart-exit-level.d.ts +11 -0
  54. package/dist/core/chart-order-edit.d.ts +50 -0
  55. package/dist/core/clock.d.ts +2 -0
  56. package/dist/core/close-commands.d.ts +24 -0
  57. package/dist/core/close-flow.d.ts +14 -0
  58. package/dist/core/command-context.d.ts +16 -0
  59. package/dist/core/command-coordinator.d.ts +71 -0
  60. package/dist/core/command-follow.d.ts +32 -0
  61. package/dist/core/command-keys.d.ts +11 -0
  62. package/dist/core/context-orders.d.ts +19 -0
  63. package/dist/core/deferred.d.ts +5 -0
  64. package/dist/core/dialog-coordinator.d.ts +73 -0
  65. package/dist/core/display-preferences.d.ts +10 -0
  66. package/dist/core/disposal.d.ts +8 -0
  67. package/dist/core/entity-store.d.ts +56 -0
  68. package/dist/core/entity-validation.d.ts +9 -0
  69. package/dist/core/errors.d.ts +24 -0
  70. package/dist/core/execution-demand.d.ts +11 -0
  71. package/dist/core/execution-sound.d.ts +10 -0
  72. package/dist/core/exit-level-draft.d.ts +9 -0
  73. package/dist/core/exit-level-summary.d.ts +3 -0
  74. package/dist/core/exit-level-template.d.ts +16 -0
  75. package/dist/core/features.d.ts +39 -0
  76. package/dist/core/financial-rules.d.ts +70 -0
  77. package/dist/core/history-limit.d.ts +11 -0
  78. package/dist/core/identity.d.ts +14 -0
  79. package/dist/core/immutable.d.ts +8 -0
  80. package/dist/core/keyed-ref-count.d.ts +18 -0
  81. package/dist/core/leverage-commands.d.ts +42 -0
  82. package/dist/core/modification-context.d.ts +22 -0
  83. package/dist/core/modification-routing.d.ts +43 -0
  84. package/dist/core/notification-log.d.ts +33 -0
  85. package/dist/core/number-precision.d.ts +4 -0
  86. package/dist/core/order-commands.d.ts +50 -0
  87. package/dist/core/order-duration.d.ts +14 -0
  88. package/dist/core/order-labels.d.ts +7 -0
  89. package/dist/core/order-matching.d.ts +16 -0
  90. package/dist/core/order-modification.d.ts +20 -0
  91. package/dist/core/order-notifications.d.ts +30 -0
  92. package/dist/core/order-protection.d.ts +4 -0
  93. package/dist/core/parent-protection.d.ts +10 -0
  94. package/dist/core/position-commands.d.ts +45 -0
  95. package/dist/core/position-custom-fields.d.ts +5 -0
  96. package/dist/core/position-estimates.d.ts +22 -0
  97. package/dist/core/position-protection-permissions.d.ts +4 -0
  98. package/dist/core/preferences-key.d.ts +2 -0
  99. package/dist/core/preview-leases.d.ts +12 -0
  100. package/dist/core/protection-legs.d.ts +23 -0
  101. package/dist/core/protection-notifications.d.ts +9 -0
  102. package/dist/core/protection-rules.d.ts +21 -0
  103. package/dist/core/quantity-input.d.ts +53 -0
  104. package/dist/core/read-coordinator.d.ts +15 -0
  105. package/dist/core/readers.d.ts +6 -0
  106. package/dist/core/relative-price.d.ts +4 -0
  107. package/dist/core/review-policy.d.ts +17 -0
  108. package/dist/core/session-types.d.ts +1 -0
  109. package/dist/core/session.d.ts +114 -0
  110. package/dist/core/snapshot-dataset.d.ts +47 -0
  111. package/dist/core/symbol-catalog.d.ts +37 -0
  112. package/dist/core/tradability.d.ts +26 -0
  113. package/dist/core/trading-commands.d.ts +104 -0
  114. package/dist/core/trading-rules.d.ts +14 -0
  115. package/dist/core/trading-settings.d.ts +39 -0
  116. package/dist/core/trading-state.d.ts +52 -0
  117. package/dist/core/value-store.d.ts +11 -0
  118. package/dist/index.d.ts +15 -0
  119. package/dist/index.js +6593 -0
  120. package/dist/market-data/depth-book.d.ts +18 -0
  121. package/dist/market-data/index.d.ts +3 -0
  122. package/dist/market-data/index.js +735 -0
  123. package/dist/market-data/session-demand.d.ts +15 -0
  124. package/dist/market-data/subscriptions.d.ts +13 -0
  125. package/dist/mock/broker.d.ts +75 -0
  126. package/dist/mock/clock.d.ts +12 -0
  127. package/dist/mock/feeds.d.ts +18 -0
  128. package/dist/mock/index.d.ts +5 -0
  129. package/dist/mock/index.js +1956 -0
  130. package/dist/mock/protection-cancellation.d.ts +7 -0
  131. package/dist/mock/scenarios.d.ts +5 -0
  132. package/dist/paper/broker.d.ts +41 -0
  133. package/dist/paper/index.d.ts +6 -0
  134. package/dist/paper/index.js +469 -0
  135. package/dist/paper/market.d.ts +57 -0
  136. package/dist/paper/rules.d.ts +40 -0
  137. package/dist/ui/account-manager/account-pages.d.ts +18 -0
  138. package/dist/ui/account-manager/column-presentation.d.ts +5 -0
  139. package/dist/ui/account-manager/context-menu.d.ts +13 -0
  140. package/dist/ui/account-manager/csv-downloads.d.ts +5 -0
  141. package/dist/ui/account-manager/custom-page.d.ts +16 -0
  142. package/dist/ui/account-manager/custom-table.d.ts +18 -0
  143. package/dist/ui/account-manager/format-account-value.d.ts +12 -0
  144. package/dist/ui/account-manager/position-reader.d.ts +19 -0
  145. package/dist/ui/account-manager/row-action-tracker.d.ts +12 -0
  146. package/dist/ui/account-manager/row-actions.d.ts +37 -0
  147. package/dist/ui/account-manager/status-counts.d.ts +6 -0
  148. package/dist/ui/account-manager/table-controls.d.ts +13 -0
  149. package/dist/ui/account-manager/table-export.d.ts +30 -0
  150. package/dist/ui/account-manager/table-model.d.ts +11 -0
  151. package/dist/ui/account-manager/table-toolbar.d.ts +25 -0
  152. package/dist/ui/account-manager/table.d.ts +24 -0
  153. package/dist/ui/account-manager/view.d.ts +19 -0
  154. package/dist/ui/account-manager/workspace.d.ts +15 -0
  155. package/dist/ui/chart-actions.d.ts +11 -0
  156. package/dist/ui/chart-controls/eligibility.d.ts +6 -0
  157. package/dist/ui/chart-controls/quote-buttons.d.ts +15 -0
  158. package/dist/ui/chart-controls/quote-controls.d.ts +12 -0
  159. package/dist/ui/chart-controls/quote-widths.d.ts +8 -0
  160. package/dist/ui/dialogs/close-amount-form.d.ts +8 -0
  161. package/dist/ui/dialogs/close-preview-dialog.d.ts +5 -0
  162. package/dist/ui/dialogs/confirm-dialog.d.ts +7 -0
  163. package/dist/ui/dialogs/dialog-body.d.ts +11 -0
  164. package/dist/ui/dialogs/leverage-form.d.ts +10 -0
  165. package/dist/ui/dialogs/message-dialog.d.ts +6 -0
  166. package/dist/ui/dialogs/position-protection.d.ts +14 -0
  167. package/dist/ui/dialogs/properties-dialog.d.ts +9 -0
  168. package/dist/ui/dialogs/sanitize-html.d.ts +2 -0
  169. package/dist/ui/dialogs/types.d.ts +5 -0
  170. package/dist/ui/dialogs/view.d.ts +5 -0
  171. package/dist/ui/dock-sizes.d.ts +20 -0
  172. package/dist/ui/dom/controller.d.ts +34 -0
  173. package/dist/ui/dom/ladder.d.ts +23 -0
  174. package/dist/ui/dom/view.d.ts +8 -0
  175. package/dist/ui/dom/workspace.d.ts +17 -0
  176. package/dist/ui/effective-mode.d.ts +11 -0
  177. package/dist/ui/financial-lease.d.ts +3 -0
  178. package/dist/ui/icons.d.ts +4 -0
  179. package/dist/ui/index.d.ts +9 -0
  180. package/dist/ui/index.js +15918 -0
  181. package/dist/ui/layout.d.ts +5 -0
  182. package/dist/ui/mount.d.ts +11 -0
  183. package/dist/ui/notifications/log.d.ts +6 -0
  184. package/dist/ui/notifications/toasts.d.ts +5 -0
  185. package/dist/ui/number-input.d.ts +2 -0
  186. package/dist/ui/order-ticket/chart-draft-controls.d.ts +8 -0
  187. package/dist/ui/order-ticket/chart-projection.d.ts +9 -0
  188. package/dist/ui/order-ticket/controller.d.ts +41 -0
  189. package/dist/ui/order-ticket/custom-field.d.ts +9 -0
  190. package/dist/ui/order-ticket/duration-input.d.ts +9 -0
  191. package/dist/ui/order-ticket/exit-input.d.ts +34 -0
  192. package/dist/ui/order-ticket/financial-controls.d.ts +10 -0
  193. package/dist/ui/order-ticket/layout-context.d.ts +7 -0
  194. package/dist/ui/order-ticket/market.d.ts +12 -0
  195. package/dist/ui/order-ticket/menu.d.ts +6 -0
  196. package/dist/ui/order-ticket/mode-rules.d.ts +4 -0
  197. package/dist/ui/order-ticket/modification-fields.d.ts +23 -0
  198. package/dist/ui/order-ticket/move-handle.d.ts +4 -0
  199. package/dist/ui/order-ticket/order-sent.d.ts +4 -0
  200. package/dist/ui/order-ticket/placement.d.ts +27 -0
  201. package/dist/ui/order-ticket/preview-message.d.ts +4 -0
  202. package/dist/ui/order-ticket/price-input.d.ts +14 -0
  203. package/dist/ui/order-ticket/quantity-input.d.ts +26 -0
  204. package/dist/ui/order-ticket/review-panel.d.ts +10 -0
  205. package/dist/ui/order-ticket/rules.d.ts +16 -0
  206. package/dist/ui/order-ticket/stop-input.d.ts +17 -0
  207. package/dist/ui/order-ticket/submit-bar.d.ts +13 -0
  208. package/dist/ui/order-ticket/symbol-search-controller.d.ts +50 -0
  209. package/dist/ui/order-ticket/symbol-search.d.ts +12 -0
  210. package/dist/ui/order-ticket/untradable-notice.d.ts +8 -0
  211. package/dist/ui/order-ticket/view.d.ts +16 -0
  212. package/dist/ui/panel-visibility.d.ts +6 -0
  213. package/dist/ui/pointer-drag.d.ts +20 -0
  214. package/dist/ui/popup-mount.d.ts +4 -0
  215. package/dist/ui/primitives.d.ts +29 -0
  216. package/dist/ui/protection/editor.d.ts +18 -0
  217. package/dist/ui/protection/fields.d.ts +30 -0
  218. package/dist/ui/protection/level.d.ts +14 -0
  219. package/dist/ui/protection/protected-size.d.ts +5 -0
  220. package/dist/ui/protection/ticket-workspace.d.ts +7 -0
  221. package/dist/ui/resize-handle.css +34 -0
  222. package/dist/ui/resize-handle.d.ts +20 -0
  223. package/dist/ui/resize-handle.js +185 -0
  224. package/dist/ui/select.d.ts +26 -0
  225. package/dist/ui/surface-theme.d.ts +3 -0
  226. package/dist/ui/switch.d.ts +7 -0
  227. package/dist/ui/symbol-logo.d.ts +7 -0
  228. package/dist/ui/tabs.d.ts +19 -0
  229. package/dist/ui/ticket-dock.d.ts +18 -0
  230. package/dist/ui/ticket-shell.d.ts +15 -0
  231. package/dist/ui/trading.css +1808 -0
  232. package/dist/ui/trap-tab.d.ts +11 -0
  233. package/dist/vendor/solid-ui/index.d.ts +3 -0
  234. package/dist/vendor/solid-ui/paged-list-window.d.ts +27 -0
  235. package/dist/vendor/solid-ui/virtual-list.d.ts +21 -0
  236. package/package.json +104 -3
@@ -0,0 +1,1956 @@
1
+ // src/mock/clock.ts
2
+ var SimulationClock = class {
3
+ time;
4
+ sequence = 0;
5
+ timers = /* @__PURE__ */ new Map();
6
+ constructor(start = 17e11) {
7
+ this.time = start;
8
+ }
9
+ now() {
10
+ return this.time;
11
+ }
12
+ setTimeout(callback, milliseconds) {
13
+ const id = ++this.sequence;
14
+ this.timers.set(id, { at: this.time + milliseconds, callback });
15
+ return id;
16
+ }
17
+ clearTimeout(handle) {
18
+ this.timers.delete(handle);
19
+ }
20
+ advance(milliseconds) {
21
+ if (!Number.isFinite(milliseconds) || milliseconds < 0) throw new Error("Advance requires a nonnegative duration.");
22
+ const target = this.time + milliseconds;
23
+ while (true) {
24
+ const next = [...this.timers].filter(([, value]) => value.at <= target).sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
25
+ if (!next) break;
26
+ this.time = next[1].at;
27
+ this.timers.delete(next[0]);
28
+ next[1].callback();
29
+ }
30
+ this.time = target;
31
+ }
32
+ };
33
+
34
+ // src/mock/scenarios.ts
35
+ var simulationProfiles = ["equity-net", "equity-estimates", "fx-netting", "fx-multiposition", "crypto", "custom-ui", "failure-lab"];
36
+ function simulationInstrument(profile) {
37
+ const forex = profile.startsWith("fx-");
38
+ const crypto2 = profile === "crypto";
39
+ const pipSize = forex ? 0.1 : 0.01;
40
+ return {
41
+ description: "Simulated instrument",
42
+ qty: { min: 1, max: 1e4, step: 1, default: 2 },
43
+ minTick: 0.01,
44
+ pipSize,
45
+ pipValue: pipSize,
46
+ type: forex ? "forex" : crypto2 ? "crypto" : "stock",
47
+ currency: "USD",
48
+ baseCurrency: crypto2 ? "SIM" : void 0,
49
+ quoteCurrency: crypto2 ? "USD" : void 0,
50
+ marginRate: 0.1,
51
+ leverage: "10",
52
+ brokerSymbol: "SIM:X",
53
+ allowedOrderTypes: [2 /* Market */, 1 /* Limit */, 3 /* Stop */, 4 /* StopLimit */]
54
+ };
55
+ }
56
+ function simulationConfig(profile) {
57
+ return {
58
+ configFlags: {
59
+ supportPLUpdate: profile !== "equity-estimates",
60
+ supportStopLimitOrders: true,
61
+ supportOrderBrackets: true,
62
+ supportPositionBrackets: profile !== "fx-netting",
63
+ supportIndividualPositionBrackets: profile === "fx-netting",
64
+ supportPositionNetting: profile === "fx-netting",
65
+ supportMultiposition: profile === "fx-multiposition",
66
+ supportClosePosition: true,
67
+ supportCloseIndividualPosition: true,
68
+ supportPartialClosePosition: true,
69
+ supportPartialCloseIndividualPosition: true,
70
+ supportReversePosition: true,
71
+ supportNativeReversePosition: true,
72
+ supportLevel2Data: true,
73
+ supportMargin: true,
74
+ supportLeverage: true,
75
+ supportModifyDuration: true,
76
+ supportModifyOrderType: true,
77
+ supportTrailingStop: true,
78
+ supportGuaranteedStop: true,
79
+ supportMultipleExitLevels: true,
80
+ supportUnpairedExitLevels: true,
81
+ supportCryptoExchangeOrderTicket: profile === "crypto",
82
+ supportBalances: profile === "crypto",
83
+ supportCustomOrderInfo: true
84
+ },
85
+ durations: [
86
+ { name: "Good until cancelled", value: "GTC", default: true },
87
+ { name: "Good until date", value: "GTD", hasDatePicker: true, hasTimePicker: true }
88
+ ],
89
+ tradedGroupConfig: { supportAdaptiveLayout: true }
90
+ };
91
+ }
92
+
93
+ // src/core/keyed-ref-count.ts
94
+ function releaseAll(releases) {
95
+ let failed = false, first;
96
+ for (const release of releases) {
97
+ try {
98
+ release();
99
+ } catch (cause) {
100
+ if (!failed) first = cause;
101
+ failed = true;
102
+ }
103
+ }
104
+ if (failed) throw first;
105
+ }
106
+ var KeyedRefCount = class {
107
+ constructor(dispose) {
108
+ this.dispose = dispose;
109
+ }
110
+ dispose;
111
+ entries = /* @__PURE__ */ new Map();
112
+ get(key) {
113
+ return this.entries.get(key)?.value;
114
+ }
115
+ *values() {
116
+ for (const entry of this.entries.values()) yield entry.value;
117
+ }
118
+ *[Symbol.iterator]() {
119
+ for (const [key, entry] of this.entries) yield [key, entry.value];
120
+ }
121
+ acquire(key, create, owner = /* @__PURE__ */ Symbol()) {
122
+ let entry = this.entries.get(key);
123
+ const first = !entry;
124
+ if (!entry) {
125
+ entry = { value: create(), owners: /* @__PURE__ */ new Set() };
126
+ this.entries.set(key, entry);
127
+ }
128
+ const retained = entry;
129
+ retained.owners.add(owner);
130
+ let owned = true;
131
+ return {
132
+ value: retained.value,
133
+ first,
134
+ release: () => {
135
+ if (!owned) return;
136
+ owned = false;
137
+ if (this.entries.get(key) !== retained || !retained.owners.delete(owner) || retained.owners.size) return;
138
+ this.entries.delete(key);
139
+ this.dispose(retained.value, key);
140
+ }
141
+ };
142
+ }
143
+ releaseAll() {
144
+ const entries = [...this.entries];
145
+ this.entries.clear();
146
+ releaseAll(entries.map(([key, entry]) => () => this.dispose(entry.value, key)));
147
+ }
148
+ };
149
+
150
+ // src/core/errors.ts
151
+ var TradingError = class _TradingError extends Error {
152
+ constructor(code, message, options) {
153
+ super(message, options);
154
+ this.code = code;
155
+ this.name = "TradingError";
156
+ }
157
+ code;
158
+ static disposed(message = "This trading session is closed.") {
159
+ return new _TradingError("disposed", message);
160
+ }
161
+ static accountChanged() {
162
+ return new _TradingError("stale-context", "The trading account changed.");
163
+ }
164
+ static disconnected() {
165
+ return new _TradingError("disconnected", "Reconnect before trading.");
166
+ }
167
+ static brokerUnavailable() {
168
+ return new _TradingError("broker-unavailable", "The broker is unavailable.");
169
+ }
170
+ static positionChanged() {
171
+ return new _TradingError("stale-context", "This position changed. Review its current details.");
172
+ }
173
+ };
174
+
175
+ // src/core/immutable.ts
176
+ function ordinaryRecordPrototype(prototype) {
177
+ if (prototype === null || prototype === Object.prototype) return true;
178
+ if (Object.getPrototypeOf(prototype) !== null) return false;
179
+ const constructor = Object.getOwnPropertyDescriptor(prototype, "constructor");
180
+ return !!constructor && "value" in constructor && typeof constructor.value === "function" && Function.prototype.toString.call(constructor.value) === Function.prototype.toString.call(Object);
181
+ }
182
+ var produced = /* @__PURE__ */ new WeakSet();
183
+ function copyData(value, ancestors) {
184
+ if (value === null || value === void 0 || ["string", "number", "boolean", "bigint"].includes(typeof value))
185
+ return value;
186
+ if (typeof value === "object" && produced.has(value)) return value;
187
+ if (typeof value !== "object")
188
+ throw new TradingError(
189
+ "invalid-input",
190
+ "Broker data cannot contain executable values."
191
+ );
192
+ const prototype = Object.getPrototypeOf(value);
193
+ if (!Array.isArray(value) && !ordinaryRecordPrototype(prototype))
194
+ throw new TradingError(
195
+ "invalid-input",
196
+ "Broker data must contain ordinary records."
197
+ );
198
+ if (ancestors.has(value))
199
+ throw new TradingError(
200
+ "invalid-input",
201
+ "Broker data cannot contain circular records."
202
+ );
203
+ ancestors.add(value);
204
+ const result = Array.isArray(value) ? [] : {};
205
+ for (const key of Object.keys(value)) {
206
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
207
+ if (!descriptor || !("value" in descriptor))
208
+ throw new TradingError(
209
+ "invalid-input",
210
+ "Broker data cannot contain accessors."
211
+ );
212
+ Object.defineProperty(result, key, {
213
+ value: copyData(descriptor.value, ancestors),
214
+ enumerable: true,
215
+ writable: true,
216
+ configurable: true
217
+ });
218
+ }
219
+ ancestors.delete(value);
220
+ Object.freeze(result);
221
+ produced.add(result);
222
+ return result;
223
+ }
224
+ function snapshot(value) {
225
+ return copyData(value, /* @__PURE__ */ new Set());
226
+ }
227
+ function equalData(a, b) {
228
+ if (Object.is(a, b)) return true;
229
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
230
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
231
+ const keys = Object.keys(a);
232
+ if (keys.length !== Object.keys(b).length) return false;
233
+ return keys.every((key) => {
234
+ const left = Object.getOwnPropertyDescriptor(a, key);
235
+ const right = Object.getOwnPropertyDescriptor(b, key);
236
+ return !!left && !!right && "value" in left && "value" in right && equalData(left.value, right.value);
237
+ });
238
+ }
239
+
240
+ // src/core/entity-store.ts
241
+ var EntityStore = class {
242
+ constructor(validate, accept = () => true) {
243
+ this.validate = validate;
244
+ this.accept = accept;
245
+ }
246
+ validate;
247
+ accept;
248
+ entities = /* @__PURE__ */ new Map();
249
+ revisions = /* @__PURE__ */ new Map();
250
+ listeners = /* @__PURE__ */ new Set();
251
+ before = /* @__PURE__ */ new Map();
252
+ idsSnapshot;
253
+ sequence = 0;
254
+ depth = 0;
255
+ disposed = false;
256
+ ids() {
257
+ return this.idsSnapshot ??= Object.freeze([...this.entities.keys()]);
258
+ }
259
+ get(id) {
260
+ return this.entities.get(id);
261
+ }
262
+ // Missing identities share a conservative watermark; deleted IDs never need permanent tombstones.
263
+ revision(id) {
264
+ return this.revisions.get(id) ?? this.sequence;
265
+ }
266
+ subscribeChanges(listener) {
267
+ if (this.disposed) return () => {
268
+ };
269
+ this.listeners.add(listener);
270
+ return () => {
271
+ this.listeners.delete(listener);
272
+ };
273
+ }
274
+ record(id) {
275
+ if (!this.before.has(id)) this.before.set(id, this.entities.get(id));
276
+ }
277
+ upsert(entity, authoritative = false) {
278
+ if (this.disposed) return false;
279
+ this.validate(entity);
280
+ const old = this.entities.get(entity.id);
281
+ if (!authoritative && !this.accept(entity, old) || equalData(old, entity))
282
+ return false;
283
+ const next = snapshot(entity);
284
+ this.record(entity.id);
285
+ this.entities.set(entity.id, next);
286
+ this.revisions.set(entity.id, ++this.sequence);
287
+ if (!old) this.idsSnapshot = void 0;
288
+ this.publish();
289
+ return true;
290
+ }
291
+ patch(id, changes) {
292
+ if (changes.id !== void 0 && changes.id !== id)
293
+ throw new TradingError(
294
+ "invalid-input",
295
+ "An update cannot change its identity."
296
+ );
297
+ const old = this.entities.get(id);
298
+ if (!old) return false;
299
+ return this.upsert({ ...old, ...changes, id });
300
+ }
301
+ remove(id) {
302
+ if (this.disposed || !this.entities.has(id)) return false;
303
+ this.record(id);
304
+ this.entities.delete(id);
305
+ this.idsSnapshot = void 0;
306
+ this.revisions.delete(id);
307
+ this.sequence++;
308
+ this.publish();
309
+ return true;
310
+ }
311
+ transaction(operation) {
312
+ this.depth++;
313
+ try {
314
+ operation();
315
+ } finally {
316
+ this.depth--;
317
+ this.publish();
318
+ }
319
+ }
320
+ /**
321
+ * Replaces the snapshot atomically: one malformed row rejects the whole read. With `quarantine`, invalid rows
322
+ * are set aside instead: valid rows commit, a quarantined ID keeps its previous value, and each failure is
323
+ * returned; a read with rows but none valid still fails as a whole.
324
+ */
325
+ replace(entities, options = {}) {
326
+ if (!Array.isArray(entities))
327
+ throw new TradingError("invalid-input", "The broker returned invalid account information.");
328
+ const incoming = /* @__PURE__ */ new Map();
329
+ const seen = /* @__PURE__ */ new Set();
330
+ const quarantined = [];
331
+ let valid = 0;
332
+ for (const entity of entities) {
333
+ const id = entity && typeof entity === "object" && typeof entity.id === "string" ? entity.id : void 0;
334
+ try {
335
+ this.validate(entity);
336
+ if (seen.has(entity.id))
337
+ throw new TradingError("invalid-input", "The broker returned duplicate identities.");
338
+ seen.add(entity.id);
339
+ if (!options.accept || options.accept(entity)) incoming.set(entity.id, snapshot(entity));
340
+ valid++;
341
+ } catch (cause) {
342
+ if (!options.quarantine) throw cause;
343
+ quarantined.push({ ...id !== void 0 ? { id } : {}, message: cause instanceof Error ? cause.message : String(cause) });
344
+ }
345
+ }
346
+ if (quarantined.length && !valid)
347
+ throw new TradingError("invalid-input", "The broker returned invalid account information.");
348
+ const kept = new Set(
349
+ quarantined.flatMap((row) => row.id !== void 0 && !options.expire?.has(row.id) ? [row.id] : [])
350
+ );
351
+ this.transaction(() => {
352
+ for (const id of this.entities.keys())
353
+ if (!incoming.has(id) && !kept.has(id)) this.remove(id);
354
+ for (const entity of incoming.values()) this.upsert(entity, true);
355
+ });
356
+ return quarantined;
357
+ }
358
+ publish() {
359
+ if (this.depth || !this.before.size) return;
360
+ const added = [], updated = [], removed = [];
361
+ for (const [id, old] of this.before) {
362
+ const next = this.entities.get(id);
363
+ if (equalData(old, next)) continue;
364
+ if (!next) removed.push(id);
365
+ else if (!old) added.push(id);
366
+ else updated.push(id);
367
+ }
368
+ this.before.clear();
369
+ if (!added.length && !updated.length && !removed.length) return;
370
+ const change = Object.freeze({
371
+ added: Object.freeze(added),
372
+ updated: Object.freeze(updated),
373
+ removed: Object.freeze(removed),
374
+ revision: this.sequence
375
+ });
376
+ for (const listener of [...this.listeners]) {
377
+ if (this.disposed) break;
378
+ if (this.listeners.has(listener)) listener(change);
379
+ }
380
+ }
381
+ destroy() {
382
+ this.disposed = true;
383
+ this.listeners.clear();
384
+ this.before.clear();
385
+ this.entities.clear();
386
+ this.revisions.clear();
387
+ this.idsSnapshot = Object.freeze([]);
388
+ }
389
+ };
390
+
391
+ // src/core/capability-metadata.ts
392
+ var defaultFlags = Object.freeze({
393
+ "showQuantityInsteadOfAmount": false,
394
+ "supportOrderBrackets": false,
395
+ "supportStopLoss": true,
396
+ "supportTrailingStop": false,
397
+ "supportGuaranteedStop": false,
398
+ "supportPositions": true,
399
+ "supportPositionBrackets": false,
400
+ "supportIndividualPositionBrackets": false,
401
+ "supportPositionNetting": false,
402
+ "supportClosePosition": false,
403
+ "supportCloseIndividualPosition": false,
404
+ "supportModifyOrderPrice": true,
405
+ "supportEditAmount": true,
406
+ "supportModifyBrackets": true,
407
+ "supportLevel2Data": false,
408
+ "supportMultiposition": false,
409
+ "supportPLUpdate": true,
410
+ "supportReversePosition": false,
411
+ "supportNativeReversePosition": false,
412
+ "supportMarketOrders": true,
413
+ "supportLimitOrders": true,
414
+ "supportStopOrders": true,
415
+ "supportStopLimitOrders": false,
416
+ "supportDemoLiveSwitcher": true,
417
+ "supportMarketBrackets": true,
418
+ "supportSymbolSearch": false,
419
+ "supportModifyDuration": false,
420
+ "supportModifyTrailingStop": true,
421
+ "supportMargin": false,
422
+ "supportPlaceOrderPreview": false,
423
+ "supportModifyOrderPreview": false,
424
+ "supportLeverage": false,
425
+ "supportLeverageButton": true,
426
+ "supportOrdersHistory": true,
427
+ "supportAddBracketsToExistingOrder": true,
428
+ "supportBalances": false,
429
+ "closePositionCancelsOrders": false,
430
+ "supportOnlyPairPositionBrackets": false,
431
+ "supportOnlyPairOrderBrackets": false,
432
+ "supportCryptoExchangeOrderTicket": false,
433
+ "supportSymbolSpecificCryptoOrderTicket": false,
434
+ "positionPLInInstrumentCurrency": false,
435
+ "showRiskInInstrumentCurrency": false,
436
+ "supportPartialClosePosition": false,
437
+ "supportPartialCloseIndividualPosition": false,
438
+ "supportCancellingBothBracketsOnly": false,
439
+ "supportCryptoBrackets": false,
440
+ "showNotificationsLog": true,
441
+ "supportStopOrdersInBothDirections": false,
442
+ "supportStopLimitOrdersInBothDirections": false,
443
+ "supportStrictCheckingLimitOrderPrice": false,
444
+ "supportExecutions": true,
445
+ "supportModifyOrderType": false,
446
+ "requiresFIFOCloseIndividualPositions": false,
447
+ "supportMultipleExitLevels": false,
448
+ "supportUnpairedExitLevels": false,
449
+ "supportCustomOrderInfo": false,
450
+ "supportPreviewClosePosition": false
451
+ });
452
+
453
+ // src/core/entity-validation.ts
454
+ var terminalStatuses = /* @__PURE__ */ new Set([1 /* Canceled */, 2 /* Filled */, 5 /* Rejected */]);
455
+ function finite(value, name) {
456
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new TradingError("invalid-input", `Invalid ${name}.`);
457
+ }
458
+
459
+ // src/core/trading-rules.ts
460
+ function decimal(value) {
461
+ finite(value, "number");
462
+ const [mantissa, exponentText] = String(value).toLowerCase().split("e");
463
+ const [whole, fractional = ""] = mantissa.split(".");
464
+ const exponent = Number(exponentText ?? 0) - fractional.length;
465
+ const numerator = BigInt(whole + fractional);
466
+ if (exponent >= 0)
467
+ return { numerator: numerator * 10n ** BigInt(exponent), denominator: 1n };
468
+ return { numerator, denominator: 10n ** BigInt(-exponent) };
469
+ }
470
+ function aligned(value, step) {
471
+ if (!Number.isFinite(value) || !Number.isFinite(step) || step <= 0)
472
+ return false;
473
+ const a = decimal(value), b = decimal(step);
474
+ return a.numerator * b.denominator % (a.denominator * b.numerator) === 0n;
475
+ }
476
+ function snapToStep(value, step) {
477
+ finite(value, "price");
478
+ finite(step, "price step");
479
+ if (step <= 0) throw new TradingError("invalid-input", "Invalid price step.");
480
+ const a = decimal(value), b = decimal(step);
481
+ const numerator = a.numerator * b.denominator, denominator = a.denominator * b.numerator;
482
+ const negative = numerator < 0n;
483
+ const absolute = negative ? -numerator : numerator;
484
+ const rounded = (absolute * 2n + denominator) / (denominator * 2n);
485
+ return Number((negative ? -rounded : rounded) * b.numerator) / Number(b.denominator);
486
+ }
487
+ function validateQuantity(quantity, rules) {
488
+ finite(quantity, "quantity");
489
+ if (quantity <= 0 || quantity < rules.min || quantity > rules.max || !aligned(quantity, rules.step))
490
+ throw new TradingError(
491
+ "invalid-input",
492
+ "Enter a quantity within the allowed range and step."
493
+ );
494
+ }
495
+
496
+ // src/market-data/depth-book.ts
497
+ var DepthBook = class {
498
+ constructor(tick) {
499
+ this.tick = tick;
500
+ }
501
+ tick;
502
+ bids = new EntityStore(() => {
503
+ });
504
+ asks = new EntityStore(() => {
505
+ });
506
+ initialized = false;
507
+ buffered = [];
508
+ normalize(levels) {
509
+ const normalized = /* @__PURE__ */ new Map();
510
+ for (const level of levels) {
511
+ if (!Number.isFinite(level.price) || !Number.isFinite(level.volume) || level.volume < 0) throw new TradingError("invalid-input", "Invalid depth level.");
512
+ const price = snapToStep(level.price, this.tick);
513
+ normalized.set(String(price), { id: String(price), price, volume: level.volume });
514
+ }
515
+ return [...normalized.values()];
516
+ }
517
+ apply(data) {
518
+ const bids = this.normalize(data.bids), asks = this.normalize(data.asks);
519
+ if (!this.initialized && !data.snapshot) {
520
+ this.buffered.push({ snapshot: false, bids, asks });
521
+ if (this.buffered.length > 1e3) {
522
+ this.buffered = [];
523
+ throw new TradingError("broker-unavailable", "Depth needs a fresh snapshot.");
524
+ }
525
+ return void 0;
526
+ }
527
+ if (data.snapshot) {
528
+ this.initialized = true;
529
+ this.buffered = [];
530
+ this.bids.transaction(() => this.asks.transaction(() => {
531
+ this.bids.replace(bids.filter((level) => level.volume > 0));
532
+ this.asks.replace(asks.filter((level) => level.volume > 0));
533
+ }));
534
+ } else {
535
+ for (const [store, levels] of [[this.bids, bids], [this.asks, asks]]) store.transaction(() => {
536
+ for (const level of levels) {
537
+ if (level.volume === 0) store.remove(level.id);
538
+ else store.upsert(level);
539
+ }
540
+ });
541
+ }
542
+ return Object.freeze({ snapshot: data.snapshot, bids: Object.freeze(bids.sort((a, b) => a.price - b.price)), asks: Object.freeze(asks.sort((a, b) => a.price - b.price)) });
543
+ }
544
+ snapshot() {
545
+ if (!this.initialized) return void 0;
546
+ const rows = (store) => store.ids().map((id) => store.get(id)).sort((a, b) => a.price - b.price);
547
+ return Object.freeze({ snapshot: true, bids: Object.freeze(rows(this.bids)), asks: Object.freeze(rows(this.asks)) });
548
+ }
549
+ destroy() {
550
+ this.bids.destroy();
551
+ this.asks.destroy();
552
+ this.buffered = [];
553
+ }
554
+ };
555
+
556
+ // src/market-data/subscriptions.ts
557
+ function normalizeQuotes(data) {
558
+ const result = {};
559
+ for (const key of [
560
+ "trade",
561
+ "size",
562
+ "bid",
563
+ "bid_size",
564
+ "ask",
565
+ "ask_size",
566
+ "spread",
567
+ "lastSize"
568
+ ]) {
569
+ const value = data[key];
570
+ if (value === void 0) continue;
571
+ if (typeof value !== "number" || !Number.isFinite(value))
572
+ throw new TradingError("invalid-input", `Invalid quote ${key}.`);
573
+ result[key] = value;
574
+ }
575
+ for (const key of [
576
+ "isDelayed",
577
+ "isHalted",
578
+ "isHardToBorrow",
579
+ "isNotShortable"
580
+ ]) {
581
+ const value = data[key];
582
+ if (value === void 0) continue;
583
+ if (typeof value !== "boolean")
584
+ throw new TradingError("invalid-input", `Invalid quote ${key}.`);
585
+ result[key] = value;
586
+ }
587
+ return snapshot(result);
588
+ }
589
+ function quoteValues(data) {
590
+ if (data.s === "error")
591
+ return Object.freeze({
592
+ status: "error",
593
+ error: "Quotes are unavailable for this symbol."
594
+ });
595
+ const values = {};
596
+ for (const key of ["bid", "ask", "spread"])
597
+ if (data.v[key] !== void 0) values[key] = data.v[key];
598
+ if (data.v.lp !== void 0) values.trade = data.v.lp;
599
+ return Object.freeze({ status: "ready", value: normalizeQuotes(values) });
600
+ }
601
+ function createTradingMarketData(provider, tickForSymbol, diagnostic = () => {
602
+ }) {
603
+ const quotes = new KeyedRefCount((demand) => {
604
+ demand.epoch++;
605
+ releaseAll([() => {
606
+ if (demand.guid) provider.unsubscribeQuotes?.(demand.guid);
607
+ }, () => demand.listeners.clear()]);
608
+ });
609
+ const depth = new KeyedRefCount((demand) => {
610
+ demand.epoch++;
611
+ releaseAll([
612
+ () => {
613
+ if (demand.guid) provider.unsubscribeDepth?.(demand.guid);
614
+ },
615
+ () => demand.listeners.clear(),
616
+ () => demand.book.destroy()
617
+ ]);
618
+ });
619
+ const namespace = crypto.randomUUID();
620
+ let sequence = 0;
621
+ let disposed = false;
622
+ function publish(demand, value) {
623
+ if (value.status === "ready" && value.value) {
624
+ demand.latest = normalizeQuotes({ ...demand.latest, ...value.value });
625
+ value = Object.freeze({ ...value, value: demand.latest });
626
+ }
627
+ if (equalData(demand.current, value)) return;
628
+ demand.current = value;
629
+ for (const listener of [...demand.listeners.values()])
630
+ listener.callback(value);
631
+ }
632
+ function schedule(symbol, demand) {
633
+ if (demand.queued) return;
634
+ demand.queued = true;
635
+ queueMicrotask(() => {
636
+ demand.queued = false;
637
+ if (disposed || quotes.get(symbol) !== demand) return;
638
+ const speed = [...demand.listeners.values()].some(
639
+ (listener) => listener.speed === "fast"
640
+ ) ? "fast" : "normal";
641
+ if (demand.guid && demand.speed === speed) return;
642
+ demand.epoch++;
643
+ if (demand.guid) provider.unsubscribeQuotes?.(demand.guid);
644
+ demand.guid = void 0;
645
+ demand.speed = speed;
646
+ if (!provider.getQuotes || !provider.subscribeQuotes || !provider.unsubscribeQuotes) {
647
+ publish(demand, {
648
+ status: "error",
649
+ source: "snapshot",
650
+ error: "Live quotes are unavailable."
651
+ });
652
+ return;
653
+ }
654
+ const epoch = demand.epoch;
655
+ const guid = `${namespace}:quotes:${++sequence}`;
656
+ demand.guid = guid;
657
+ const live = () => !disposed && quotes.get(symbol) === demand && demand.epoch === epoch;
658
+ let initial = true;
659
+ const initialArrival = demand.arrival;
660
+ const apply = (rows, source) => {
661
+ if (!live()) return;
662
+ for (const row of rows)
663
+ if (row.n === symbol) {
664
+ try {
665
+ publish(demand, { ...quoteValues(row), source });
666
+ } catch (cause) {
667
+ publish(demand, {
668
+ status: "error",
669
+ source,
670
+ error: "The provider returned invalid quotes."
671
+ });
672
+ diagnostic(String(cause));
673
+ }
674
+ }
675
+ };
676
+ const finish = (rows, error) => {
677
+ if (!live() || !initial) return;
678
+ initial = false;
679
+ if (demand.arrival !== initialArrival) return;
680
+ if (error)
681
+ publish(demand, { status: "error", source: "snapshot", error });
682
+ else apply(rows, "snapshot");
683
+ };
684
+ try {
685
+ provider.subscribeQuotes(
686
+ speed === "normal" ? [symbol] : [],
687
+ speed === "fast" ? [symbol] : [],
688
+ (rows) => {
689
+ if (!live()) return;
690
+ for (const row of rows) {
691
+ if (row.n !== symbol) continue;
692
+ demand.arrival++;
693
+ apply([row], "stream");
694
+ }
695
+ },
696
+ guid
697
+ );
698
+ provider.getQuotes(
699
+ [symbol],
700
+ (rows) => finish(rows),
701
+ () => finish([], "Quotes are unavailable.")
702
+ );
703
+ } catch (cause) {
704
+ finish([], "Live quotes are unavailable.");
705
+ diagnostic(String(cause));
706
+ }
707
+ });
708
+ }
709
+ function startDepth(symbol, demand) {
710
+ if (disposed || depth.get(symbol) !== demand) return;
711
+ if (!provider.subscribeDepth || !provider.unsubscribeDepth)
712
+ throw new TradingError("unsupported", "Depth of Market is unavailable.");
713
+ const epoch = ++demand.epoch;
714
+ demand.starting = true;
715
+ let guid;
716
+ try {
717
+ guid = subscribeDepth(symbol, epoch, demand);
718
+ } finally {
719
+ demand.starting = false;
720
+ }
721
+ if (disposed || depth.get(symbol) !== demand)
722
+ provider.unsubscribeDepth(guid);
723
+ else demand.guid = guid;
724
+ }
725
+ function subscribeDepth(symbol, epoch, demand) {
726
+ return provider.subscribeDepth(symbol, (data) => {
727
+ if (disposed || depth.get(symbol) !== demand || demand.epoch !== epoch)
728
+ return;
729
+ try {
730
+ const normalized = demand.book.apply(data);
731
+ if (normalized)
732
+ for (const listener of [...demand.listeners]) listener(normalized);
733
+ } catch (cause) {
734
+ diagnostic(String(cause));
735
+ if (cause instanceof TradingError && cause.code === "broker-unavailable") {
736
+ demand.epoch++;
737
+ queueMicrotask(() => {
738
+ if (disposed || depth.get(symbol) !== demand) return;
739
+ try {
740
+ if (demand.guid) provider.unsubscribeDepth?.(demand.guid);
741
+ demand.guid = void 0;
742
+ startDepth(symbol, demand);
743
+ } catch (restart) {
744
+ demand.guid = void 0;
745
+ diagnostic(String(restart));
746
+ }
747
+ });
748
+ }
749
+ }
750
+ });
751
+ }
752
+ return {
753
+ acquireQuotes(symbol, speed, callback) {
754
+ if (disposed)
755
+ throw TradingError.disposed("This market-data connection is closed.");
756
+ const lease = quotes.acquire(symbol, () => ({
757
+ listeners: /* @__PURE__ */ new Map(),
758
+ epoch: 0,
759
+ current: { status: "loading", source: "snapshot" },
760
+ queued: false,
761
+ arrival: 0
762
+ }));
763
+ const demand = lease.value;
764
+ const token = /* @__PURE__ */ Symbol();
765
+ demand.listeners.set(token, { speed, callback });
766
+ const owned = demand;
767
+ const release = () => {
768
+ if (!owned.listeners.delete(token)) return;
769
+ lease.release();
770
+ if (owned.listeners.size) schedule(symbol, owned);
771
+ };
772
+ try {
773
+ callback({ ...demand.current, source: "snapshot" });
774
+ schedule(symbol, demand);
775
+ } catch (cause) {
776
+ release();
777
+ throw cause;
778
+ }
779
+ return release;
780
+ },
781
+ acquireDepth(symbol, callback) {
782
+ if (disposed)
783
+ throw TradingError.disposed("This market-data connection is closed.");
784
+ if (!provider.subscribeDepth || !provider.unsubscribeDepth)
785
+ throw new TradingError(
786
+ "unsupported",
787
+ "Depth of Market is unavailable."
788
+ );
789
+ const lease = depth.acquire(symbol, () => ({
790
+ listeners: /* @__PURE__ */ new Set(),
791
+ book: new DepthBook(tickForSymbol(symbol)),
792
+ epoch: 0,
793
+ starting: false
794
+ }), callback);
795
+ const demand = lease.value;
796
+ demand.listeners.add(callback);
797
+ const owned = demand;
798
+ const release = () => {
799
+ if (!owned.listeners.delete(callback)) return;
800
+ lease.release();
801
+ };
802
+ try {
803
+ const current = demand.book.snapshot();
804
+ if (current) callback(current);
805
+ if (!demand.guid && !demand.starting) startDepth(symbol, demand);
806
+ } catch (cause) {
807
+ demand.starting = false;
808
+ release();
809
+ throw cause;
810
+ }
811
+ return release;
812
+ },
813
+ pushQuotes(symbol, value) {
814
+ const demand = quotes.get(symbol);
815
+ if (!disposed && demand) {
816
+ demand.arrival++;
817
+ publish(demand, {
818
+ status: "ready",
819
+ source: "stream",
820
+ value: normalizeQuotes(value)
821
+ });
822
+ }
823
+ },
824
+ pushDepth(symbol, value) {
825
+ const demand = depth.get(symbol);
826
+ if (disposed || !demand) return;
827
+ const normalized = demand.book.apply(value);
828
+ if (normalized)
829
+ for (const listener of [...demand.listeners]) listener(normalized);
830
+ },
831
+ destroy() {
832
+ if (disposed) return;
833
+ disposed = true;
834
+ releaseAll([() => quotes.releaseAll(), () => depth.releaseAll()]);
835
+ }
836
+ };
837
+ }
838
+
839
+ // src/mock/feeds.ts
840
+ function createSimulationFeeds(seed = 1) {
841
+ let randomState = seed >>> 0;
842
+ let sequence = 0;
843
+ const quotes = /* @__PURE__ */ new Map();
844
+ const prices = /* @__PURE__ */ new Map();
845
+ const books = /* @__PURE__ */ new Map();
846
+ const quoteListeners = /* @__PURE__ */ new Map();
847
+ const depthListeners = /* @__PURE__ */ new Map();
848
+ const provider = {
849
+ getQuotes: (symbols, callback) => callback(symbols.map((symbol) => structuredClone(quotes.get(symbol) ?? { n: symbol, s: "error", v: {} }))),
850
+ subscribeQuotes: (symbols, fast, callback, guid) => {
851
+ quoteListeners.set(guid, { symbols: /* @__PURE__ */ new Set([...symbols, ...fast]), callback });
852
+ },
853
+ unsubscribeQuotes: (guid) => {
854
+ quoteListeners.delete(guid);
855
+ },
856
+ subscribeDepth: (symbol, callback) => {
857
+ const id = `simulation-depth-${++sequence}`;
858
+ depthListeners.set(id, { symbol, callback });
859
+ const current = books.get(symbol);
860
+ if (current) callback(structuredClone(current));
861
+ return id;
862
+ },
863
+ unsubscribeDepth: (guid) => {
864
+ depthListeners.delete(guid);
865
+ }
866
+ };
867
+ const marketData = createTradingMarketData(provider, () => 0.01);
868
+ const setQuote = (symbol, price) => {
869
+ const data = { n: symbol, s: "ok", v: { lp: price, bid: price - 0.01, ask: price + 0.01 } };
870
+ quotes.set(symbol, data);
871
+ prices.set(symbol, price);
872
+ for (const listener of quoteListeners.values()) if (listener.symbols.has(symbol)) listener.callback([structuredClone(data)]);
873
+ };
874
+ const setDepth = (symbol, data) => {
875
+ if (data.snapshot) books.set(symbol, structuredClone(data));
876
+ else {
877
+ const old = books.get(symbol) ?? { snapshot: true, bids: [], asks: [] };
878
+ for (const side of ["bids", "asks"]) {
879
+ const levels = new Map(old[side].map((level) => [level.price, level]));
880
+ for (const level of data[side]) {
881
+ if (level.volume === 0) levels.delete(level.price);
882
+ else levels.set(level.price, structuredClone(level));
883
+ }
884
+ old[side] = [...levels.values()].sort((a, b) => a.price - b.price);
885
+ }
886
+ books.set(symbol, old);
887
+ }
888
+ for (const listener of depthListeners.values()) if (listener.symbol === symbol) listener.callback(structuredClone(data));
889
+ };
890
+ setQuote("SIM:X", 100);
891
+ setDepth("SIM:X", { snapshot: true, bids: [{ price: 99.99, volume: 50 }, { price: 99.98, volume: 100 }], asks: [{ price: 100.01, volume: 60 }, { price: 100.02, volume: 120 }] });
892
+ return {
893
+ provider,
894
+ marketData,
895
+ setQuote,
896
+ setDepth,
897
+ /** Last scripted trade price, or undefined while the symbol has no quote. */
898
+ lastPrice: (symbol) => prices.get(symbol),
899
+ quoteError(symbol) {
900
+ const data = { n: symbol, s: "error", v: {} };
901
+ quotes.set(symbol, data);
902
+ for (const listener of quoteListeners.values()) if (listener.symbols.has(symbol)) listener.callback([data]);
903
+ },
904
+ tick(symbol = "SIM:X") {
905
+ randomState = Math.imul(randomState, 1664525) + 1013904223 >>> 0;
906
+ const price = 100 + randomState % 1e3 / 100;
907
+ setQuote(symbol, price);
908
+ return price;
909
+ },
910
+ counts: () => ({ quotes: quoteListeners.size, depth: depthListeners.size }),
911
+ destroy: () => {
912
+ marketData.destroy();
913
+ quoteListeners.clear();
914
+ depthListeners.clear();
915
+ }
916
+ };
917
+ }
918
+
919
+ // src/core/protection-legs.ts
920
+ function childProtectionField(child) {
921
+ if (child.type === 1 /* Limit */) return "takeProfit";
922
+ if (child.type !== 3 /* Stop */) return void 0;
923
+ if (child.stopType === 1 /* TrailingStop */) return "trailingStopPips";
924
+ if (child.stopType === 2 /* GuaranteedStop */) return "guaranteedStop";
925
+ return "stopLoss";
926
+ }
927
+ function childProtectionValue(child, field) {
928
+ if (field === "trailingStopPips") return child.trailingStopPips;
929
+ if (field === "takeProfit") return child.limitPrice;
930
+ return child.stopPrice;
931
+ }
932
+
933
+ // src/core/parent-protection.ts
934
+ function hasProtectionFields(parent) {
935
+ return !!parent.exitLevels?.length || parent.takeProfit !== void 0 || parent.stopLoss !== void 0 || parent.guaranteedStop !== void 0 || parent.trailingStopPips !== void 0;
936
+ }
937
+ var stopFields = ["stopLoss", "guaranteedStop", "trailingStopPips"];
938
+ function stale(message) {
939
+ throw new TradingError("stale-context", message);
940
+ }
941
+ function childGroups(children) {
942
+ const groups = /* @__PURE__ */ new Map();
943
+ for (const child of children) {
944
+ if (!("parentId" in child)) continue;
945
+ let group = groups.get(child.exitLevelId);
946
+ if (!group) {
947
+ group = { qty: child.qty, brackets: {} };
948
+ groups.set(child.exitLevelId, group);
949
+ }
950
+ if (group.qty !== child.qty)
951
+ stale("Protection quantities changed. Review the trade again.");
952
+ const field = childProtectionField(child);
953
+ if (!field)
954
+ throw new TradingError(
955
+ "unsupported",
956
+ "This protection order type cannot be edited."
957
+ );
958
+ const value = childProtectionValue(child, field);
959
+ if (value === void 0 || !Number.isFinite(value) || group.brackets[field] !== void 0)
960
+ stale("Protection details are incomplete. Review the trade again.");
961
+ group.brackets[field] = value;
962
+ }
963
+ return groups;
964
+ }
965
+ function mergeLegs(target, legs) {
966
+ const merged = { ...target };
967
+ const targetStop = stopFields.find((field) => target[field] !== void 0);
968
+ for (const field of Object.keys(legs)) {
969
+ const value = legs[field];
970
+ if (targetStop && field !== targetStop && stopFields.includes(field))
971
+ stale("The stop style changed. Review the trade again.");
972
+ if (target[field] === void 0) merged[field] = value;
973
+ else if (target[field] !== value)
974
+ stale("Protection prices changed. Review the trade again.");
975
+ }
976
+ return merged;
977
+ }
978
+ function completeParentProtection(parent, children) {
979
+ const groups = childGroups(children);
980
+ if (hasProtectionFields(parent)) return reconcileParent(parent, groups);
981
+ if (!groups.size) stale("Protection details are unavailable.");
982
+ const unnamed = groups.get(void 0);
983
+ if (unnamed) {
984
+ if (groups.size !== 1 || unnamed.qty !== parent.qty)
985
+ stale("Allocated protection needs a broker level ID.");
986
+ return { ...parent, ...unnamed.brackets };
987
+ }
988
+ const levels = [...groups].map(([id, group]) => ({
989
+ id,
990
+ qty: group.qty,
991
+ ...group.brackets,
992
+ isExisting: true
993
+ }));
994
+ return { ...parent, exitLevels: levels };
995
+ }
996
+ function reconcileParent(parent, groups) {
997
+ if (!groups.size) return parent;
998
+ const levels = parent.exitLevels;
999
+ if (!levels?.length) {
1000
+ const [[, group], ...rest] = [...groups];
1001
+ if (rest.length || group.qty !== parent.qty)
1002
+ stale("Allocated protection needs current parent levels.");
1003
+ return mergeLegs(parent, group.brackets);
1004
+ }
1005
+ const ids = new Set(levels.map((level) => level.id));
1006
+ for (const id of groups.keys())
1007
+ if (id === void 0 || !ids.has(id))
1008
+ stale("Protection levels changed. Review the trade again.");
1009
+ return {
1010
+ ...parent,
1011
+ exitLevels: levels.map((level) => {
1012
+ const group = groups.get(level.id);
1013
+ if (!group) return level;
1014
+ if (group.qty !== level.qty)
1015
+ stale("Protection quantities changed. Review the trade again.");
1016
+ return mergeLegs(level, group.brackets);
1017
+ })
1018
+ };
1019
+ }
1020
+
1021
+ // src/core/bracket-modification.ts
1022
+ var missingValueMessages = {
1023
+ takeProfit: "Enter a take profit price.",
1024
+ stopLoss: "Enter a stop price.",
1025
+ guaranteedStop: "Enter a stop price.",
1026
+ trailingStopPips: "Enter a trailing distance."
1027
+ };
1028
+ function protectionFromChildEdit(parent, previous, changed) {
1029
+ if (!("parentId" in previous) || !("parentId" in changed) || previous.id !== changed.id || previous.symbol !== changed.symbol || previous.parentId !== changed.parentId || previous.parentType !== changed.parentType || previous.exitLevelId !== changed.exitLevelId || previous.side !== changed.side || previous.type !== changed.type)
1030
+ throw new TradingError(
1031
+ "invalid-input",
1032
+ "The protection order identity cannot be changed."
1033
+ );
1034
+ const fixedFields = [
1035
+ "duration",
1036
+ "customFields",
1037
+ "exitLevels",
1038
+ "takeProfit",
1039
+ "stopLoss",
1040
+ "guaranteedStop"
1041
+ ];
1042
+ for (const field2 of fixedFields)
1043
+ if (!equalData(previous[field2], changed[field2]))
1044
+ throw new TradingError(
1045
+ "unsupported",
1046
+ "Only the protection price, style and allocated quantity can be changed here."
1047
+ );
1048
+ const otherPrice = changed.type === 1 /* Limit */ ? "stopPrice" : "limitPrice";
1049
+ if (!equalData(previous[otherPrice], changed[otherPrice]) || changed.type === 1 /* Limit */ && (!equalData(previous.stopType, changed.stopType) || !equalData(previous.trailingStopPips, changed.trailingStopPips)))
1050
+ throw new TradingError(
1051
+ "invalid-input",
1052
+ "The protection order type cannot be changed."
1053
+ );
1054
+ const levels = parent.exitLevels;
1055
+ const level = levels?.length ? levels.find((value2) => value2.id === previous.exitLevelId) : parent;
1056
+ if (!level)
1057
+ throw new TradingError(
1058
+ "stale-context",
1059
+ "This protection level is no longer available."
1060
+ );
1061
+ if (!levels?.length && changed.qty !== parent.qty)
1062
+ throw new TradingError(
1063
+ "invalid-input",
1064
+ "Change the parent quantity or use allocated exit levels."
1065
+ );
1066
+ const field = childProtectionField(changed);
1067
+ if (!field)
1068
+ throw new TradingError(
1069
+ "unsupported",
1070
+ "This protection order type cannot be edited."
1071
+ );
1072
+ if (field === "trailingStopPips" && changed.stopPrice !== previous.stopPrice)
1073
+ throw new TradingError(
1074
+ "invalid-input",
1075
+ "Change the trailing distance to update this protection."
1076
+ );
1077
+ const value = childProtectionValue(changed, field);
1078
+ if (value === void 0) throw new TradingError("invalid-input", missingValueMessages[field]);
1079
+ const patch = field === "takeProfit" ? { takeProfit: value } : { stopLoss: void 0, guaranteedStop: void 0, trailingStopPips: void 0, [field]: value };
1080
+ if (levels?.length)
1081
+ return {
1082
+ exitLevels: levels.map(
1083
+ (value2) => value2.id === previous.exitLevelId ? { ...structuredClone(value2), ...patch, qty: changed.qty } : structuredClone(value2)
1084
+ ),
1085
+ takeProfit: void 0,
1086
+ stopLoss: void 0,
1087
+ guaranteedStop: void 0,
1088
+ trailingStopPips: void 0
1089
+ };
1090
+ return {
1091
+ takeProfit: parent.takeProfit,
1092
+ stopLoss: parent.stopLoss,
1093
+ guaranteedStop: parent.guaranteedStop,
1094
+ trailingStopPips: parent.trailingStopPips,
1095
+ ...patch,
1096
+ exitLevels: void 0
1097
+ };
1098
+ }
1099
+
1100
+ // src/mock/protection-cancellation.ts
1101
+ var protectionLegs = [
1102
+ "takeProfit",
1103
+ "stopLoss",
1104
+ "guaranteedStop",
1105
+ "trailingStopPips"
1106
+ ];
1107
+ function leg(order) {
1108
+ if (order.type === 1 /* Limit */) return "takeProfit";
1109
+ if (order.stopType === 1 /* TrailingStop */) return "trailingStopPips";
1110
+ if (order.stopType === 2 /* GuaranteedStop */) return "guaranteedStop";
1111
+ return "stopLoss";
1112
+ }
1113
+ function withoutCanceledProtection(parent, canceled) {
1114
+ const next = { ...parent };
1115
+ if (parent.exitLevels?.length) {
1116
+ next.exitLevels = parent.exitLevels.flatMap((level) => {
1117
+ const removed = canceled.filter(
1118
+ (child) => child.exitLevelId === level.id
1119
+ );
1120
+ if (!removed.length) return [level];
1121
+ const updated = { ...level };
1122
+ for (const child of removed) delete updated[leg(child)];
1123
+ return protectionLegs.some((key) => updated[key] !== void 0) ? [updated] : [];
1124
+ });
1125
+ if (!next.exitLevels.length) delete next.exitLevels;
1126
+ return next;
1127
+ }
1128
+ for (const child of canceled) delete next[leg(child)];
1129
+ if (next.trailingStopPips === void 0) delete next.trailingStopPrice;
1130
+ if (next.stopLoss === void 0 && next.trailingStopPips === void 0 && next.guaranteedStop === void 0)
1131
+ delete next.stopType;
1132
+ return next;
1133
+ }
1134
+
1135
+ // src/mock/broker.ts
1136
+ var protectionLegKinds = ["takeProfit", "stopLoss", "guaranteedStop", "trailingStopPips"];
1137
+ var commission = -0.1;
1138
+ var updateOrderings = ["before", "after", "split"];
1139
+ function updateOrdering(value) {
1140
+ if (updateOrderings.includes(value)) return value;
1141
+ throw new Error(`Unknown update ordering: ${String(value)}.`);
1142
+ }
1143
+ function defaultUpdateOrdering() {
1144
+ const environment = globalThis.process?.env;
1145
+ const value = environment?.TRADING_UPDATE_ORDERING;
1146
+ return value ? updateOrdering(value) : "before";
1147
+ }
1148
+ function createDeterministicBroker(options = {}) {
1149
+ const profile = options.profile ?? "equity-net";
1150
+ const seed = options.seed ?? 1;
1151
+ const clock = options.clock ?? new SimulationClock();
1152
+ const pipValue = () => options.pipValue ?? simulationInstrument(profile).pipValue;
1153
+ const feeds = createSimulationFeeds(seed);
1154
+ const config = simulationConfig(profile);
1155
+ const accounts = /* @__PURE__ */ new Map();
1156
+ const calls = [];
1157
+ let host;
1158
+ let broker;
1159
+ let accountId = "simulation-A";
1160
+ let status = 1 /* Connected */;
1161
+ let sequence = seed >>> 0;
1162
+ let alive = true;
1163
+ let factoryCalls = 0;
1164
+ let rejectNext;
1165
+ let rejectAsBrokerRejection = false;
1166
+ let ackDelay = 0;
1167
+ const leverage = /* @__PURE__ */ new Map();
1168
+ const equityDemand = /* @__PURE__ */ new Set();
1169
+ const marginDemand = /* @__PURE__ */ new Set();
1170
+ const pipDemand = /* @__PURE__ */ new Set();
1171
+ const equityValues = /* @__PURE__ */ new Map();
1172
+ const previews = /* @__PURE__ */ new Map();
1173
+ let previewTtl;
1174
+ const acknowledgements = /* @__PURE__ */ new Map();
1175
+ const bracketQuantities = /* @__PURE__ */ new Map();
1176
+ const bracketParents = /* @__PURE__ */ new Map();
1177
+ const delayedReads = [];
1178
+ let delayNext = false;
1179
+ let ordering = options.updateOrdering === void 0 ? defaultUpdateOrdering() : updateOrdering(options.updateOrdering);
1180
+ let held;
1181
+ let protectionEdits = "modify";
1182
+ const id = (kind) => `sim-${kind}-${++sequence}`;
1183
+ const activeOrder = (order) => [6 /* Working */, 3 /* Inactive */, 4 /* Placing */].includes(order.status);
1184
+ for (const [index, name] of ["simulation-A", "simulation-B"].entries()) {
1185
+ const state = {
1186
+ orders: /* @__PURE__ */ new Map(),
1187
+ positions: /* @__PURE__ */ new Map(),
1188
+ individuals: /* @__PURE__ */ new Map(),
1189
+ executions: /* @__PURE__ */ new Map(),
1190
+ equity: 1e4 + index * 5e3
1191
+ };
1192
+ const position = {
1193
+ id: `${name}:net:SIM:X`,
1194
+ symbol: "SIM:X",
1195
+ qty: 4,
1196
+ side: 1 /* Buy */,
1197
+ avgPrice: 99,
1198
+ extra: { pl: 4 }
1199
+ };
1200
+ state.positions.set(position.id, position);
1201
+ const individual = {
1202
+ id: `${name}:individual:1`,
1203
+ date: clock.now(),
1204
+ symbol: "SIM:X",
1205
+ qty: 4,
1206
+ side: 1 /* Buy */,
1207
+ price: 99,
1208
+ extra: { pl: 4 }
1209
+ };
1210
+ state.individuals.set(individual.id, individual);
1211
+ accounts.set(name, state);
1212
+ }
1213
+ const current = () => accounts.get(accountId);
1214
+ const requireHost = () => {
1215
+ if (!host || !alive) throw new Error("Simulation is closed or not initialized.");
1216
+ return host;
1217
+ };
1218
+ const record = (method, ...args) => {
1219
+ calls.push({ method, args: structuredClone(args), accountId });
1220
+ };
1221
+ const publish = (send) => {
1222
+ const adapter = requireHost();
1223
+ const deliver = () => {
1224
+ if (alive && status === 1 /* Connected */) send(adapter);
1225
+ };
1226
+ if (!held) return deliver();
1227
+ if (held.passFirst) {
1228
+ held.passFirst = false;
1229
+ return deliver();
1230
+ }
1231
+ held.pending.push(deliver);
1232
+ };
1233
+ const mutation = (method, args, work) => {
1234
+ if (ordering === "before") return settle(method, args, work);
1235
+ const hold = { pending: [], passFirst: ordering === "split" };
1236
+ const settled = settle(method, args, work, hold);
1237
+ const release = () => void Promise.resolve().then(() => {
1238
+ for (const deliver of hold.pending.splice(0)) deliver();
1239
+ });
1240
+ settled.then(release, release);
1241
+ return settled;
1242
+ };
1243
+ const settle = async (method, args, work, hold) => {
1244
+ requireHost();
1245
+ record(method, ...args);
1246
+ if (status !== 1 /* Connected */) throw new Error("Simulation is disconnected.");
1247
+ if (rejectNext) {
1248
+ const message = rejectNext;
1249
+ rejectNext = void 0;
1250
+ if (rejectAsBrokerRejection) throw { code: "rejected", message };
1251
+ throw new Error(message);
1252
+ }
1253
+ held = hold;
1254
+ let result;
1255
+ try {
1256
+ result = work();
1257
+ } finally {
1258
+ held = void 0;
1259
+ }
1260
+ const delay = ackDelay;
1261
+ ackDelay = 0;
1262
+ if (delay > 0)
1263
+ await new Promise((resolve) => {
1264
+ const handle = clock.setTimeout(() => {
1265
+ acknowledgements.delete(handle);
1266
+ resolve();
1267
+ }, delay);
1268
+ acknowledgements.set(handle, resolve);
1269
+ });
1270
+ return result;
1271
+ };
1272
+ const read = (method, value) => {
1273
+ record(method);
1274
+ if (status !== 1 /* Connected */) return Promise.reject(new Error("Simulation is disconnected."));
1275
+ const captured = structuredClone(value);
1276
+ if (!delayNext) return Promise.resolve(captured);
1277
+ delayNext = false;
1278
+ return new Promise((resolve) => delayedReads.push({ release: () => resolve(captured) }));
1279
+ };
1280
+ const emitOrder = (order) => {
1281
+ current().orders.set(order.id, structuredClone(order));
1282
+ const update = structuredClone(order);
1283
+ publish((adapter) => adapter.orderUpdate(update));
1284
+ };
1285
+ const emitPosition = (position) => {
1286
+ if (position.qty) current().positions.set(position.id, structuredClone(position));
1287
+ else current().positions.delete(position.id);
1288
+ const update = structuredClone(position);
1289
+ publish((adapter) => adapter.positionUpdate(update));
1290
+ };
1291
+ const emitIndividual = (position) => {
1292
+ if (position.qty) current().individuals.set(position.id, structuredClone(position));
1293
+ else current().individuals.delete(position.id);
1294
+ const update = structuredClone(position);
1295
+ publish((adapter) => adapter.individualPositionUpdate(update));
1296
+ };
1297
+ const realise = (cashFlow) => {
1298
+ if (!cashFlow) return;
1299
+ const state = current();
1300
+ state.equity += cashFlow;
1301
+ const equity = state.equity;
1302
+ equityValues.get(accountId)?.setValue(equity);
1303
+ if (equityDemand.has(accountId)) publish((adapter) => adapter.equityUpdate(equity));
1304
+ };
1305
+ const closedPL = (side, average, price, qty) => (price - average) * qty * side;
1306
+ const markPrice = (symbol) => feeds.lastPrice(symbol) ?? 100;
1307
+ function getOrder(orderId) {
1308
+ const order = current().orders.get(orderId);
1309
+ if (!order || !activeOrder(order)) throw new Error("The order is no longer active.");
1310
+ return order;
1311
+ }
1312
+ function getPosition(positionId) {
1313
+ const position = current().positions.get(positionId);
1314
+ if (!position) throw new Error("The position is no longer active.");
1315
+ return position;
1316
+ }
1317
+ function cancelSelectedOrder(order) {
1318
+ if (!activeOrder(current().orders.get(order.id) ?? order)) return;
1319
+ const selected = [order];
1320
+ for (const candidate of current().orders.values()) {
1321
+ if (candidate.id === order.id || !activeOrder(candidate) || !("parentId" in candidate) || candidate.symbol !== order.symbol)
1322
+ continue;
1323
+ if (!("parentId" in order)) {
1324
+ if (candidate.parentType === 1 /* Order */ && candidate.parentId === order.id) selected.push(candidate);
1325
+ continue;
1326
+ }
1327
+ if (config.configFlags.supportCancellingBothBracketsOnly && candidate.parentType === order.parentType && candidate.parentId === order.parentId && candidate.exitLevelId === order.exitLevelId)
1328
+ selected.push(candidate);
1329
+ }
1330
+ for (const candidate of selected) emitOrder({ ...candidate, status: 1 /* Canceled */ });
1331
+ if (!("parentId" in order)) return;
1332
+ const children = selected.filter((child) => "parentId" in child);
1333
+ if (order.parentType === 1 /* Order */) {
1334
+ const parent = current().orders.get(order.parentId);
1335
+ if (parent && activeOrder(parent)) emitOrder(withoutCanceledProtection(parent, children));
1336
+ } else if (order.parentType === 2 /* Position */) {
1337
+ const parent = current().positions.get(order.parentId);
1338
+ if (parent) emitPosition(withoutCanceledProtection(parent, children));
1339
+ } else if (order.parentType === 3 /* IndividualPosition */) {
1340
+ const parent = current().individuals.get(order.parentId);
1341
+ if (parent) emitIndividual(withoutCanceledProtection(parent, children));
1342
+ }
1343
+ }
1344
+ function modifyBracketOrder(previous, order) {
1345
+ let parent;
1346
+ if (previous.parentType === 1 /* Order */) parent = current().orders.get(previous.parentId);
1347
+ else if (previous.parentType === 2 /* Position */) parent = current().positions.get(previous.parentId);
1348
+ else if (previous.parentType === 3 /* IndividualPosition */)
1349
+ parent = current().individuals.get(previous.parentId);
1350
+ if (!parent) throw new Error("Protection parent is unavailable.");
1351
+ const children = [...current().orders.values()].filter(
1352
+ (child) => "parentId" in child && child.parentType === previous.parentType && child.parentId === previous.parentId && activeOrder(child)
1353
+ );
1354
+ const brackets = protectionFromChildEdit(
1355
+ completeParentProtection(parent, children),
1356
+ previous,
1357
+ order
1358
+ );
1359
+ const updated = { ...parent, ...brackets };
1360
+ if (previous.parentType === 1 /* Order */) {
1361
+ const parentOrder = updated;
1362
+ parentOrder.stopType = void 0;
1363
+ if (brackets.trailingStopPips !== void 0) parentOrder.stopType = 1 /* TrailingStop */;
1364
+ else if (brackets.guaranteedStop !== void 0) parentOrder.stopType = 2 /* GuaranteedStop */;
1365
+ else if (brackets.stopLoss !== void 0) parentOrder.stopType = 0 /* StopLoss */;
1366
+ emitOrder(parentOrder);
1367
+ } else if (previous.parentType === 2 /* Position */) emitPosition(updated);
1368
+ else emitIndividual(updated);
1369
+ bracketQuantities.set(order.id, order.qty);
1370
+ emitOrder({ ...order, status: previous.status });
1371
+ for (const sibling of current().orders.values()) {
1372
+ if (sibling.id === order.id || !("parentId" in sibling) || !activeOrder(sibling) || sibling.parentType !== previous.parentType || sibling.parentId !== previous.parentId || sibling.exitLevelId !== previous.exitLevelId || sibling.qty === order.qty)
1373
+ continue;
1374
+ bracketQuantities.set(sibling.id, order.qty);
1375
+ emitOrder({ ...sibling, qty: order.qty });
1376
+ }
1377
+ }
1378
+ function protection(parent, parentType, brackets) {
1379
+ const existing = /* @__PURE__ */ new Map();
1380
+ const replaced = [];
1381
+ for (const child of current().orders.values())
1382
+ if ("parentId" in child && child.parentType === parentType && child.parentId === parent.id && activeOrder(child))
1383
+ if (protectionEdits === "replace") replaced.push(child);
1384
+ else existing.set(legKey(child.exitLevelId, legKind(child)), child);
1385
+ const requested = protectionLegs2(parent, parentType, brackets);
1386
+ for (const child of replaced) emitOrder({ ...child, status: 1 /* Canceled */ });
1387
+ for (const [key, child] of existing) if (!requested.has(key)) emitOrder({ ...child, status: 1 /* Canceled */ });
1388
+ for (const [key, template] of requested) {
1389
+ const survivor = existing.get(key);
1390
+ const child = survivor ? { ...template, id: survivor.id, status: survivor.status } : { ...template, id: id("bracket") };
1391
+ bracketQuantities.set(child.id, child.qty);
1392
+ if (parentType === 1 /* Order */) bracketParents.set(child.id, parent.id);
1393
+ if (!survivor || !sameOrder(survivor, child)) emitOrder(child);
1394
+ }
1395
+ }
1396
+ const legKey = (exitLevelId, leg2) => `${exitLevelId ?? "single"}:${leg2}`;
1397
+ function legKind(child) {
1398
+ if (child.type === 1 /* Limit */) return "takeProfit";
1399
+ if (child.stopType === 1 /* TrailingStop */) return "trailingStopPips";
1400
+ if (child.stopType === 2 /* GuaranteedStop */) return "guaranteedStop";
1401
+ return "stopLoss";
1402
+ }
1403
+ const sameOrder = (left, right) => Object.keys({ ...left, ...right }).every(
1404
+ (key) => JSON.stringify(left[key]) === JSON.stringify(right[key])
1405
+ );
1406
+ function protectionLegs2(parent, parentType, brackets) {
1407
+ const legs = /* @__PURE__ */ new Map();
1408
+ const levels = brackets.exitLevels ?? [
1409
+ {
1410
+ id: "single",
1411
+ qty: parent.qty,
1412
+ takeProfit: brackets.takeProfit,
1413
+ stopLoss: brackets.stopLoss,
1414
+ guaranteedStop: brackets.guaranteedStop,
1415
+ trailingStopPips: brackets.trailingStopPips
1416
+ }
1417
+ ];
1418
+ for (const level of levels) {
1419
+ for (const leg2 of protectionLegKinds) {
1420
+ const price = level[leg2];
1421
+ if (price === void 0) continue;
1422
+ const takeProfit = leg2 === "takeProfit";
1423
+ legs.set(legKey(level.id, leg2), {
1424
+ symbol: parent.symbol,
1425
+ side: -parent.side,
1426
+ qty: level.qty,
1427
+ type: takeProfit ? 1 /* Limit */ : 3 /* Stop */,
1428
+ status: parentType === 1 /* Order */ ? 3 /* Inactive */ : 6 /* Working */,
1429
+ parentId: parent.id,
1430
+ parentType,
1431
+ exitLevelId: level.id,
1432
+ ...takeProfit ? { limitPrice: price } : {
1433
+ stopPrice: leg2 === "trailingStopPips" ? 100 - parent.side * price * simulationInstrument(profile).pipSize : price
1434
+ },
1435
+ ...leg2 === "trailingStopPips" ? { stopType: 1 /* TrailingStop */, trailingStopPips: price } : {},
1436
+ ...leg2 === "guaranteedStop" ? { stopType: 2 /* GuaranteedStop */ } : {}
1437
+ });
1438
+ }
1439
+ }
1440
+ return legs;
1441
+ }
1442
+ function closePosition(positionId, amount, price) {
1443
+ const position = getPosition(positionId);
1444
+ const qty = amount ?? position.qty;
1445
+ validateQuantity(qty, simulationInstrument(profile).qty);
1446
+ if (qty > position.qty) throw new Error("Close quantity exceeds the position.");
1447
+ emitPosition({ ...position, qty: position.qty - qty });
1448
+ if (qty === position.qty) {
1449
+ for (const order of current().orders.values())
1450
+ if ("parentId" in order && order.parentId === positionId && activeOrder(order))
1451
+ emitOrder({ ...order, status: 1 /* Canceled */ });
1452
+ }
1453
+ realise(closedPL(position.side, position.avgPrice, price ?? markPrice(position.symbol), qty));
1454
+ }
1455
+ function closeIndividualPosition(positionId, amount, price) {
1456
+ const position = current().individuals.get(positionId);
1457
+ if (!position) throw new Error("Unknown individual position.");
1458
+ const qty = amount ?? position.qty;
1459
+ validateQuantity(qty, simulationInstrument(profile).qty);
1460
+ if (qty > position.qty) throw new Error("Invalid close quantity.");
1461
+ emitIndividual({ ...position, qty: position.qty - qty });
1462
+ if (qty === position.qty) {
1463
+ for (const order of current().orders.values())
1464
+ if ("parentId" in order && order.parentType === 3 /* IndividualPosition */ && order.parentId === positionId && activeOrder(order))
1465
+ emitOrder({ ...order, status: 1 /* Canceled */ });
1466
+ }
1467
+ const net = [...current().positions.values()].find((value) => value.symbol === position.symbol);
1468
+ if (net) closePosition(net.id, Math.min(qty, net.qty), price);
1469
+ }
1470
+ function cancelExitLevelSiblings(order) {
1471
+ for (const sibling of current().orders.values())
1472
+ if ("parentId" in sibling && sibling.parentId === order.parentId && sibling.exitLevelId === order.exitLevelId && sibling.id !== order.id && activeOrder(sibling))
1473
+ emitOrder({ ...sibling, status: 1 /* Canceled */ });
1474
+ }
1475
+ function recordExecution(symbol, side, qty, price) {
1476
+ const execution = { id: id("execution"), symbol, side, qty, price, time: clock.now(), commission };
1477
+ current().executions.set(execution.id, execution);
1478
+ publish((adapter) => adapter.executionUpdate(execution));
1479
+ realise(commission);
1480
+ }
1481
+ function netFill(positionKey, symbol, fillSide, qty, price) {
1482
+ const previous = current().positions.get(positionKey);
1483
+ const signed = (previous ? previous.qty * previous.side : 0) + qty * fillSide;
1484
+ const side = signed < 0 ? -1 /* Sell */ : 1 /* Buy */;
1485
+ let avgPrice = price;
1486
+ if (previous && previous.side === fillSide)
1487
+ avgPrice = (previous.avgPrice * previous.qty + price * qty) / (previous.qty + qty);
1488
+ else if (previous && side === previous.side) avgPrice = previous.avgPrice;
1489
+ const position = { id: positionKey, symbol, side, qty: Math.abs(signed), avgPrice, extra: { pl: 0 } };
1490
+ emitPosition(position);
1491
+ if (previous && previous.side !== fillSide)
1492
+ realise(closedPL(previous.side, previous.avgPrice, price, Math.min(qty, previous.qty)));
1493
+ return position;
1494
+ }
1495
+ function reversePosition(positionId) {
1496
+ const position = getPosition(positionId);
1497
+ const price = markPrice(position.symbol);
1498
+ const side = -position.side;
1499
+ for (const order of current().orders.values())
1500
+ if ("parentId" in order && order.parentId === positionId && activeOrder(order))
1501
+ emitOrder({ ...order, status: 1 /* Canceled */ });
1502
+ if (config.configFlags.supportPositionNetting) {
1503
+ for (const individual of [...current().individuals.values()])
1504
+ if (individual.symbol === position.symbol) {
1505
+ for (const order of current().orders.values())
1506
+ if ("parentId" in order && order.parentId === individual.id && activeOrder(order))
1507
+ emitOrder({ ...order, status: 1 /* Canceled */ });
1508
+ emitIndividual({ ...individual, qty: 0 });
1509
+ }
1510
+ }
1511
+ const qty = position.qty * 2;
1512
+ emitOrder({
1513
+ id: id("order"),
1514
+ symbol: position.symbol,
1515
+ side,
1516
+ qty,
1517
+ type: 2 /* Market */,
1518
+ status: 2 /* Filled */,
1519
+ filledQty: qty,
1520
+ avgPrice: price
1521
+ });
1522
+ recordExecution(position.symbol, side, position.qty, price);
1523
+ recordExecution(position.symbol, side, position.qty, price);
1524
+ netFill(positionId, position.symbol, side, qty, price);
1525
+ if (config.configFlags.supportPositionNetting)
1526
+ emitIndividual({
1527
+ id: id("individual"),
1528
+ date: clock.now(),
1529
+ symbol: position.symbol,
1530
+ side,
1531
+ qty: position.qty,
1532
+ price
1533
+ });
1534
+ }
1535
+ function fill(orderId, quantity, price = 100) {
1536
+ const order = getOrder(orderId), remaining = order.qty - (order.filledQty ?? 0), qty = quantity ?? remaining;
1537
+ if (order.status === 3 /* Inactive */) throw new Error("The bracket is not active.");
1538
+ validateQuantity(qty, simulationInstrument(profile).qty);
1539
+ if (qty > remaining || !Number.isFinite(price)) throw new Error("Invalid fill.");
1540
+ const filledQty = (order.filledQty ?? 0) + qty;
1541
+ emitOrder({
1542
+ ...order,
1543
+ filledQty,
1544
+ avgPrice: price,
1545
+ status: filledQty === order.qty ? 2 /* Filled */ : 6 /* Working */
1546
+ });
1547
+ recordExecution(order.symbol, order.side, qty, price);
1548
+ if ("parentId" in order && order.parentType === 2 /* Position */) {
1549
+ closePosition(order.parentId, qty, price);
1550
+ cancelExitLevelSiblings(order);
1551
+ return;
1552
+ }
1553
+ if ("parentId" in order && order.parentType === 3 /* IndividualPosition */) {
1554
+ closeIndividualPosition(order.parentId, qty, price);
1555
+ cancelExitLevelSiblings(order);
1556
+ return;
1557
+ }
1558
+ const positionKey = config.configFlags.supportMultiposition ? id("position") : `${accountId}:net:${order.symbol}`;
1559
+ const position = netFill(positionKey, order.symbol, order.side, qty, price);
1560
+ if (config.configFlags.supportPositionNetting)
1561
+ emitIndividual({ id: id("individual"), date: clock.now(), symbol: order.symbol, side: order.side, qty, price });
1562
+ for (const child of current().orders.values())
1563
+ if ("parentId" in child && bracketParents.get(child.id) === order.id && activeOrder(child))
1564
+ emitOrder({
1565
+ ...child,
1566
+ parentId: position.id,
1567
+ parentType: 2 /* Position */,
1568
+ // Multiposition: each fill opens its own position, so an exit moved onto it covers that position only.
1569
+ qty: Math.min(
1570
+ bracketQuantities.get(child.id) ?? child.qty,
1571
+ config.configFlags.supportMultiposition ? position.qty : filledQty
1572
+ ),
1573
+ status: 6 /* Working */
1574
+ });
1575
+ }
1576
+ const formatter = (places = 2) => ({
1577
+ format: (value) => value === void 0 ? "" : value.toFixed(places),
1578
+ parse: (text) => {
1579
+ const value = Number(text);
1580
+ if (!text.trim() || !Number.isFinite(value)) return { res: false, error: "Enter a number." };
1581
+ return { res: true, value };
1582
+ }
1583
+ });
1584
+ const checkPreview = (value, confirmId) => {
1585
+ if (!confirmId) return;
1586
+ const preview = previews.get(confirmId);
1587
+ if (preview?.payload !== JSON.stringify(value)) throw new Error("This preview is stale.");
1588
+ if (previewTtl !== void 0 && clock.now() - preview.createdAt > previewTtl) {
1589
+ previews.delete(confirmId);
1590
+ throw new Error("This preview has expired.");
1591
+ }
1592
+ };
1593
+ const consumePreview = (confirmId) => {
1594
+ if (confirmId) previews.delete(confirmId);
1595
+ };
1596
+ const openQuantity = (positionId) => current().individuals.get(positionId)?.qty ?? current().positions.get(positionId)?.qty;
1597
+ const closePreviewPayload = (positionId, amount) => ({
1598
+ positionId,
1599
+ amount: amount ?? openQuantity(positionId) ?? null
1600
+ });
1601
+ const checkClosePreview = (positionId, amount, confirmId) => checkPreview(closePreviewPayload(positionId, amount), confirmId);
1602
+ const factory = (adapterHost) => {
1603
+ factoryCalls++;
1604
+ if (host) throw new Error("A simulation supports one session. Create another fixture for another widget.");
1605
+ host = adapterHost;
1606
+ const summaries = /* @__PURE__ */ new Map();
1607
+ const terminal = {
1608
+ connectionStatus: () => status,
1609
+ currentAccount: () => accountId,
1610
+ accountsMetainfo: () => read(
1611
+ "accountsMetainfo",
1612
+ [...accounts.keys()].map((account, index) => ({
1613
+ id: account,
1614
+ name: `Simulated account ${index + 1}`,
1615
+ type: "demo",
1616
+ currency: "USD"
1617
+ }))
1618
+ ),
1619
+ setCurrentAccount: (target) => {
1620
+ record("setCurrentAccount", target);
1621
+ if (!accounts.has(target)) throw new Error("Unknown account.");
1622
+ accountId = target;
1623
+ requireHost().currentAccountUpdate();
1624
+ },
1625
+ accountManagerInfo: () => {
1626
+ let info = summaries.get(accountId);
1627
+ if (!info) {
1628
+ const equity = requireHost().factory.createWatchedValue(current().equity);
1629
+ equityValues.set(accountId, equity);
1630
+ info = {
1631
+ accountTitle: "Simulated trading",
1632
+ pages: [],
1633
+ summary: [{ text: "Equity", wValue: equity }],
1634
+ orderColumns: [
1635
+ { id: "symbol", label: "Symbol", dataFields: ["symbol"] },
1636
+ { id: "qty", label: "Quantity", dataFields: ["qty"], formatter: "formatQuantity" /* FormatQuantity */ },
1637
+ { id: "status", label: "Status", dataFields: ["status"], formatter: "status" /* Status */ }
1638
+ ],
1639
+ positionColumns: [
1640
+ { id: "symbol", label: "Symbol", dataFields: ["symbol", "symbol"], formatter: "symbol" /* Symbol */ },
1641
+ { id: "side", label: "Side", dataFields: ["side"], formatter: "side" /* Side */ },
1642
+ { id: "qty", label: "Qty", dataFields: ["qty"], formatter: "formatQuantity" /* FormatQuantity */ },
1643
+ {
1644
+ id: "avgPrice",
1645
+ label: "Avg fill price",
1646
+ dataFields: ["avgPrice"],
1647
+ formatter: "formatPrice" /* FormatPrice */
1648
+ },
1649
+ {
1650
+ id: "profitLoss",
1651
+ label: "P&L",
1652
+ dataFields: [["extra", "pl"]],
1653
+ formatter: "profit" /* Profit */,
1654
+ showZeroValues: false
1655
+ },
1656
+ {
1657
+ id: "takeProfit",
1658
+ label: "Take profit",
1659
+ dataFields: ["takeProfit"],
1660
+ formatter: "formatPrice" /* FormatPrice */
1661
+ },
1662
+ {
1663
+ id: "stopLoss",
1664
+ label: "Stop loss",
1665
+ dataFields: ["stopLoss"],
1666
+ formatter: "formatPrice" /* FormatPrice */
1667
+ }
1668
+ ]
1669
+ };
1670
+ summaries.set(accountId, info);
1671
+ }
1672
+ return info;
1673
+ },
1674
+ orders: () => read("orders", [...current().orders.values()].filter(activeOrder)),
1675
+ ordersHistory: () => read(
1676
+ "ordersHistory",
1677
+ [...current().orders.values()].filter((order) => !activeOrder(order))
1678
+ ),
1679
+ positions: () => read("positions", [...current().positions.values()]),
1680
+ individualPositions: () => read("individualPositions", [...current().individuals.values()]),
1681
+ executions: (symbol) => read(
1682
+ "executions",
1683
+ [...current().executions.values()].filter((execution) => execution.symbol === symbol)
1684
+ ),
1685
+ symbolInfo: async (symbol) => {
1686
+ record("symbolInfo", symbol);
1687
+ if (symbol !== "SIM:X") throw new Error("Unknown simulated instrument.");
1688
+ const value = simulationInstrument(profile);
1689
+ const multiple = leverage.get(symbol);
1690
+ return {
1691
+ ...value,
1692
+ pipValue: pipValue(),
1693
+ ...options.instrumentUnits === void 0 ? {} : { units: options.instrumentUnits },
1694
+ leverage: String(multiple ?? 10),
1695
+ marginRate: 1 / (multiple ?? 10)
1696
+ };
1697
+ },
1698
+ isTradable: async (symbol) => symbol === "SIM:X",
1699
+ chartContextMenuActions: (context) => requireHost().defaultContextMenuActions(context),
1700
+ placeOrder: (order, confirmId) => mutation("placeOrder", [order, confirmId], () => {
1701
+ validateQuantity(order.qty, simulationInstrument(profile).qty);
1702
+ checkPreview(order, confirmId);
1703
+ const placed = { ...structuredClone(order), id: id("order"), status: 6 /* Working */ };
1704
+ emitOrder(placed);
1705
+ protection(placed, 1 /* Order */, placed);
1706
+ consumePreview(confirmId);
1707
+ return { orderId: placed.id };
1708
+ }),
1709
+ modifyOrder: (order, confirmId) => mutation("modifyOrder", [order, confirmId], () => {
1710
+ const old = getOrder(order.id);
1711
+ if (old.symbol !== order.symbol || old.side !== order.side) throw new Error("Immutable order identity.");
1712
+ validateQuantity(order.qty, simulationInstrument(profile).qty);
1713
+ checkPreview(order, confirmId);
1714
+ if ("parentId" in old && "parentId" in order) modifyBracketOrder(old, order);
1715
+ else {
1716
+ emitOrder({ ...order, status: old.status });
1717
+ protection(order, 1 /* Order */, order);
1718
+ }
1719
+ consumePreview(confirmId);
1720
+ }),
1721
+ cancelOrder: (orderId) => mutation("cancelOrder", [orderId], () => cancelSelectedOrder(getOrder(orderId))),
1722
+ cancelOrders: (symbol, side, ids) => mutation("cancelOrders", [symbol, side, ids], () => {
1723
+ const selected = ids.map(getOrder);
1724
+ if (selected.some((order) => order.symbol !== symbol || side !== void 0 && order.side !== side))
1725
+ throw new Error("Invalid cancellation selection.");
1726
+ for (const order of selected) cancelSelectedOrder(order);
1727
+ }),
1728
+ closePosition: (positionId, amount, confirmId) => mutation("closePosition", [positionId, amount, confirmId], () => {
1729
+ checkClosePreview(positionId, amount, confirmId);
1730
+ closePosition(positionId, amount);
1731
+ consumePreview(confirmId);
1732
+ realise(commission);
1733
+ }),
1734
+ closeIndividualPosition: (positionId, amount, confirmId) => mutation("closeIndividualPosition", [positionId, amount, confirmId], () => {
1735
+ checkClosePreview(positionId, amount, confirmId);
1736
+ closeIndividualPosition(positionId, amount);
1737
+ consumePreview(confirmId);
1738
+ realise(commission);
1739
+ }),
1740
+ reversePosition: (positionId) => mutation("reversePosition", [positionId], () => reversePosition(positionId)),
1741
+ editPositionBrackets: (positionId, brackets, fields) => mutation("editPositionBrackets", [positionId, brackets, fields], () => {
1742
+ const position = getPosition(positionId);
1743
+ const updated = { ...position, ...brackets };
1744
+ emitPosition(updated);
1745
+ protection(updated, 2 /* Position */, brackets);
1746
+ }),
1747
+ editIndividualPositionBrackets: (positionId, brackets) => mutation("editIndividualPositionBrackets", [positionId, brackets], () => {
1748
+ const position = current().individuals.get(positionId);
1749
+ if (!position) throw new Error("Unknown individual position.");
1750
+ const updated = { ...position, ...brackets };
1751
+ emitIndividual(updated);
1752
+ protection(updated, 3 /* IndividualPosition */, brackets);
1753
+ }),
1754
+ previewOrder: async (order) => {
1755
+ record("previewOrder", order);
1756
+ const confirmId = id("preview");
1757
+ previews.set(confirmId, { payload: JSON.stringify(order), createdAt: clock.now() });
1758
+ const result = {
1759
+ confirmId,
1760
+ sections: [{ rows: [{ title: "Simulated commission", value: "0.10 USD" }] }]
1761
+ };
1762
+ return result;
1763
+ },
1764
+ leverageInfo: async (params) => {
1765
+ record("leverageInfo", params);
1766
+ return { title: "Simulated leverage", leverage: leverage.get(params.symbol) ?? 10, min: 1, max: 100, step: 1 };
1767
+ },
1768
+ previewLeverage: async (params) => {
1769
+ record("previewLeverage", params);
1770
+ return {
1771
+ infos: ["Simulation only"],
1772
+ errors: params.leverage < 1 || params.leverage > 100 ? ["Choose leverage from 1 to 100."] : []
1773
+ };
1774
+ },
1775
+ setLeverage: (params) => mutation("setLeverage", [params], () => {
1776
+ if (!Number.isInteger(params.leverage) || params.leverage < 1 || params.leverage > 100)
1777
+ throw new Error("Invalid leverage.");
1778
+ leverage.set(params.symbol, params.leverage);
1779
+ return { leverage: params.leverage };
1780
+ }),
1781
+ subscribeEquity: () => {
1782
+ equityDemand.add(accountId);
1783
+ requireHost().equityUpdate(current().equity);
1784
+ },
1785
+ unsubscribeEquity: () => {
1786
+ equityDemand.delete(accountId);
1787
+ },
1788
+ subscribeMarginAvailable: (symbol) => {
1789
+ marginDemand.add(`${accountId}:${symbol}`);
1790
+ requireHost().marginAvailableUpdate(current().equity / 2);
1791
+ },
1792
+ unsubscribeMarginAvailable: (symbol) => {
1793
+ marginDemand.delete(`${accountId}:${symbol}`);
1794
+ },
1795
+ subscribePipValue: (symbol) => {
1796
+ pipDemand.add(`${accountId}:${symbol}`);
1797
+ requireHost().pipValueUpdate(symbol, { buyPipValue: pipValue(), sellPipValue: pipValue() });
1798
+ },
1799
+ unsubscribePipValue: (symbol) => {
1800
+ pipDemand.delete(`${accountId}:${symbol}`);
1801
+ },
1802
+ formatter: async () => formatter(),
1803
+ spreadFormatter: async () => formatter(),
1804
+ quantityFormatter: async () => formatter(0),
1805
+ getSymbolSpecificTradingOptions: async () => ({ supportBracketsInPips: true, supportRiskControlsAndInfo: true }),
1806
+ getOrderDialogOptions: async () => ({
1807
+ maxExitLevelsCount: 4
1808
+ }),
1809
+ getPositionDialogOptions: async () => ({ maxExitLevelsCount: 4 })
1810
+ };
1811
+ broker = terminal;
1812
+ return terminal;
1813
+ };
1814
+ if (profile === "custom-ui")
1815
+ config.customUI = {
1816
+ showOrderDialog: async (template) => {
1817
+ const approved = await requireHost().showConfirmDialog("Custom simulated order", template.symbol);
1818
+ if (!approved) return false;
1819
+ await broker.placeOrder({
1820
+ ...template,
1821
+ type: template.type ?? 2 /* Market */,
1822
+ side: template.side ?? 1 /* Buy */,
1823
+ qty: template.qty ?? 2
1824
+ });
1825
+ return true;
1826
+ },
1827
+ showPositionDialog: async (position, brackets) => {
1828
+ if (!await requireHost().showConfirmDialog("Custom protection", position.symbol)) return false;
1829
+ await broker.editPositionBrackets(position.id, brackets);
1830
+ return true;
1831
+ },
1832
+ showCancelOrderDialog: (order) => requireHost().showConfirmDialog("Custom cancellation", order.id),
1833
+ showClosePositionDialog: (position) => requireHost().showConfirmDialog("Custom close", position.id),
1834
+ showReversePositionDialog: (position) => requireHost().showConfirmDialog("Custom reverse", position.id)
1835
+ };
1836
+ const extensions = {
1837
+ previewClosePosition: async (request) => {
1838
+ record("previewClosePosition", request);
1839
+ const previewId = id("close-preview");
1840
+ previews.set(previewId, {
1841
+ payload: JSON.stringify(closePreviewPayload(request.positionId, request.amount)),
1842
+ createdAt: clock.now()
1843
+ });
1844
+ return {
1845
+ id: previewId,
1846
+ rows: [{ title: "Quantity", value: String(request.amount ?? openQuantity(request.positionId) ?? "") }],
1847
+ disclaimer: "Simulated outcome only."
1848
+ };
1849
+ },
1850
+ disposeBroker: () => {
1851
+ alive = false;
1852
+ for (const [handle, resolve] of acknowledgements) {
1853
+ clock.clearTimeout(handle);
1854
+ resolve();
1855
+ }
1856
+ acknowledgements.clear();
1857
+ equityDemand.clear();
1858
+ marginDemand.clear();
1859
+ pipDemand.clear();
1860
+ feeds.destroy();
1861
+ for (const read2 of delayedReads.splice(0)) read2.release();
1862
+ }
1863
+ };
1864
+ return {
1865
+ profile,
1866
+ clock,
1867
+ brokerConfig: config,
1868
+ brokerFactory: factory,
1869
+ marketData: feeds.marketData,
1870
+ extensions,
1871
+ controls: {
1872
+ patchCapabilities(patch) {
1873
+ const adapter = requireHost(), copied = structuredClone(patch);
1874
+ config.configFlags = { ...config.configFlags, ...copied };
1875
+ adapter.patchConfig(copied);
1876
+ },
1877
+ fill,
1878
+ /** Moves the scripted quote and, when the profile supports it, pushes broker P&L for open positions. */
1879
+ tick(symbol = "SIM:X") {
1880
+ const price = feeds.tick(symbol);
1881
+ if (!config.configFlags.supportPLUpdate) return price;
1882
+ for (const position of current().positions.values())
1883
+ if (position.symbol === symbol) {
1884
+ const pl = closedPL(position.side, position.avgPrice, price, position.qty);
1885
+ publish((adapter) => adapter.plUpdate(position.id, pl));
1886
+ }
1887
+ if (!config.configFlags.supportPositionNetting) return price;
1888
+ for (const position of current().individuals.values())
1889
+ if (position.symbol === symbol) {
1890
+ const pl = closedPL(position.side, position.price, price, position.qty);
1891
+ publish((adapter) => adapter.individualPositionPLUpdate(position.id, pl));
1892
+ }
1893
+ return price;
1894
+ },
1895
+ quote: feeds.setQuote,
1896
+ quoteError: feeds.quoteError,
1897
+ depth: feeds.setDepth,
1898
+ /** The next mutation rejects; with `brokerRejection` it throws the `BrokerRejection` shape a live adapter should use. */
1899
+ rejectNextOperation(message = "Simulated rejection", options2 = {}) {
1900
+ rejectNext = message;
1901
+ rejectAsBrokerRejection = !!options2.brokerRejection;
1902
+ },
1903
+ delayNextAcknowledgement(milliseconds = 2e4) {
1904
+ ackDelay = milliseconds;
1905
+ },
1906
+ delayNextSnapshot() {
1907
+ delayNext = true;
1908
+ },
1909
+ releaseSnapshots() {
1910
+ for (const read2 of delayedReads.splice(0)) read2.release();
1911
+ },
1912
+ disconnect() {
1913
+ status = 3 /* Disconnected */;
1914
+ requireHost().connectionStatusUpdate(status);
1915
+ },
1916
+ reconnect() {
1917
+ status = 1 /* Connected */;
1918
+ requireHost().connectionStatusUpdate(status);
1919
+ },
1920
+ /** Changes when later mutations deliver their host updates relative to their promise. */
1921
+ updateOrdering(value) {
1922
+ ordering = updateOrdering(value);
1923
+ },
1924
+ /** Chooses whether later protection edits modify surviving legs in place or replace every leg. */
1925
+ protectionEdits(value) {
1926
+ protectionEdits = value;
1927
+ },
1928
+ /** Expires order previews older than `milliseconds` on the simulation clock; `undefined` keeps them until used. */
1929
+ previewTtl(milliseconds) {
1930
+ if (milliseconds !== void 0 && (!Number.isFinite(milliseconds) || milliseconds < 0))
1931
+ throw new Error("A preview lifetime must be a nonnegative duration.");
1932
+ previewTtl = milliseconds;
1933
+ },
1934
+ factoryCalls: () => factoryCalls,
1935
+ snapshot: () => structuredClone({
1936
+ accountId,
1937
+ orders: [...current().orders.values()],
1938
+ positions: [...current().positions.values()],
1939
+ individualPositions: [...current().individuals.values()],
1940
+ executions: [...current().executions.values()]
1941
+ }),
1942
+ calls: () => structuredClone(calls),
1943
+ subscriptionCounts: () => ({
1944
+ equity: equityDemand.size,
1945
+ margin: marginDemand.size,
1946
+ pip: pipDemand.size,
1947
+ ...feeds.counts()
1948
+ })
1949
+ }
1950
+ };
1951
+ }
1952
+ export {
1953
+ SimulationClock,
1954
+ createDeterministicBroker,
1955
+ simulationProfiles
1956
+ };