@reefclaw/connect 0.1.11 → 0.1.12

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 (397) hide show
  1. package/assets/bridge/gateway/heartbeat-cron.d.ts +27 -0
  2. package/assets/bridge/gateway/heartbeat-cron.js +85 -0
  3. package/assets/bridge/providers/gateway.d.ts +2 -0
  4. package/assets/bridge/providers/gateway.js +57 -16
  5. package/assets/bridge/setup.js +6 -51
  6. package/dist/deps.js +2 -2
  7. package/dist/plugin.js +35 -7
  8. package/package.json +1 -1
  9. package/assets/plugin/audit/mode-transition-audit.d.ts +0 -11
  10. package/assets/plugin/audit/mode-transition-audit.js +0 -29
  11. package/assets/plugin/balance-utils.d.ts +0 -36
  12. package/assets/plugin/balance-utils.js +0 -98
  13. package/assets/plugin/ccxt/binance-ban-gate.d.ts +0 -47
  14. package/assets/plugin/ccxt/binance-ban-gate.js +0 -420
  15. package/assets/plugin/ccxt/binance-private.d.ts +0 -346
  16. package/assets/plugin/ccxt/binance-private.js +0 -1525
  17. package/assets/plugin/ccxt/binance-public.d.ts +0 -34
  18. package/assets/plugin/ccxt/binance-public.js +0 -180
  19. package/assets/plugin/ccxt/intel-public.d.ts +0 -25
  20. package/assets/plugin/ccxt/intel-public.js +0 -80
  21. package/assets/plugin/ccxt/public-market-data-api.d.ts +0 -26
  22. package/assets/plugin/ccxt/public-market-data-api.js +0 -23
  23. package/assets/plugin/config/agent-config-client.d.ts +0 -77
  24. package/assets/plugin/config/agent-config-client.js +0 -188
  25. package/assets/plugin/config/agent-config-poller.d.ts +0 -32
  26. package/assets/plugin/config/agent-config-poller.js +0 -101
  27. package/assets/plugin/config/brackets-config.d.ts +0 -22
  28. package/assets/plugin/config/brackets-config.js +0 -58
  29. package/assets/plugin/config/entitlement-gate.d.ts +0 -51
  30. package/assets/plugin/config/entitlement-gate.js +0 -137
  31. package/assets/plugin/config/gate-store.d.ts +0 -18
  32. package/assets/plugin/config/gate-store.js +0 -61
  33. package/assets/plugin/config/plugin-config-io.d.ts +0 -222
  34. package/assets/plugin/config/plugin-config-io.js +0 -126
  35. package/assets/plugin/config/position-review-config.d.ts +0 -35
  36. package/assets/plugin/config/position-review-config.js +0 -105
  37. package/assets/plugin/config/tool-gate.d.ts +0 -53
  38. package/assets/plugin/config/tool-gate.js +0 -128
  39. package/assets/plugin/config/user-data-stream-config.d.ts +0 -89
  40. package/assets/plugin/config/user-data-stream-config.js +0 -239
  41. package/assets/plugin/connector-supervisor.d.ts +0 -36
  42. package/assets/plugin/connector-supervisor.js +0 -149
  43. package/assets/plugin/exchange-adapter.d.ts +0 -65
  44. package/assets/plugin/exchange-adapter.js +0 -4
  45. package/assets/plugin/index.d.ts +0 -30
  46. package/assets/plugin/index.js +0 -2756
  47. package/assets/plugin/ingest/pending-entry-metadata.d.ts +0 -74
  48. package/assets/plugin/ingest/pending-entry-metadata.js +0 -236
  49. package/assets/plugin/ingest/position-auto-capture.d.ts +0 -171
  50. package/assets/plugin/ingest/position-auto-capture.js +0 -709
  51. package/assets/plugin/ingest/position-decisions-client.d.ts +0 -327
  52. package/assets/plugin/ingest/position-decisions-client.js +0 -306
  53. package/assets/plugin/ingest/readiness-reporter.d.ts +0 -42
  54. package/assets/plugin/ingest/readiness-reporter.js +0 -163
  55. package/assets/plugin/ingest/reconcile-db-vs-exchange.d.ts +0 -51
  56. package/assets/plugin/ingest/reconcile-db-vs-exchange.js +0 -170
  57. package/assets/plugin/ingest/reconciler-cleanup.d.ts +0 -37
  58. package/assets/plugin/ingest/reconciler-cleanup.js +0 -147
  59. package/assets/plugin/ingest/rest-gap-filler.d.ts +0 -191
  60. package/assets/plugin/ingest/rest-gap-filler.js +0 -565
  61. package/assets/plugin/ingest/touched-symbols-store.d.ts +0 -25
  62. package/assets/plugin/ingest/touched-symbols-store.js +0 -96
  63. package/assets/plugin/ingest/trade-store-client.d.ts +0 -40
  64. package/assets/plugin/ingest/trade-store-client.js +0 -125
  65. package/assets/plugin/ingest/ws-ingest.d.ts +0 -43
  66. package/assets/plugin/ingest/ws-ingest.js +0 -126
  67. package/assets/plugin/learning/setup-family.d.ts +0 -21
  68. package/assets/plugin/learning/setup-family.js +0 -103
  69. package/assets/plugin/lifecycle/install-signal-handlers.d.ts +0 -33
  70. package/assets/plugin/lifecycle/install-signal-handlers.js +0 -112
  71. package/assets/plugin/lifecycle/shutdown-coordinator.d.ts +0 -43
  72. package/assets/plugin/lifecycle/shutdown-coordinator.js +0 -131
  73. package/assets/plugin/lifecycle/trading-operation-lock.d.ts +0 -17
  74. package/assets/plugin/lifecycle/trading-operation-lock.js +0 -14
  75. package/assets/plugin/live/bracket-id.d.ts +0 -26
  76. package/assets/plugin/live/bracket-id.js +0 -112
  77. package/assets/plugin/live/bracket-ledger.d.ts +0 -54
  78. package/assets/plugin/live/bracket-ledger.js +0 -267
  79. package/assets/plugin/live/bracket-manager.d.ts +0 -82
  80. package/assets/plugin/live/bracket-manager.js +0 -478
  81. package/assets/plugin/live/bracket-params.d.ts +0 -22
  82. package/assets/plugin/live/bracket-params.js +0 -124
  83. package/assets/plugin/live/bracket-reconciler.d.ts +0 -95
  84. package/assets/plugin/live/bracket-reconciler.js +0 -573
  85. package/assets/plugin/live/bracket-types.d.ts +0 -102
  86. package/assets/plugin/live/bracket-types.js +0 -8
  87. package/assets/plugin/live/deposit-tracker.d.ts +0 -62
  88. package/assets/plugin/live/deposit-tracker.js +0 -97
  89. package/assets/plugin/live/emergency-controls.d.ts +0 -32
  90. package/assets/plugin/live/emergency-controls.js +0 -226
  91. package/assets/plugin/live/exchange-errors.d.ts +0 -12
  92. package/assets/plugin/live/exchange-errors.js +0 -130
  93. package/assets/plugin/live/exchange-info-cache.d.ts +0 -37
  94. package/assets/plugin/live/exchange-info-cache.js +0 -134
  95. package/assets/plugin/live/fact-subscriber.d.ts +0 -78
  96. package/assets/plugin/live/fact-subscriber.js +0 -182
  97. package/assets/plugin/live/fill-price.d.ts +0 -13
  98. package/assets/plugin/live/fill-price.js +0 -37
  99. package/assets/plugin/live/intent-journal.d.ts +0 -42
  100. package/assets/plugin/live/intent-journal.js +0 -122
  101. package/assets/plugin/live/listen-key-manager.d.ts +0 -70
  102. package/assets/plugin/live/listen-key-manager.js +0 -169
  103. package/assets/plugin/live/live-adapter.d.ts +0 -319
  104. package/assets/plugin/live/live-adapter.js +0 -1906
  105. package/assets/plugin/live/live-balance-enricher.d.ts +0 -32
  106. package/assets/plugin/live/live-balance-enricher.js +0 -104
  107. package/assets/plugin/live/live-bracket-api.d.ts +0 -13
  108. package/assets/plugin/live/live-bracket-api.js +0 -20
  109. package/assets/plugin/live/live-state-store.d.ts +0 -194
  110. package/assets/plugin/live/live-state-store.js +0 -450
  111. package/assets/plugin/live/local-signal-service.d.ts +0 -57
  112. package/assets/plugin/live/local-signal-service.js +0 -151
  113. package/assets/plugin/live/local-strategy-evaluator.d.ts +0 -62
  114. package/assets/plugin/live/local-strategy-evaluator.js +0 -131
  115. package/assets/plugin/live/microstructure-assembler.d.ts +0 -54
  116. package/assets/plugin/live/microstructure-assembler.js +0 -148
  117. package/assets/plugin/live/order-poller.d.ts +0 -29
  118. package/assets/plugin/live/order-poller.js +0 -125
  119. package/assets/plugin/live/position-state-store.d.ts +0 -87
  120. package/assets/plugin/live/position-state-store.js +0 -237
  121. package/assets/plugin/live/proposal-decision-listener.d.ts +0 -70
  122. package/assets/plugin/live/proposal-decision-listener.js +0 -292
  123. package/assets/plugin/live/proposal-manager.d.ts +0 -76
  124. package/assets/plugin/live/proposal-manager.js +0 -140
  125. package/assets/plugin/live/rate-limiter.d.ts +0 -47
  126. package/assets/plugin/live/rate-limiter.js +0 -159
  127. package/assets/plugin/live/reconciler.d.ts +0 -39
  128. package/assets/plugin/live/reconciler.js +0 -175
  129. package/assets/plugin/live/setup-buckets.d.ts +0 -7
  130. package/assets/plugin/live/setup-buckets.js +0 -33
  131. package/assets/plugin/live/slippage-tracker.d.ts +0 -45
  132. package/assets/plugin/live/slippage-tracker.js +0 -78
  133. package/assets/plugin/live/stop-watcher.d.ts +0 -67
  134. package/assets/plugin/live/stop-watcher.js +0 -218
  135. package/assets/plugin/live/user-data-active-probe.d.ts +0 -54
  136. package/assets/plugin/live/user-data-active-probe.js +0 -180
  137. package/assets/plugin/live/user-data-stream-controller.d.ts +0 -200
  138. package/assets/plugin/live/user-data-stream-controller.js +0 -579
  139. package/assets/plugin/live/user-data-stream-ws.d.ts +0 -22
  140. package/assets/plugin/live/user-data-stream-ws.js +0 -63
  141. package/assets/plugin/live/user-data-stream.d.ts +0 -243
  142. package/assets/plugin/live/user-data-stream.js +0 -704
  143. package/assets/plugin/logger.d.ts +0 -2
  144. package/assets/plugin/logger.js +0 -2
  145. package/assets/plugin/mfe.d.ts +0 -21
  146. package/assets/plugin/mfe.js +0 -68
  147. package/assets/plugin/onboarding/mode-ladder.d.ts +0 -1
  148. package/assets/plugin/onboarding/mode-ladder.js +0 -3
  149. package/assets/plugin/onboarding/runtime.d.ts +0 -90
  150. package/assets/plugin/onboarding/runtime.js +0 -184
  151. package/assets/plugin/openclaw.plugin.json +0 -92
  152. package/assets/plugin/paper-adapter.d.ts +0 -24
  153. package/assets/plugin/paper-adapter.js +0 -91
  154. package/assets/plugin/persistence/state-manager.d.ts +0 -66
  155. package/assets/plugin/persistence/state-manager.js +0 -222
  156. package/assets/plugin/pinned-plan.d.ts +0 -9
  157. package/assets/plugin/pinned-plan.js +0 -23
  158. package/assets/plugin/portfolio/reentry-tracker.d.ts +0 -36
  159. package/assets/plugin/portfolio/reentry-tracker.js +0 -127
  160. package/assets/plugin/portfolio/wave9-admission.d.ts +0 -67
  161. package/assets/plugin/portfolio/wave9-admission.js +0 -262
  162. package/assets/plugin/portfolio/wave9-policy.d.ts +0 -36
  163. package/assets/plugin/portfolio/wave9-policy.js +0 -183
  164. package/assets/plugin/risk/pre-trade-check.d.ts +0 -38
  165. package/assets/plugin/risk/pre-trade-check.js +0 -345
  166. package/assets/plugin/risk/pre-trade-types.d.ts +0 -60
  167. package/assets/plugin/risk/pre-trade-types.js +0 -3
  168. package/assets/plugin/shadow/shadow-tracker.d.ts +0 -36
  169. package/assets/plugin/shadow/shadow-tracker.js +0 -151
  170. package/assets/plugin/shadow/types.d.ts +0 -42
  171. package/assets/plugin/shadow/types.js +0 -20
  172. package/assets/plugin/shared/indicators-extended.d.ts +0 -52
  173. package/assets/plugin/shared/indicators-extended.js +0 -291
  174. package/assets/plugin/shared/indicators.d.ts +0 -15
  175. package/assets/plugin/shared/indicators.js +0 -114
  176. package/assets/plugin/signals/conditions/registry.d.ts +0 -16
  177. package/assets/plugin/signals/conditions/registry.js +0 -1333
  178. package/assets/plugin/signals/conditions/types.d.ts +0 -1
  179. package/assets/plugin/signals/conditions/types.js +0 -4
  180. package/assets/plugin/signals/direction-rules.d.ts +0 -3
  181. package/assets/plugin/signals/direction-rules.js +0 -24
  182. package/assets/plugin/signals/entry-rules.d.ts +0 -6
  183. package/assets/plugin/signals/entry-rules.js +0 -33
  184. package/assets/plugin/signals/serialize-context.d.ts +0 -4
  185. package/assets/plugin/signals/serialize-context.js +0 -39
  186. package/assets/plugin/signals/stop-rules.d.ts +0 -3
  187. package/assets/plugin/signals/stop-rules.js +0 -48
  188. package/assets/plugin/signals/strategy-adapter.d.ts +0 -47
  189. package/assets/plugin/signals/strategy-adapter.js +0 -209
  190. package/assets/plugin/signals/types.d.ts +0 -1
  191. package/assets/plugin/signals/types.js +0 -8
  192. package/assets/plugin/simulator/exchange-simulator.d.ts +0 -105
  193. package/assets/plugin/simulator/exchange-simulator.js +0 -759
  194. package/assets/plugin/simulator/fill-engine.d.ts +0 -53
  195. package/assets/plugin/simulator/fill-engine.js +0 -280
  196. package/assets/plugin/simulator/paper-market-feed.d.ts +0 -26
  197. package/assets/plugin/simulator/paper-market-feed.js +0 -104
  198. package/assets/plugin/simulator/realistic-fills.d.ts +0 -59
  199. package/assets/plugin/simulator/realistic-fills.js +0 -175
  200. package/assets/plugin/simulator/types.d.ts +0 -228
  201. package/assets/plugin/simulator/types.js +0 -43
  202. package/assets/plugin/strategy/builtin-strategies.d.ts +0 -2
  203. package/assets/plugin/strategy/builtin-strategies.js +0 -113
  204. package/assets/plugin/strategy/condition-registry.d.ts +0 -3
  205. package/assets/plugin/strategy/condition-registry.js +0 -153
  206. package/assets/plugin/strategy/evaluator.d.ts +0 -70
  207. package/assets/plugin/strategy/evaluator.js +0 -98
  208. package/assets/plugin/tools/assessment-validation.d.ts +0 -141
  209. package/assets/plugin/tools/assessment-validation.js +0 -473
  210. package/assets/plugin/tools/attach-brackets.d.ts +0 -39
  211. package/assets/plugin/tools/attach-brackets.js +0 -564
  212. package/assets/plugin/tools/audit-bracket-protection.d.ts +0 -49
  213. package/assets/plugin/tools/audit-bracket-protection.js +0 -683
  214. package/assets/plugin/tools/bracket-control.d.ts +0 -12
  215. package/assets/plugin/tools/bracket-control.js +0 -35
  216. package/assets/plugin/tools/cancel-all-orders.d.ts +0 -9
  217. package/assets/plugin/tools/cancel-all-orders.js +0 -8
  218. package/assets/plugin/tools/cancel-order.d.ts +0 -14
  219. package/assets/plugin/tools/cancel-order.js +0 -60
  220. package/assets/plugin/tools/check-position-health.d.ts +0 -46
  221. package/assets/plugin/tools/check-position-health.js +0 -194
  222. package/assets/plugin/tools/clear-exchange-credentials.d.ts +0 -24
  223. package/assets/plugin/tools/clear-exchange-credentials.js +0 -70
  224. package/assets/plugin/tools/close-position.d.ts +0 -45
  225. package/assets/plugin/tools/close-position.js +0 -722
  226. package/assets/plugin/tools/create-order.d.ts +0 -82
  227. package/assets/plugin/tools/create-order.js +0 -1544
  228. package/assets/plugin/tools/exit-gate.d.ts +0 -58
  229. package/assets/plugin/tools/exit-gate.js +0 -162
  230. package/assets/plugin/tools/fetch-balance.d.ts +0 -5
  231. package/assets/plugin/tools/fetch-balance.js +0 -4
  232. package/assets/plugin/tools/fetch-ohlcv.d.ts +0 -11
  233. package/assets/plugin/tools/fetch-ohlcv.js +0 -8
  234. package/assets/plugin/tools/fetch-open-orders.d.ts +0 -7
  235. package/assets/plugin/tools/fetch-open-orders.js +0 -4
  236. package/assets/plugin/tools/fetch-positions.d.ts +0 -7
  237. package/assets/plugin/tools/fetch-positions.js +0 -4
  238. package/assets/plugin/tools/fetch-ticker.d.ts +0 -11
  239. package/assets/plugin/tools/fetch-ticker.js +0 -5
  240. package/assets/plugin/tools/get-agent-profile.d.ts +0 -4
  241. package/assets/plugin/tools/get-agent-profile.js +0 -6
  242. package/assets/plugin/tools/get-analytics.d.ts +0 -6
  243. package/assets/plugin/tools/get-analytics.js +0 -7
  244. package/assets/plugin/tools/get-backtest.d.ts +0 -12
  245. package/assets/plugin/tools/get-backtest.js +0 -91
  246. package/assets/plugin/tools/get-basis.d.ts +0 -7
  247. package/assets/plugin/tools/get-basis.js +0 -7
  248. package/assets/plugin/tools/get-bracket-config.d.ts +0 -11
  249. package/assets/plugin/tools/get-bracket-config.js +0 -24
  250. package/assets/plugin/tools/get-cascade-risk.d.ts +0 -7
  251. package/assets/plugin/tools/get-cascade-risk.js +0 -8
  252. package/assets/plugin/tools/get-crypto-metrics.d.ts +0 -18
  253. package/assets/plugin/tools/get-crypto-metrics.js +0 -62
  254. package/assets/plugin/tools/get-cvd.d.ts +0 -6
  255. package/assets/plugin/tools/get-cvd.js +0 -6
  256. package/assets/plugin/tools/get-divergences.d.ts +0 -6
  257. package/assets/plugin/tools/get-divergences.js +0 -6
  258. package/assets/plugin/tools/get-funding-context.d.ts +0 -6
  259. package/assets/plugin/tools/get-funding-context.js +0 -16
  260. package/assets/plugin/tools/get-liquidation-levels.d.ts +0 -7
  261. package/assets/plugin/tools/get-liquidation-levels.js +0 -7
  262. package/assets/plugin/tools/get-liquidation-pulse.d.ts +0 -9
  263. package/assets/plugin/tools/get-liquidation-pulse.js +0 -22
  264. package/assets/plugin/tools/get-market-breadth.d.ts +0 -6
  265. package/assets/plugin/tools/get-market-breadth.js +0 -8
  266. package/assets/plugin/tools/get-market-intel.d.ts +0 -19
  267. package/assets/plugin/tools/get-market-intel.js +0 -116
  268. package/assets/plugin/tools/get-market-structure.d.ts +0 -47
  269. package/assets/plugin/tools/get-market-structure.js +0 -198
  270. package/assets/plugin/tools/get-my-mined-patterns.d.ts +0 -20
  271. package/assets/plugin/tools/get-my-mined-patterns.js +0 -61
  272. package/assets/plugin/tools/get-my-proposed-learnings.d.ts +0 -20
  273. package/assets/plugin/tools/get-my-proposed-learnings.js +0 -55
  274. package/assets/plugin/tools/get-my-recent-reviews.d.ts +0 -22
  275. package/assets/plugin/tools/get-my-recent-reviews.js +0 -66
  276. package/assets/plugin/tools/get-orderbook.d.ts +0 -21
  277. package/assets/plugin/tools/get-orderbook.js +0 -32
  278. package/assets/plugin/tools/get-pattern-scan.d.ts +0 -7
  279. package/assets/plugin/tools/get-pattern-scan.js +0 -8
  280. package/assets/plugin/tools/get-regime.d.ts +0 -6
  281. package/assets/plugin/tools/get-regime.js +0 -7
  282. package/assets/plugin/tools/get-relevant-learnings.d.ts +0 -21
  283. package/assets/plugin/tools/get-relevant-learnings.js +0 -65
  284. package/assets/plugin/tools/get-resting-liquidity.d.ts +0 -6
  285. package/assets/plugin/tools/get-resting-liquidity.js +0 -11
  286. package/assets/plugin/tools/get-risk-scenario.d.ts +0 -29
  287. package/assets/plugin/tools/get-risk-scenario.js +0 -47
  288. package/assets/plugin/tools/get-risk-summary.d.ts +0 -51
  289. package/assets/plugin/tools/get-risk-summary.js +0 -118
  290. package/assets/plugin/tools/get-sentiment.d.ts +0 -4
  291. package/assets/plugin/tools/get-sentiment.js +0 -6
  292. package/assets/plugin/tools/get-session-review.d.ts +0 -7
  293. package/assets/plugin/tools/get-session-review.js +0 -8
  294. package/assets/plugin/tools/get-setup-detail.d.ts +0 -7
  295. package/assets/plugin/tools/get-setup-detail.js +0 -322
  296. package/assets/plugin/tools/get-signals.d.ts +0 -15
  297. package/assets/plugin/tools/get-signals.js +0 -54
  298. package/assets/plugin/tools/get-sizing.d.ts +0 -6
  299. package/assets/plugin/tools/get-sizing.js +0 -6
  300. package/assets/plugin/tools/get-trade-feedback.d.ts +0 -7
  301. package/assets/plugin/tools/get-trade-feedback.js +0 -8
  302. package/assets/plugin/tools/get-trade-flow.d.ts +0 -7
  303. package/assets/plugin/tools/get-trade-flow.js +0 -7
  304. package/assets/plugin/tools/get-volume-analysis.d.ts +0 -21
  305. package/assets/plugin/tools/get-volume-analysis.js +0 -74
  306. package/assets/plugin/tools/get-volume-profile.d.ts +0 -7
  307. package/assets/plugin/tools/get-volume-profile.js +0 -7
  308. package/assets/plugin/tools/get-wave9-status.d.ts +0 -127
  309. package/assets/plugin/tools/get-wave9-status.js +0 -796
  310. package/assets/plugin/tools/helpers.d.ts +0 -26
  311. package/assets/plugin/tools/helpers.js +0 -39
  312. package/assets/plugin/tools/intel-api.d.ts +0 -34
  313. package/assets/plugin/tools/intel-api.js +0 -119
  314. package/assets/plugin/tools/intel-cache.d.ts +0 -25
  315. package/assets/plugin/tools/intel-cache.js +0 -148
  316. package/assets/plugin/tools/list-strategies.d.ts +0 -17
  317. package/assets/plugin/tools/list-strategies.js +0 -23
  318. package/assets/plugin/tools/modify-stop.d.ts +0 -21
  319. package/assets/plugin/tools/modify-stop.js +0 -120
  320. package/assets/plugin/tools/modify-target.d.ts +0 -21
  321. package/assets/plugin/tools/modify-target.js +0 -110
  322. package/assets/plugin/tools/propose-learning.d.ts +0 -22
  323. package/assets/plugin/tools/propose-learning.js +0 -65
  324. package/assets/plugin/tools/query-review-outcomes.d.ts +0 -30
  325. package/assets/plugin/tools/query-review-outcomes.js +0 -64
  326. package/assets/plugin/tools/query-trades.d.ts +0 -21
  327. package/assets/plugin/tools/query-trades.js +0 -37
  328. package/assets/plugin/tools/record-position-reviews.d.ts +0 -38
  329. package/assets/plugin/tools/record-position-reviews.js +0 -147
  330. package/assets/plugin/tools/save-strategy.d.ts +0 -16
  331. package/assets/plugin/tools/save-strategy.js +0 -46
  332. package/assets/plugin/tools/scan-pairs.d.ts +0 -22
  333. package/assets/plugin/tools/scan-pairs.js +0 -234
  334. package/assets/plugin/tools/score-setup.d.ts +0 -31
  335. package/assets/plugin/tools/score-setup.js +0 -268
  336. package/assets/plugin/tools/set-bracket-requirement.d.ts +0 -18
  337. package/assets/plugin/tools/set-bracket-requirement.js +0 -81
  338. package/assets/plugin/tools/set-exchange-credentials.d.ts +0 -25
  339. package/assets/plugin/tools/set-exchange-credentials.js +0 -80
  340. package/assets/plugin/tools/set-trading-mode.d.ts +0 -26
  341. package/assets/plugin/tools/set-trading-mode.js +0 -135
  342. package/assets/plugin/tools/test-exchange-credentials.d.ts +0 -16
  343. package/assets/plugin/tools/test-exchange-credentials.js +0 -100
  344. package/assets/plugin/tools/toggle-strategy.d.ts +0 -8
  345. package/assets/plugin/tools/toggle-strategy.js +0 -15
  346. package/assets/plugin/trading-params-cache.d.ts +0 -26
  347. package/assets/plugin/trading-params-cache.js +0 -52
  348. package/assets/plugin/types.d.ts +0 -134
  349. package/assets/plugin/types.js +0 -7
  350. package/assets/plugin/util/plugin-paths.d.ts +0 -3
  351. package/assets/plugin/util/plugin-paths.js +0 -15
  352. package/assets/plugin/venues/hyperliquid/hl-balance.d.ts +0 -116
  353. package/assets/plugin/venues/hyperliquid/hl-balance.js +0 -145
  354. package/assets/plugin/venues/hyperliquid/hl-bracket-coordinator.d.ts +0 -123
  355. package/assets/plugin/venues/hyperliquid/hl-bracket-coordinator.js +0 -533
  356. package/assets/plugin/venues/hyperliquid/hl-brackets.d.ts +0 -102
  357. package/assets/plugin/venues/hyperliquid/hl-brackets.js +0 -172
  358. package/assets/plugin/venues/hyperliquid/hl-cloid.d.ts +0 -22
  359. package/assets/plugin/venues/hyperliquid/hl-cloid.js +0 -82
  360. package/assets/plugin/venues/hyperliquid/hl-info-cache.d.ts +0 -46
  361. package/assets/plugin/venues/hyperliquid/hl-info-cache.js +0 -125
  362. package/assets/plugin/venues/hyperliquid/hl-live-adapter.d.ts +0 -146
  363. package/assets/plugin/venues/hyperliquid/hl-live-adapter.js +0 -728
  364. package/assets/plugin/venues/hyperliquid/hl-precision.d.ts +0 -61
  365. package/assets/plugin/venues/hyperliquid/hl-precision.js +0 -176
  366. package/assets/plugin/venues/hyperliquid/hl-private.d.ts +0 -88
  367. package/assets/plugin/venues/hyperliquid/hl-private.js +0 -357
  368. package/assets/plugin/venues/hyperliquid/hl-public.d.ts +0 -79
  369. package/assets/plugin/venues/hyperliquid/hl-public.js +0 -436
  370. package/assets/plugin/venues/hyperliquid/hl-rate-gate.d.ts +0 -57
  371. package/assets/plugin/venues/hyperliquid/hl-rate-gate.js +0 -220
  372. package/assets/plugin/venues/hyperliquid/hl-user-stream.d.ts +0 -90
  373. package/assets/plugin/venues/hyperliquid/hl-user-stream.js +0 -220
  374. package/assets/plugin/venues/registry.d.ts +0 -38
  375. package/assets/plugin/venues/registry.js +0 -46
  376. package/assets/plugin/venues/symbols.d.ts +0 -43
  377. package/assets/plugin/venues/symbols.js +0 -107
  378. package/assets/plugin/wave9/live-account-capture.d.ts +0 -67
  379. package/assets/plugin/wave9/live-account-capture.js +0 -435
  380. package/assets/plugin/wave9/live-autonomous-protection.d.ts +0 -39
  381. package/assets/plugin/wave9/live-autonomous-protection.js +0 -112
  382. package/assets/plugin/wave9/live-durable-reconciliation-scheduler.d.ts +0 -33
  383. package/assets/plugin/wave9/live-durable-reconciliation-scheduler.js +0 -115
  384. package/assets/plugin/wave9/live-execution-ledger.d.ts +0 -107
  385. package/assets/plugin/wave9/live-execution-ledger.js +0 -498
  386. package/assets/plugin/wave9/live-position-confirmation.d.ts +0 -18
  387. package/assets/plugin/wave9/live-position-confirmation.js +0 -111
  388. package/assets/plugin/wave9/live-residual-protection.d.ts +0 -18
  389. package/assets/plugin/wave9/live-residual-protection.js +0 -250
  390. package/assets/plugin/wave9/live-startup-reconciliation.d.ts +0 -38
  391. package/assets/plugin/wave9/live-startup-reconciliation.js +0 -454
  392. package/assets/plugin/wave9/live-symbol-ownership.d.ts +0 -20
  393. package/assets/plugin/wave9/live-symbol-ownership.js +0 -132
  394. package/assets/plugin/wave9/paper-admission-guard.d.ts +0 -199
  395. package/assets/plugin/wave9/paper-admission-guard.js +0 -650
  396. package/assets/plugin/wave9/usdm-evidence-provider.d.ts +0 -42
  397. package/assets/plugin/wave9/usdm-evidence-provider.js +0 -133
@@ -1,450 +0,0 @@
1
- // LiveStateStore — in-memory account state fed by the user-data WebSocket.
2
- //
3
- // Design notes:
4
- // - Pure state machine. No IO. No timers. No network calls. All testable
5
- // with synchronous unit tests + snapshot assertions.
6
- // - Writes come from two sources:
7
- // 1. `applySnapshot(snap)` — authoritative REST snapshot taken on
8
- // connect + reconnect + forced resync. Replaces state wholesale.
9
- // 2. `applyAccountUpdate(ev)` / `applyOrderUpdate(ev)` — WS deltas that
10
- // mutate state per-symbol / per-asset / per-orderId.
11
- // - Reads (`getPositions` / `getBalance` / `getOpenOrders`) return
12
- // STRUCTURAL CLONES. Consumers can't mutate the store by accident.
13
- // - `diffAgainstSnapshot(rest)` compares local state vs a REST truth-check.
14
- // Drifts are classified minor/major; parent decides whether to force resync.
15
- // - Idempotent snapshot apply — a snapshot replaces rather than appends, so
16
- // a duplicate snapshot doesn't double-count.
17
- // - No hedge-mode support — v1 is one-way only. If a position event with
18
- // positionSide=LONG/SHORT (not BOTH) arrives, we log a warning and apply
19
- // by symbol (first-write-wins). Parent refuses to enable observe/enforce
20
- // on hedge-mode accounts at a higher layer.
21
- //
22
- // Binance event shapes (user-data stream, Futures):
23
- // ACCOUNT_UPDATE.a.P[i] = { s: symbol, ps: 'LONG'|'SHORT'|'BOTH',
24
- // pa: positionAmt, ep: entryPrice,
25
- // up: unrealizedPnl, mt: 'cross'|'isolated',
26
- // cr: cumulativeRealized (optional) }
27
- // ACCOUNT_UPDATE.a.B[i] = { a: asset, wb: walletBalance, cw: crossWallet,
28
- // bc: balanceChange }
29
- // ORDER_TRADE_UPDATE.o = { s: symbol, i: orderId, c: clientOrderId,
30
- // S: 'BUY'|'SELL', o: orderType, f: timeInForce,
31
- // q: origQty, p: origPrice, ap: avgPrice,
32
- // x: execType ('NEW'|'TRADE'|'CANCELED'|'EXPIRED'|'REJECTED'|...),
33
- // X: orderStatus ('NEW'|'PARTIALLY_FILLED'|'FILLED'|...),
34
- // l: lastFilledQty, z: cumFilledQty, L: lastFillPrice,
35
- // n: commission, N: commissionAsset, T: transactTime }
36
- //
37
- // We translate into our narrower domain types (CcxtPosition, CcxtBalance,
38
- // CcxtOrder) at apply time so the rest of the plugin sees one shape only.
39
- import { EventEmitter } from 'node:events';
40
- import { parseBracketCid } from './bracket-id.js';
41
- import { logger } from '../logger.js';
42
- const TAG = 'live-state-store';
43
- const DEFAULT_THRESHOLDS = {
44
- balanceMinorBps: 10, // 0.1%
45
- positionMinorContracts: 1e-6, // essentially any nonzero is major
46
- };
47
- export class LiveStateStore extends EventEmitter {
48
- // Positions keyed by symbol (one-way mode: one position per symbol).
49
- positions = new Map();
50
- // Balance keyed by currency.
51
- balances = new Map();
52
- // Open orders keyed by exchange orderId.
53
- orders = new Map();
54
- // Last-apply timestamps for observability.
55
- lastSnapshotAt = null;
56
- lastAccountUpdateAt = null;
57
- lastOrderUpdateAt = null;
58
- thresholds;
59
- constructor(thresholds = {}) {
60
- super();
61
- this.thresholds = { ...DEFAULT_THRESHOLDS, ...thresholds };
62
- }
63
- // ---- Reads (synchronous, safe) ----
64
- /** Get positions, optionally filtered by symbol. Returns clones. */
65
- getPositions(symbol) {
66
- if (symbol) {
67
- const p = this.positions.get(symbol);
68
- return p ? [clonePosition(p)] : [];
69
- }
70
- return Array.from(this.positions.values()).map(clonePosition);
71
- }
72
- /** Get the current balance view. Matches the CCXT shape. */
73
- getBalance() {
74
- const free = {};
75
- const used = {};
76
- const total = {};
77
- const result = { free, used, total };
78
- for (const [cur, b] of this.balances) {
79
- free[cur] = b.free;
80
- used[cur] = b.used;
81
- total[cur] = b.total;
82
- result[cur] = { ...b };
83
- }
84
- return result;
85
- }
86
- /** Get open orders, optionally filtered by symbol. Returns clones. */
87
- getOpenOrders(symbol) {
88
- const all = Array.from(this.orders.values());
89
- const filtered = symbol ? all.filter(o => o.symbol === symbol) : all;
90
- return filtered.map(cloneOrder);
91
- }
92
- /** Observability — last-apply timestamps for each write path. */
93
- getHealth() {
94
- return {
95
- lastSnapshotAt: this.lastSnapshotAt,
96
- lastAccountUpdateAt: this.lastAccountUpdateAt,
97
- lastOrderUpdateAt: this.lastOrderUpdateAt,
98
- positionCount: this.positions.size,
99
- orderCount: this.orders.size,
100
- balanceAssetCount: this.balances.size,
101
- };
102
- }
103
- // ---- Writes ----
104
- /** Replace state with a REST snapshot. Called on connect + reconnect + forced resync.
105
- * Idempotent: a duplicate snapshot produces identical state. */
106
- applySnapshot(snap) {
107
- this.positions.clear();
108
- for (const p of snap.positions) {
109
- if (p.contracts > 0) {
110
- this.positions.set(p.symbol, clonePosition(p));
111
- }
112
- }
113
- this.balances.clear();
114
- if (snap.balance) {
115
- for (const cur of Object.keys(snap.balance.total ?? {})) {
116
- const total = snap.balance.total[cur] ?? 0;
117
- const free = snap.balance.free[cur] ?? 0;
118
- const used = snap.balance.used[cur] ?? 0;
119
- if (total > 0 || free > 0 || used > 0) {
120
- this.balances.set(cur, { free, used, total });
121
- }
122
- }
123
- }
124
- this.orders.clear();
125
- for (const o of snap.openOrders) {
126
- if (o.status === 'open' && o.id) {
127
- this.orders.set(o.id, cloneOrder(o));
128
- }
129
- }
130
- this.lastSnapshotAt = snap.timestamp;
131
- this.emit('stateChanged', 'snapshot');
132
- }
133
- /** Replace the algo-order subset of the store with a fresh REST list.
134
- *
135
- * Binance's user-data WS does NOT emit ORDER_TRADE_UPDATE for algo orders
136
- * (STOP_MARKET / TAKE_PROFIT_MARKET) until they trigger — only the resulting
137
- * regular order fires the event. As a result, the store cannot observe algo
138
- * add/cancel/modify events via WS alone and diverges from REST whenever
139
- * brackets are touched.
140
- *
141
- * This method closes that gap: callers (the controller's refresh loop) hand
142
- * it the current REST view of algo orders, and we swap them in wholesale
143
- * while leaving regular orders (WS-tracked) untouched. An order is classed
144
- * as "algo" iff its clientOrderId parses as a reefclaw bracket cid with
145
- * role stop or target. External algo orders (manual STOP_MARKET placed via
146
- * Binance UI with no rc- prefix) are NOT tracked by this path — the 60s
147
- * reconciler snapshot still covers them. */
148
- replaceAlgoOrders(freshAlgoOrders) {
149
- let removedStale = 0;
150
- for (const [id, order] of this.orders) {
151
- if (isAlgoBracketOrder(order)) {
152
- this.orders.delete(id);
153
- removedStale++;
154
- }
155
- }
156
- let addedFresh = 0;
157
- for (const o of freshAlgoOrders) {
158
- if (!o.id || o.status !== 'open')
159
- continue;
160
- if (!isAlgoBracketOrder(o))
161
- continue;
162
- this.orders.set(o.id, cloneOrder(o));
163
- addedFresh++;
164
- }
165
- if (removedStale !== addedFresh) {
166
- logger.info('live-state-store', `replaceAlgoOrders: ${removedStale} removed, ${addedFresh} added`);
167
- }
168
- this.emit('stateChanged', 'algo_refresh');
169
- }
170
- /** Refresh ONLY the mark-derived soft fields (markPrice + unrealizedPnl) of
171
- * positions that already exist in the store, from a fresh REST snapshot.
172
- *
173
- * Why this exists: Binance's user-data `ACCOUNT_UPDATE` is event-driven
174
- * (fills / funding / transfers) and carries NO per-tick mark price, so a
175
- * quiet open position's `unrealizedPnl` in this store is FROZEN at the last
176
- * event's value while the Binance app recomputes uPnl every mark tick. In
177
- * enforce/observe mode this store is the authoritative read path, so the
178
- * dashboard's Unrealized cell froze between events ("close but lags/frozen"
179
- * — 2026-05-16). The controller's 60s truth-check already fetches a fresh
180
- * REST snapshot (with live uPnl + mark) but DISCARDS it unless position
181
- * structure drifts (diffPositions ignores uPnl entirely). This method lets
182
- * the truth-check spend that already-paid REST read on a uPnl refresh
183
- * instead of throwing it away — bounding uPnl staleness to the 60s interval
184
- * rather than "until the next trade/funding event".
185
- *
186
- * Strictly bounded — this is NOT applySnapshot:
187
- * - only mutates positions present in BOTH the store and the fresh REST
188
- * list with the SAME symbol AND side (structural changes are the
189
- * truth-check's job, not this method's);
190
- * - never adds, never removes, never touches balance or orders;
191
- * - so it cannot reintroduce the null≠empty / stale-as-truth collapse
192
- * class (callers only reach here with a non-null REST snapshot anyway —
193
- * buildSnapshot throws UntrustedSnapshotError on a failed fetch). */
194
- refreshDerivedMarkFields(restPositions) {
195
- let refreshed = 0;
196
- for (const rp of restPositions) {
197
- if (rp.contracts <= 0)
198
- continue;
199
- const lp = this.positions.get(rp.symbol);
200
- if (!lp || lp.side !== rp.side)
201
- continue; // structural change → leave for truth-check
202
- if (lp.markPrice === rp.markPrice && lp.unrealizedPnl === rp.unrealizedPnl)
203
- continue;
204
- this.positions.set(rp.symbol, {
205
- ...lp,
206
- markPrice: rp.markPrice,
207
- unrealizedPnl: rp.unrealizedPnl,
208
- });
209
- refreshed++;
210
- }
211
- if (refreshed > 0) {
212
- this.emit('stateChanged', 'mark_refresh');
213
- }
214
- }
215
- /** Apply an ACCOUNT_UPDATE event (positions + balance deltas). */
216
- applyAccountUpdate(ev) {
217
- for (const pos of ev.positions) {
218
- // Refuse hedge-mode position events — v1 is one-way. `BOTH` is one-way;
219
- // `LONG`/`SHORT` on a one-way account shouldn't happen but if it does
220
- // we warn and still apply by symbol.
221
- if (pos.positionSide === 'LONG' || pos.positionSide === 'SHORT') {
222
- logger.warn(TAG, `Hedge-mode position event received for ${pos.symbol} (positionSide=${pos.positionSide}) — v1 is one-way only`);
223
- this.emit('applyError', 'hedge_mode_position', `${pos.symbol} positionSide=${pos.positionSide}`);
224
- // Fall through: still apply per symbol. Reconciler will catch drift.
225
- }
226
- if (pos.side === 'flat' || pos.quantity <= 0) {
227
- this.positions.delete(pos.symbol);
228
- }
229
- else {
230
- const existing = this.positions.get(pos.symbol);
231
- // Preserve metadata fields we don't receive via WS (setupType, thesis,
232
- // stopPrice, etc). They're set at open time by the plugin itself, not
233
- // by Binance. WS updates carry the numeric state; metadata carries over.
234
- const merged = {
235
- symbol: pos.symbol,
236
- side: pos.side,
237
- contracts: pos.quantity,
238
- contractSize: existing?.contractSize ?? 1,
239
- entryPrice: pos.entryPrice,
240
- markPrice: existing?.markPrice ?? pos.entryPrice,
241
- notional: pos.quantity * pos.entryPrice,
242
- unrealizedPnl: pos.unrealizedPnl,
243
- percentage: existing?.percentage ?? 0,
244
- timestamp: ev.eventTime,
245
- datetime: new Date(ev.eventTime).toISOString(),
246
- // Carry-over metadata
247
- setupType: existing?.setupType,
248
- thesis: existing?.thesis,
249
- stopPrice: existing?.stopPrice,
250
- targetPrice: existing?.targetPrice,
251
- regime: existing?.regime,
252
- regimeConfidence: existing?.regimeConfidence,
253
- scorecardVerdict: existing?.scorecardVerdict,
254
- confluenceScore: existing?.confluenceScore,
255
- };
256
- this.positions.set(pos.symbol, merged);
257
- }
258
- }
259
- for (const bal of ev.balances) {
260
- if (bal.walletBalance <= 0 && (this.balances.get(bal.asset)?.used ?? 0) <= 0) {
261
- // Zero wallet and no reserved margin: drop the asset so getBalance()
262
- // doesn't return a forest of empty entries.
263
- this.balances.delete(bal.asset);
264
- }
265
- else {
266
- const prev = this.balances.get(bal.asset);
267
- const used = prev?.used ?? 0;
268
- // `free` is derived — Binance's WS balance-change doesn't include
269
- // free/used split. We keep whatever `used` we already had (margin
270
- // lockup changes through position events, not balance events) and
271
- // compute `free = total - used`.
272
- const total = bal.walletBalance;
273
- const free = Math.max(0, total - used);
274
- this.balances.set(bal.asset, { free, used, total });
275
- }
276
- }
277
- this.lastAccountUpdateAt = ev.eventTime;
278
- this.emit('stateChanged', 'account_update');
279
- }
280
- /** Apply an ORDER_TRADE_UPDATE event (single order state transition). */
281
- applyOrderUpdate(ev) {
282
- const key = ev.orderId;
283
- if (ev.status === 'closed' || ev.status === 'canceled') {
284
- // Terminal — remove from open-orders view.
285
- this.orders.delete(key);
286
- }
287
- else {
288
- // open (NEW or PARTIALLY_FILLED)
289
- const existing = this.orders.get(key);
290
- const cctxType = ev.type === 'limit' ? 'limit' : 'market';
291
- const merged = {
292
- id: ev.orderId,
293
- symbol: ev.symbol,
294
- side: ev.side,
295
- type: cctxType,
296
- status: 'open',
297
- amount: ev.origQuantity,
298
- filled: ev.cumulativeFilled,
299
- remaining: Math.max(0, ev.origQuantity - ev.cumulativeFilled),
300
- average: ev.avgPrice,
301
- price: ev.origPrice,
302
- cost: ev.cumulativeFilled * (ev.avgPrice ?? 0),
303
- fee: existing?.fee ?? { cost: ev.commission, currency: ev.commissionAsset },
304
- timestamp: ev.transactionTime,
305
- datetime: new Date(ev.transactionTime).toISOString(),
306
- timeInForce: ev.timeInForce,
307
- clientOrderId: ev.clientOrderId,
308
- };
309
- this.orders.set(key, merged);
310
- }
311
- this.lastOrderUpdateAt = ev.eventTime;
312
- this.emit('stateChanged', 'order_update');
313
- }
314
- /** Clear all state. Used on shutdown/reset. */
315
- reset() {
316
- this.positions.clear();
317
- this.balances.clear();
318
- this.orders.clear();
319
- this.lastSnapshotAt = null;
320
- this.lastAccountUpdateAt = null;
321
- this.lastOrderUpdateAt = null;
322
- }
323
- // ---- Drift detection (60s truth-check) ----
324
- /** Diff local state vs a fresh REST snapshot. Classifies drifts by severity
325
- * so the parent reconciler can decide: log-only (minor) vs forced resync (major). */
326
- diffAgainstSnapshot(rest) {
327
- const positions = this.diffPositions(rest.positions);
328
- const balance = this.diffBalance(rest.balance);
329
- const orders = this.diffOrders(rest.openOrders);
330
- // Severity rollup
331
- const hasMajorPosition = positions.some(p => p.kind === 'new' || p.kind === 'closed' || p.kind === 'side_changed' ||
332
- Math.abs(p.localContracts - p.restContracts) > this.thresholds.positionMinorContracts);
333
- const hasMajorBalance = balance.some(b => Math.abs(b.deltaBps) >= this.thresholds.balanceMinorBps);
334
- const hasMajorOrder = orders.length > 0; // any order mismatch is major — small-N
335
- let severity = 'none';
336
- if (hasMajorPosition || hasMajorBalance || hasMajorOrder) {
337
- severity = 'major';
338
- }
339
- else if (positions.length > 0 || balance.length > 0) {
340
- severity = 'minor';
341
- }
342
- const summary = severity === 'none'
343
- ? 'no drift'
344
- : `${positions.length} position / ${balance.length} balance / ${orders.length} order diffs`;
345
- return { severity, positions, balance, orders, summary };
346
- }
347
- diffPositions(rest) {
348
- const drifts = [];
349
- const restMap = new Map(rest.filter(p => p.contracts > 0).map(p => [p.symbol, p]));
350
- for (const [symbol, rp] of restMap) {
351
- const lp = this.positions.get(symbol);
352
- if (!lp) {
353
- drifts.push({
354
- symbol,
355
- localContracts: 0, restContracts: rp.contracts,
356
- localSide: null, restSide: rp.side,
357
- kind: 'new',
358
- });
359
- }
360
- else if (lp.side !== rp.side) {
361
- drifts.push({
362
- symbol,
363
- localContracts: lp.contracts, restContracts: rp.contracts,
364
- localSide: lp.side, restSide: rp.side,
365
- kind: 'side_changed',
366
- });
367
- }
368
- else if (Math.abs(lp.contracts - rp.contracts) > this.thresholds.positionMinorContracts) {
369
- drifts.push({
370
- symbol,
371
- localContracts: lp.contracts, restContracts: rp.contracts,
372
- localSide: lp.side, restSide: rp.side,
373
- kind: 'size_changed',
374
- });
375
- }
376
- }
377
- for (const [symbol, lp] of this.positions) {
378
- if (!restMap.has(symbol)) {
379
- drifts.push({
380
- symbol,
381
- localContracts: lp.contracts, restContracts: 0,
382
- localSide: lp.side, restSide: null,
383
- kind: 'closed',
384
- });
385
- }
386
- }
387
- return drifts;
388
- }
389
- diffBalance(rest) {
390
- const drifts = [];
391
- if (!rest)
392
- return drifts;
393
- const restTotals = rest.total ?? {};
394
- const seen = new Set();
395
- for (const asset of Object.keys(restTotals)) {
396
- seen.add(asset);
397
- const restTotal = restTotals[asset] ?? 0;
398
- const local = this.balances.get(asset);
399
- const localTotal = local?.total ?? 0;
400
- if (Math.abs(localTotal - restTotal) < 1e-10)
401
- continue;
402
- const denom = Math.abs(restTotal) > 1e-10 ? Math.abs(restTotal) : 1;
403
- const deltaBps = ((localTotal - restTotal) / denom) * 10_000;
404
- drifts.push({ asset, localTotal, restTotal, deltaBps });
405
- }
406
- for (const [asset, b] of this.balances) {
407
- if (seen.has(asset))
408
- continue;
409
- // Asset present locally but absent from REST
410
- if (b.total > 1e-10) {
411
- drifts.push({
412
- asset, localTotal: b.total, restTotal: 0,
413
- deltaBps: 10_000, // effectively infinite divergence
414
- });
415
- }
416
- }
417
- return drifts;
418
- }
419
- diffOrders(rest) {
420
- const drifts = [];
421
- const restMap = new Map(rest.filter(o => o.status === 'open' && o.id).map(o => [o.id, o]));
422
- for (const [id, ro] of restMap) {
423
- if (!this.orders.has(id)) {
424
- drifts.push({ orderId: id, symbol: ro.symbol, kind: 'missing_locally' });
425
- }
426
- }
427
- for (const [id, lo] of this.orders) {
428
- if (!restMap.has(id)) {
429
- drifts.push({ orderId: id, symbol: lo.symbol, kind: 'missing_on_rest' });
430
- }
431
- }
432
- return drifts;
433
- }
434
- }
435
- // ---- Clone helpers ----
436
- function clonePosition(p) {
437
- return { ...p };
438
- }
439
- function cloneOrder(o) {
440
- return { ...o, fee: { ...o.fee } };
441
- }
442
- /** True iff an order is a reefclaw-managed bracket SL/TP (i.e. an algo order
443
- * we track). Regular entries with bracket-cid role 'entry' are NOT algo;
444
- * they fire normal ORDER_TRADE_UPDATE events and stay in the store via WS. */
445
- function isAlgoBracketOrder(o) {
446
- if (!o.clientOrderId)
447
- return false;
448
- const parsed = parseBracketCid(o.clientOrderId);
449
- return parsed !== null && (parsed.role === 'stop' || parsed.role === 'target');
450
- }
@@ -1,57 +0,0 @@
1
- import { FactSubscriber } from './fact-subscriber.js';
2
- import { type EvaluatorParams } from './local-strategy-evaluator.js';
3
- import type { StrategyConfig, SignalSnapshot } from '@reefclaw/shared';
4
- export interface LocalSignalServiceOptions {
5
- intelligenceUrl: string;
6
- connectionToken: string;
7
- /** Symbols to stream + evaluate locally. */
8
- symbols: string[];
9
- params?: EvaluatorParams;
10
- /** Strategy mirror refresh cadence (default 10 min). */
11
- strategyRefreshMs?: number;
12
- /** Local evaluation cadence (default 5s — matches the central engine). */
13
- evalIntervalMs?: number;
14
- /** Injected for tests. */
15
- fetchImpl?: typeof fetch;
16
- /** Injected for tests. */
17
- now?: () => number;
18
- /** Max age of a symbol's streamed fact before getSnapshot refuses to serve
19
- * it (default 60s = 12× the broadcaster's 5s cadence). A stale fact means
20
- * the stream is stalled/down — enforce-mode get_signals must fall back to
21
- * central rather than serve signals computed from old market data. */
22
- factStalenessMs?: number;
23
- }
24
- export declare class LocalSignalService {
25
- private readonly opts;
26
- private readonly subscriber;
27
- private readonly evaluator;
28
- private readonly params;
29
- private readonly doFetch;
30
- private readonly now;
31
- private strategies;
32
- private readonly statesCache;
33
- private readonly recent;
34
- private strategyTimer;
35
- private evalTimer;
36
- constructor(opts: LocalSignalServiceOptions);
37
- private factIsFresh;
38
- start(): Promise<void>;
39
- stop(): void;
40
- /** Latest locally-computed snapshot for a symbol, or null if no fact +
41
- * evaluation has happened yet OR the symbol's streamed fact has gone
42
- * stale (caller should fall back to central in both cases). */
43
- getSnapshot(symbol: string): SignalSnapshot | null;
44
- hasSnapshot(symbol: string): boolean;
45
- getStats(): {
46
- strategies: number;
47
- symbolsEvaluated: number;
48
- subscriber: ReturnType<FactSubscriber['getStats']>;
49
- };
50
- /** One evaluation cycle across all streamed symbols (mirrors the engine tick). */
51
- evalAll(): Promise<void>;
52
- private refreshStrategies;
53
- /** Test seam — set strategies without an HTTP fetch. */
54
- __setStrategiesForTest(s: StrategyConfig[]): void;
55
- /** Test seam — feed a raw SSE chunk to the subscriber. */
56
- __ingestForTest(chunk: string): void;
57
- }
@@ -1,151 +0,0 @@
1
- // Local signal service — facts-out (docs/FACTS_OUT_ARCHITECTURE.md) step 5.
2
- //
3
- // Runs the central signal engine's job LOCALLY in the plugin: subscribes to the
4
- // intel fact stream, mirrors the user's strategy configs (GET /api/strategies),
5
- // and evaluates them every ~5s with the shared LocalStrategyEvaluator — caching
6
- // per-symbol states + a recent-signals ring exactly like the central engine.
7
- // getSnapshot(symbol) returns the same SignalSnapshot shape get_signals serves.
8
- //
9
- // Gated by plugin-config `signals.evaluator` (central | shadow | enforce):
10
- // central (default) — service never created; get_signals calls intel as today.
11
- // shadow — service runs; get_signals still returns central but logs
12
- // the local snapshot for comparison. Zero behaviour change.
13
- // enforce — get_signals returns the local snapshot (falling back to
14
- // central when no fact has arrived for that symbol yet).
15
- import { FactSubscriber } from './fact-subscriber.js';
16
- import { LocalStrategyEvaluator, DEFAULT_EVALUATOR_PARAMS } from './local-strategy-evaluator.js';
17
- const RECENT_RING = 50;
18
- const DEFAULT_FACT_STALENESS_MS = 60_000;
19
- function isDeclarativeConfig(config) {
20
- return config.executionModel === undefined || config.executionModel === 'declarative';
21
- }
22
- export class LocalSignalService {
23
- opts;
24
- subscriber;
25
- evaluator = new LocalStrategyEvaluator();
26
- params;
27
- doFetch;
28
- now;
29
- strategies = [];
30
- statesCache = new Map();
31
- recent = new Map();
32
- strategyTimer = null;
33
- evalTimer = null;
34
- constructor(opts) {
35
- this.opts = opts;
36
- this.params = opts.params ?? DEFAULT_EVALUATOR_PARAMS;
37
- this.doFetch = opts.fetchImpl ?? fetch;
38
- this.now = opts.now ?? Date.now;
39
- this.subscriber = new FactSubscriber({
40
- baseUrl: opts.intelligenceUrl,
41
- token: opts.connectionToken,
42
- symbols: opts.symbols,
43
- fetchImpl: opts.fetchImpl,
44
- now: opts.now,
45
- });
46
- }
47
- factIsFresh(symbol) {
48
- const at = this.subscriber.getLatestFactAt(symbol);
49
- if (at === null)
50
- return false;
51
- return this.now() - at <= (this.opts.factStalenessMs ?? DEFAULT_FACT_STALENESS_MS);
52
- }
53
- async start() {
54
- await this.refreshStrategies();
55
- this.strategyTimer = setInterval(() => void this.refreshStrategies(), this.opts.strategyRefreshMs ?? 600_000);
56
- this.evalTimer = setInterval(() => void this.evalAll(), this.opts.evalIntervalMs ?? 5_000);
57
- // Don't let the background timers hold the process open during shutdown.
58
- this.strategyTimer.unref?.();
59
- this.evalTimer.unref?.();
60
- this.subscriber.start();
61
- }
62
- stop() {
63
- if (this.strategyTimer) {
64
- clearInterval(this.strategyTimer);
65
- this.strategyTimer = null;
66
- }
67
- if (this.evalTimer) {
68
- clearInterval(this.evalTimer);
69
- this.evalTimer = null;
70
- }
71
- this.subscriber.stop();
72
- }
73
- /** Latest locally-computed snapshot for a symbol, or null if no fact +
74
- * evaluation has happened yet OR the symbol's streamed fact has gone
75
- * stale (caller should fall back to central in both cases). */
76
- getSnapshot(symbol) {
77
- const states = this.statesCache.get(symbol);
78
- if (!states)
79
- return null;
80
- if (!this.factIsFresh(symbol))
81
- return null;
82
- return {
83
- activeStrategies: states,
84
- recentSignals: this.recent.get(symbol) ?? [],
85
- timestamp: new Date(this.now()).toISOString(),
86
- scope: 'local',
87
- };
88
- }
89
- hasSnapshot(symbol) {
90
- return this.statesCache.has(symbol);
91
- }
92
- getStats() {
93
- return {
94
- strategies: this.strategies.length,
95
- symbolsEvaluated: this.statesCache.size,
96
- subscriber: this.subscriber.getStats(),
97
- };
98
- }
99
- /** One evaluation cycle across all streamed symbols (mirrors the engine tick). */
100
- async evalAll() {
101
- if (this.strategies.length === 0)
102
- return;
103
- const now = this.now();
104
- for (const symbol of this.opts.symbols) {
105
- const ctx = this.subscriber.getLatest(symbol);
106
- if (!ctx)
107
- continue;
108
- // Don't re-evaluate stale contexts — getSnapshot refuses them anyway.
109
- if (!this.factIsFresh(symbol))
110
- continue;
111
- const { states, signals } = await this.evaluator.evaluateSnapshot(ctx, this.strategies, now, this.params);
112
- this.statesCache.set(symbol, states);
113
- if (signals.length > 0) {
114
- const ring = this.recent.get(symbol) ?? [];
115
- ring.unshift(...signals);
116
- if (ring.length > RECENT_RING)
117
- ring.length = RECENT_RING;
118
- this.recent.set(symbol, ring);
119
- }
120
- }
121
- }
122
- async refreshStrategies() {
123
- try {
124
- const resp = await this.doFetch(`${this.opts.intelligenceUrl}/api/strategies?active=true`, {
125
- headers: { Authorization: `Bearer ${this.opts.connectionToken}` },
126
- });
127
- if (!resp.ok)
128
- return;
129
- const body = (await resp.json());
130
- if (!Array.isArray(body.strategies))
131
- return;
132
- const configs = body.strategies
133
- .map((r) => r.config)
134
- .filter((c) => !!c && isDeclarativeConfig(c));
135
- // A valid empty list means all generic strategies are off (or only a
136
- // dedicated portfolio bundle is active), so clear stale generic rows.
137
- this.strategies = configs;
138
- }
139
- catch {
140
- /* keep last-known strategies — fail-open */
141
- }
142
- }
143
- /** Test seam — set strategies without an HTTP fetch. */
144
- __setStrategiesForTest(s) {
145
- this.strategies = s.filter((config) => isDeclarativeConfig(config));
146
- }
147
- /** Test seam — feed a raw SSE chunk to the subscriber. */
148
- __ingestForTest(chunk) {
149
- this.subscriber.ingest(chunk);
150
- }
151
- }