@reefclaw/connect 0.1.12 → 0.1.13

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 (390) hide show
  1. package/assets/plugin/audit/mode-transition-audit.d.ts +11 -0
  2. package/assets/plugin/audit/mode-transition-audit.js +29 -0
  3. package/assets/plugin/balance-utils.d.ts +36 -0
  4. package/assets/plugin/balance-utils.js +98 -0
  5. package/assets/plugin/ccxt/binance-ban-gate.d.ts +47 -0
  6. package/assets/plugin/ccxt/binance-ban-gate.js +420 -0
  7. package/assets/plugin/ccxt/binance-private.d.ts +346 -0
  8. package/assets/plugin/ccxt/binance-private.js +1525 -0
  9. package/assets/plugin/ccxt/binance-public.d.ts +34 -0
  10. package/assets/plugin/ccxt/binance-public.js +180 -0
  11. package/assets/plugin/ccxt/intel-public.d.ts +25 -0
  12. package/assets/plugin/ccxt/intel-public.js +80 -0
  13. package/assets/plugin/ccxt/public-market-data-api.d.ts +26 -0
  14. package/assets/plugin/ccxt/public-market-data-api.js +23 -0
  15. package/assets/plugin/config/agent-config-client.d.ts +77 -0
  16. package/assets/plugin/config/agent-config-client.js +188 -0
  17. package/assets/plugin/config/agent-config-poller.d.ts +32 -0
  18. package/assets/plugin/config/agent-config-poller.js +101 -0
  19. package/assets/plugin/config/brackets-config.d.ts +22 -0
  20. package/assets/plugin/config/brackets-config.js +58 -0
  21. package/assets/plugin/config/entitlement-gate.d.ts +51 -0
  22. package/assets/plugin/config/entitlement-gate.js +137 -0
  23. package/assets/plugin/config/gate-store.d.ts +18 -0
  24. package/assets/plugin/config/gate-store.js +61 -0
  25. package/assets/plugin/config/plugin-config-io.d.ts +222 -0
  26. package/assets/plugin/config/plugin-config-io.js +126 -0
  27. package/assets/plugin/config/position-review-config.d.ts +35 -0
  28. package/assets/plugin/config/position-review-config.js +105 -0
  29. package/assets/plugin/config/tool-gate.d.ts +53 -0
  30. package/assets/plugin/config/tool-gate.js +128 -0
  31. package/assets/plugin/config/user-data-stream-config.d.ts +89 -0
  32. package/assets/plugin/config/user-data-stream-config.js +239 -0
  33. package/assets/plugin/connector-supervisor.d.ts +36 -0
  34. package/assets/plugin/connector-supervisor.js +149 -0
  35. package/assets/plugin/exchange-adapter.d.ts +65 -0
  36. package/assets/plugin/exchange-adapter.js +4 -0
  37. package/assets/plugin/index.d.ts +30 -0
  38. package/assets/plugin/index.js +2763 -0
  39. package/assets/plugin/ingest/pending-entry-metadata.d.ts +74 -0
  40. package/assets/plugin/ingest/pending-entry-metadata.js +236 -0
  41. package/assets/plugin/ingest/position-auto-capture.d.ts +171 -0
  42. package/assets/plugin/ingest/position-auto-capture.js +709 -0
  43. package/assets/plugin/ingest/position-decisions-client.d.ts +327 -0
  44. package/assets/plugin/ingest/position-decisions-client.js +306 -0
  45. package/assets/plugin/ingest/readiness-reporter.d.ts +42 -0
  46. package/assets/plugin/ingest/readiness-reporter.js +163 -0
  47. package/assets/plugin/ingest/reconcile-db-vs-exchange.d.ts +51 -0
  48. package/assets/plugin/ingest/reconcile-db-vs-exchange.js +170 -0
  49. package/assets/plugin/ingest/reconciler-cleanup.d.ts +37 -0
  50. package/assets/plugin/ingest/reconciler-cleanup.js +147 -0
  51. package/assets/plugin/ingest/rest-gap-filler.d.ts +191 -0
  52. package/assets/plugin/ingest/rest-gap-filler.js +565 -0
  53. package/assets/plugin/ingest/touched-symbols-store.d.ts +25 -0
  54. package/assets/plugin/ingest/touched-symbols-store.js +96 -0
  55. package/assets/plugin/ingest/trade-store-client.d.ts +40 -0
  56. package/assets/plugin/ingest/trade-store-client.js +125 -0
  57. package/assets/plugin/ingest/ws-ingest.d.ts +43 -0
  58. package/assets/plugin/ingest/ws-ingest.js +126 -0
  59. package/assets/plugin/learning/setup-family.d.ts +21 -0
  60. package/assets/plugin/learning/setup-family.js +103 -0
  61. package/assets/plugin/lifecycle/install-signal-handlers.d.ts +33 -0
  62. package/assets/plugin/lifecycle/install-signal-handlers.js +112 -0
  63. package/assets/plugin/lifecycle/shutdown-coordinator.d.ts +43 -0
  64. package/assets/plugin/lifecycle/shutdown-coordinator.js +131 -0
  65. package/assets/plugin/lifecycle/trading-operation-lock.d.ts +17 -0
  66. package/assets/plugin/lifecycle/trading-operation-lock.js +14 -0
  67. package/assets/plugin/live/bracket-id.d.ts +26 -0
  68. package/assets/plugin/live/bracket-id.js +112 -0
  69. package/assets/plugin/live/bracket-ledger.d.ts +54 -0
  70. package/assets/plugin/live/bracket-ledger.js +267 -0
  71. package/assets/plugin/live/bracket-manager.d.ts +82 -0
  72. package/assets/plugin/live/bracket-manager.js +478 -0
  73. package/assets/plugin/live/bracket-params.d.ts +22 -0
  74. package/assets/plugin/live/bracket-params.js +124 -0
  75. package/assets/plugin/live/bracket-reconciler.d.ts +95 -0
  76. package/assets/plugin/live/bracket-reconciler.js +573 -0
  77. package/assets/plugin/live/bracket-types.d.ts +102 -0
  78. package/assets/plugin/live/bracket-types.js +8 -0
  79. package/assets/plugin/live/deposit-tracker.d.ts +62 -0
  80. package/assets/plugin/live/deposit-tracker.js +97 -0
  81. package/assets/plugin/live/emergency-controls.d.ts +32 -0
  82. package/assets/plugin/live/emergency-controls.js +226 -0
  83. package/assets/plugin/live/exchange-errors.d.ts +12 -0
  84. package/assets/plugin/live/exchange-errors.js +130 -0
  85. package/assets/plugin/live/exchange-info-cache.d.ts +37 -0
  86. package/assets/plugin/live/exchange-info-cache.js +134 -0
  87. package/assets/plugin/live/fact-subscriber.d.ts +78 -0
  88. package/assets/plugin/live/fact-subscriber.js +182 -0
  89. package/assets/plugin/live/fill-price.d.ts +13 -0
  90. package/assets/plugin/live/fill-price.js +37 -0
  91. package/assets/plugin/live/intent-journal.d.ts +42 -0
  92. package/assets/plugin/live/intent-journal.js +122 -0
  93. package/assets/plugin/live/listen-key-manager.d.ts +70 -0
  94. package/assets/plugin/live/listen-key-manager.js +169 -0
  95. package/assets/plugin/live/live-adapter.d.ts +319 -0
  96. package/assets/plugin/live/live-adapter.js +1906 -0
  97. package/assets/plugin/live/live-balance-enricher.d.ts +32 -0
  98. package/assets/plugin/live/live-balance-enricher.js +104 -0
  99. package/assets/plugin/live/live-bracket-api.d.ts +13 -0
  100. package/assets/plugin/live/live-bracket-api.js +20 -0
  101. package/assets/plugin/live/live-state-store.d.ts +194 -0
  102. package/assets/plugin/live/live-state-store.js +450 -0
  103. package/assets/plugin/live/local-signal-service.d.ts +57 -0
  104. package/assets/plugin/live/local-signal-service.js +151 -0
  105. package/assets/plugin/live/local-strategy-evaluator.d.ts +62 -0
  106. package/assets/plugin/live/local-strategy-evaluator.js +131 -0
  107. package/assets/plugin/live/microstructure-assembler.d.ts +54 -0
  108. package/assets/plugin/live/microstructure-assembler.js +148 -0
  109. package/assets/plugin/live/order-poller.d.ts +29 -0
  110. package/assets/plugin/live/order-poller.js +125 -0
  111. package/assets/plugin/live/position-state-store.d.ts +87 -0
  112. package/assets/plugin/live/position-state-store.js +237 -0
  113. package/assets/plugin/live/proposal-decision-listener.d.ts +70 -0
  114. package/assets/plugin/live/proposal-decision-listener.js +292 -0
  115. package/assets/plugin/live/proposal-manager.d.ts +76 -0
  116. package/assets/plugin/live/proposal-manager.js +140 -0
  117. package/assets/plugin/live/rate-limiter.d.ts +47 -0
  118. package/assets/plugin/live/rate-limiter.js +159 -0
  119. package/assets/plugin/live/reconciler.d.ts +39 -0
  120. package/assets/plugin/live/reconciler.js +175 -0
  121. package/assets/plugin/live/setup-buckets.d.ts +7 -0
  122. package/assets/plugin/live/setup-buckets.js +33 -0
  123. package/assets/plugin/live/slippage-tracker.d.ts +45 -0
  124. package/assets/plugin/live/slippage-tracker.js +78 -0
  125. package/assets/plugin/live/stop-watcher.d.ts +67 -0
  126. package/assets/plugin/live/stop-watcher.js +218 -0
  127. package/assets/plugin/live/user-data-active-probe.d.ts +54 -0
  128. package/assets/plugin/live/user-data-active-probe.js +180 -0
  129. package/assets/plugin/live/user-data-stream-controller.d.ts +200 -0
  130. package/assets/plugin/live/user-data-stream-controller.js +579 -0
  131. package/assets/plugin/live/user-data-stream-ws.d.ts +22 -0
  132. package/assets/plugin/live/user-data-stream-ws.js +63 -0
  133. package/assets/plugin/live/user-data-stream.d.ts +243 -0
  134. package/assets/plugin/live/user-data-stream.js +704 -0
  135. package/assets/plugin/logger.d.ts +2 -0
  136. package/assets/plugin/logger.js +2 -0
  137. package/assets/plugin/mfe.d.ts +21 -0
  138. package/assets/plugin/mfe.js +68 -0
  139. package/assets/plugin/onboarding/mode-ladder.d.ts +1 -0
  140. package/assets/plugin/onboarding/mode-ladder.js +3 -0
  141. package/assets/plugin/onboarding/runtime.d.ts +102 -0
  142. package/assets/plugin/onboarding/runtime.js +215 -0
  143. package/assets/plugin/openclaw.plugin.json +92 -0
  144. package/assets/plugin/paper-adapter.d.ts +24 -0
  145. package/assets/plugin/paper-adapter.js +91 -0
  146. package/assets/plugin/persistence/state-manager.d.ts +66 -0
  147. package/assets/plugin/persistence/state-manager.js +222 -0
  148. package/assets/plugin/pinned-plan.d.ts +9 -0
  149. package/assets/plugin/pinned-plan.js +23 -0
  150. package/assets/plugin/portfolio/reentry-tracker.d.ts +36 -0
  151. package/assets/plugin/portfolio/reentry-tracker.js +127 -0
  152. package/assets/plugin/portfolio/wave9-admission.d.ts +67 -0
  153. package/assets/plugin/portfolio/wave9-admission.js +262 -0
  154. package/assets/plugin/portfolio/wave9-policy.d.ts +36 -0
  155. package/assets/plugin/portfolio/wave9-policy.js +183 -0
  156. package/assets/plugin/risk/pre-trade-check.d.ts +38 -0
  157. package/assets/plugin/risk/pre-trade-check.js +345 -0
  158. package/assets/plugin/risk/pre-trade-types.d.ts +60 -0
  159. package/assets/plugin/risk/pre-trade-types.js +3 -0
  160. package/assets/plugin/shadow/shadow-tracker.d.ts +36 -0
  161. package/assets/plugin/shadow/shadow-tracker.js +151 -0
  162. package/assets/plugin/shadow/types.d.ts +42 -0
  163. package/assets/plugin/shadow/types.js +20 -0
  164. package/assets/plugin/shared/indicators-extended.d.ts +52 -0
  165. package/assets/plugin/shared/indicators-extended.js +291 -0
  166. package/assets/plugin/shared/indicators.d.ts +15 -0
  167. package/assets/plugin/shared/indicators.js +114 -0
  168. package/assets/plugin/signals/conditions/registry.d.ts +16 -0
  169. package/assets/plugin/signals/conditions/registry.js +1333 -0
  170. package/assets/plugin/signals/conditions/types.d.ts +1 -0
  171. package/assets/plugin/signals/conditions/types.js +4 -0
  172. package/assets/plugin/signals/direction-rules.d.ts +3 -0
  173. package/assets/plugin/signals/direction-rules.js +24 -0
  174. package/assets/plugin/signals/entry-rules.d.ts +6 -0
  175. package/assets/plugin/signals/entry-rules.js +33 -0
  176. package/assets/plugin/signals/serialize-context.d.ts +4 -0
  177. package/assets/plugin/signals/serialize-context.js +39 -0
  178. package/assets/plugin/signals/stop-rules.d.ts +3 -0
  179. package/assets/plugin/signals/stop-rules.js +48 -0
  180. package/assets/plugin/signals/strategy-adapter.d.ts +47 -0
  181. package/assets/plugin/signals/strategy-adapter.js +209 -0
  182. package/assets/plugin/signals/types.d.ts +1 -0
  183. package/assets/plugin/signals/types.js +8 -0
  184. package/assets/plugin/simulator/exchange-simulator.d.ts +105 -0
  185. package/assets/plugin/simulator/exchange-simulator.js +759 -0
  186. package/assets/plugin/simulator/fill-engine.d.ts +53 -0
  187. package/assets/plugin/simulator/fill-engine.js +280 -0
  188. package/assets/plugin/simulator/paper-market-feed.d.ts +26 -0
  189. package/assets/plugin/simulator/paper-market-feed.js +104 -0
  190. package/assets/plugin/simulator/realistic-fills.d.ts +59 -0
  191. package/assets/plugin/simulator/realistic-fills.js +175 -0
  192. package/assets/plugin/simulator/types.d.ts +228 -0
  193. package/assets/plugin/simulator/types.js +43 -0
  194. package/assets/plugin/strategy/builtin-strategies.d.ts +2 -0
  195. package/assets/plugin/strategy/builtin-strategies.js +113 -0
  196. package/assets/plugin/strategy/condition-registry.d.ts +3 -0
  197. package/assets/plugin/strategy/condition-registry.js +153 -0
  198. package/assets/plugin/strategy/evaluator.d.ts +70 -0
  199. package/assets/plugin/strategy/evaluator.js +98 -0
  200. package/assets/plugin/tools/assessment-validation.d.ts +141 -0
  201. package/assets/plugin/tools/assessment-validation.js +473 -0
  202. package/assets/plugin/tools/attach-brackets.d.ts +39 -0
  203. package/assets/plugin/tools/attach-brackets.js +564 -0
  204. package/assets/plugin/tools/audit-bracket-protection.d.ts +49 -0
  205. package/assets/plugin/tools/audit-bracket-protection.js +683 -0
  206. package/assets/plugin/tools/bracket-control.d.ts +12 -0
  207. package/assets/plugin/tools/bracket-control.js +35 -0
  208. package/assets/plugin/tools/cancel-all-orders.d.ts +9 -0
  209. package/assets/plugin/tools/cancel-all-orders.js +8 -0
  210. package/assets/plugin/tools/cancel-order.d.ts +14 -0
  211. package/assets/plugin/tools/cancel-order.js +60 -0
  212. package/assets/plugin/tools/check-position-health.d.ts +46 -0
  213. package/assets/plugin/tools/check-position-health.js +194 -0
  214. package/assets/plugin/tools/clear-exchange-credentials.d.ts +24 -0
  215. package/assets/plugin/tools/clear-exchange-credentials.js +70 -0
  216. package/assets/plugin/tools/close-position.d.ts +45 -0
  217. package/assets/plugin/tools/close-position.js +722 -0
  218. package/assets/plugin/tools/create-order.d.ts +89 -0
  219. package/assets/plugin/tools/create-order.js +1555 -0
  220. package/assets/plugin/tools/exit-gate.d.ts +58 -0
  221. package/assets/plugin/tools/exit-gate.js +162 -0
  222. package/assets/plugin/tools/fetch-balance.d.ts +5 -0
  223. package/assets/plugin/tools/fetch-balance.js +4 -0
  224. package/assets/plugin/tools/fetch-ohlcv.d.ts +11 -0
  225. package/assets/plugin/tools/fetch-ohlcv.js +8 -0
  226. package/assets/plugin/tools/fetch-open-orders.d.ts +7 -0
  227. package/assets/plugin/tools/fetch-open-orders.js +4 -0
  228. package/assets/plugin/tools/fetch-positions.d.ts +7 -0
  229. package/assets/plugin/tools/fetch-positions.js +4 -0
  230. package/assets/plugin/tools/fetch-ticker.d.ts +11 -0
  231. package/assets/plugin/tools/fetch-ticker.js +5 -0
  232. package/assets/plugin/tools/get-agent-profile.d.ts +4 -0
  233. package/assets/plugin/tools/get-agent-profile.js +6 -0
  234. package/assets/plugin/tools/get-analytics.d.ts +6 -0
  235. package/assets/plugin/tools/get-analytics.js +7 -0
  236. package/assets/plugin/tools/get-backtest.d.ts +12 -0
  237. package/assets/plugin/tools/get-backtest.js +91 -0
  238. package/assets/plugin/tools/get-basis.d.ts +7 -0
  239. package/assets/plugin/tools/get-basis.js +7 -0
  240. package/assets/plugin/tools/get-bracket-config.d.ts +11 -0
  241. package/assets/plugin/tools/get-bracket-config.js +24 -0
  242. package/assets/plugin/tools/get-cascade-risk.d.ts +7 -0
  243. package/assets/plugin/tools/get-cascade-risk.js +8 -0
  244. package/assets/plugin/tools/get-crypto-metrics.d.ts +18 -0
  245. package/assets/plugin/tools/get-crypto-metrics.js +62 -0
  246. package/assets/plugin/tools/get-cvd.d.ts +6 -0
  247. package/assets/plugin/tools/get-cvd.js +6 -0
  248. package/assets/plugin/tools/get-divergences.d.ts +6 -0
  249. package/assets/plugin/tools/get-divergences.js +6 -0
  250. package/assets/plugin/tools/get-funding-context.d.ts +6 -0
  251. package/assets/plugin/tools/get-funding-context.js +16 -0
  252. package/assets/plugin/tools/get-liquidation-levels.d.ts +7 -0
  253. package/assets/plugin/tools/get-liquidation-levels.js +7 -0
  254. package/assets/plugin/tools/get-liquidation-pulse.d.ts +9 -0
  255. package/assets/plugin/tools/get-liquidation-pulse.js +22 -0
  256. package/assets/plugin/tools/get-market-breadth.d.ts +6 -0
  257. package/assets/plugin/tools/get-market-breadth.js +8 -0
  258. package/assets/plugin/tools/get-market-intel.d.ts +19 -0
  259. package/assets/plugin/tools/get-market-intel.js +116 -0
  260. package/assets/plugin/tools/get-market-structure.d.ts +47 -0
  261. package/assets/plugin/tools/get-market-structure.js +198 -0
  262. package/assets/plugin/tools/get-my-mined-patterns.d.ts +20 -0
  263. package/assets/plugin/tools/get-my-mined-patterns.js +61 -0
  264. package/assets/plugin/tools/get-my-proposed-learnings.d.ts +20 -0
  265. package/assets/plugin/tools/get-my-proposed-learnings.js +55 -0
  266. package/assets/plugin/tools/get-my-recent-reviews.d.ts +22 -0
  267. package/assets/plugin/tools/get-my-recent-reviews.js +66 -0
  268. package/assets/plugin/tools/get-orderbook.d.ts +21 -0
  269. package/assets/plugin/tools/get-orderbook.js +32 -0
  270. package/assets/plugin/tools/get-pattern-scan.d.ts +7 -0
  271. package/assets/plugin/tools/get-pattern-scan.js +8 -0
  272. package/assets/plugin/tools/get-regime.d.ts +6 -0
  273. package/assets/plugin/tools/get-regime.js +7 -0
  274. package/assets/plugin/tools/get-relevant-learnings.d.ts +21 -0
  275. package/assets/plugin/tools/get-relevant-learnings.js +65 -0
  276. package/assets/plugin/tools/get-resting-liquidity.d.ts +6 -0
  277. package/assets/plugin/tools/get-resting-liquidity.js +11 -0
  278. package/assets/plugin/tools/get-risk-scenario.d.ts +29 -0
  279. package/assets/plugin/tools/get-risk-scenario.js +47 -0
  280. package/assets/plugin/tools/get-risk-summary.d.ts +51 -0
  281. package/assets/plugin/tools/get-risk-summary.js +118 -0
  282. package/assets/plugin/tools/get-sentiment.d.ts +4 -0
  283. package/assets/plugin/tools/get-sentiment.js +6 -0
  284. package/assets/plugin/tools/get-session-review.d.ts +7 -0
  285. package/assets/plugin/tools/get-session-review.js +8 -0
  286. package/assets/plugin/tools/get-setup-detail.d.ts +7 -0
  287. package/assets/plugin/tools/get-setup-detail.js +322 -0
  288. package/assets/plugin/tools/get-signals.d.ts +15 -0
  289. package/assets/plugin/tools/get-signals.js +54 -0
  290. package/assets/plugin/tools/get-sizing.d.ts +6 -0
  291. package/assets/plugin/tools/get-sizing.js +6 -0
  292. package/assets/plugin/tools/get-trade-feedback.d.ts +7 -0
  293. package/assets/plugin/tools/get-trade-feedback.js +8 -0
  294. package/assets/plugin/tools/get-trade-flow.d.ts +7 -0
  295. package/assets/plugin/tools/get-trade-flow.js +7 -0
  296. package/assets/plugin/tools/get-volume-analysis.d.ts +21 -0
  297. package/assets/plugin/tools/get-volume-analysis.js +74 -0
  298. package/assets/plugin/tools/get-volume-profile.d.ts +7 -0
  299. package/assets/plugin/tools/get-volume-profile.js +7 -0
  300. package/assets/plugin/tools/get-wave9-status.d.ts +127 -0
  301. package/assets/plugin/tools/get-wave9-status.js +796 -0
  302. package/assets/plugin/tools/helpers.d.ts +26 -0
  303. package/assets/plugin/tools/helpers.js +39 -0
  304. package/assets/plugin/tools/intel-api.d.ts +34 -0
  305. package/assets/plugin/tools/intel-api.js +119 -0
  306. package/assets/plugin/tools/intel-cache.d.ts +25 -0
  307. package/assets/plugin/tools/intel-cache.js +148 -0
  308. package/assets/plugin/tools/list-strategies.d.ts +17 -0
  309. package/assets/plugin/tools/list-strategies.js +23 -0
  310. package/assets/plugin/tools/modify-stop.d.ts +21 -0
  311. package/assets/plugin/tools/modify-stop.js +120 -0
  312. package/assets/plugin/tools/modify-target.d.ts +21 -0
  313. package/assets/plugin/tools/modify-target.js +110 -0
  314. package/assets/plugin/tools/propose-learning.d.ts +22 -0
  315. package/assets/plugin/tools/propose-learning.js +65 -0
  316. package/assets/plugin/tools/query-review-outcomes.d.ts +30 -0
  317. package/assets/plugin/tools/query-review-outcomes.js +64 -0
  318. package/assets/plugin/tools/query-trades.d.ts +21 -0
  319. package/assets/plugin/tools/query-trades.js +37 -0
  320. package/assets/plugin/tools/record-position-reviews.d.ts +38 -0
  321. package/assets/plugin/tools/record-position-reviews.js +147 -0
  322. package/assets/plugin/tools/save-strategy.d.ts +16 -0
  323. package/assets/plugin/tools/save-strategy.js +46 -0
  324. package/assets/plugin/tools/scan-pairs.d.ts +22 -0
  325. package/assets/plugin/tools/scan-pairs.js +234 -0
  326. package/assets/plugin/tools/score-setup.d.ts +31 -0
  327. package/assets/plugin/tools/score-setup.js +268 -0
  328. package/assets/plugin/tools/set-bracket-requirement.d.ts +18 -0
  329. package/assets/plugin/tools/set-bracket-requirement.js +81 -0
  330. package/assets/plugin/tools/set-exchange-credentials.d.ts +25 -0
  331. package/assets/plugin/tools/set-exchange-credentials.js +80 -0
  332. package/assets/plugin/tools/set-trading-mode.d.ts +26 -0
  333. package/assets/plugin/tools/set-trading-mode.js +152 -0
  334. package/assets/plugin/tools/test-exchange-credentials.d.ts +16 -0
  335. package/assets/plugin/tools/test-exchange-credentials.js +100 -0
  336. package/assets/plugin/tools/toggle-strategy.d.ts +8 -0
  337. package/assets/plugin/tools/toggle-strategy.js +15 -0
  338. package/assets/plugin/trading-params-cache.d.ts +26 -0
  339. package/assets/plugin/trading-params-cache.js +52 -0
  340. package/assets/plugin/types.d.ts +134 -0
  341. package/assets/plugin/types.js +7 -0
  342. package/assets/plugin/util/plugin-paths.d.ts +3 -0
  343. package/assets/plugin/util/plugin-paths.js +15 -0
  344. package/assets/plugin/venues/hyperliquid/hl-balance.d.ts +116 -0
  345. package/assets/plugin/venues/hyperliquid/hl-balance.js +145 -0
  346. package/assets/plugin/venues/hyperliquid/hl-bracket-coordinator.d.ts +123 -0
  347. package/assets/plugin/venues/hyperliquid/hl-bracket-coordinator.js +533 -0
  348. package/assets/plugin/venues/hyperliquid/hl-brackets.d.ts +102 -0
  349. package/assets/plugin/venues/hyperliquid/hl-brackets.js +172 -0
  350. package/assets/plugin/venues/hyperliquid/hl-cloid.d.ts +22 -0
  351. package/assets/plugin/venues/hyperliquid/hl-cloid.js +82 -0
  352. package/assets/plugin/venues/hyperliquid/hl-info-cache.d.ts +46 -0
  353. package/assets/plugin/venues/hyperliquid/hl-info-cache.js +125 -0
  354. package/assets/plugin/venues/hyperliquid/hl-live-adapter.d.ts +146 -0
  355. package/assets/plugin/venues/hyperliquid/hl-live-adapter.js +728 -0
  356. package/assets/plugin/venues/hyperliquid/hl-precision.d.ts +61 -0
  357. package/assets/plugin/venues/hyperliquid/hl-precision.js +176 -0
  358. package/assets/plugin/venues/hyperliquid/hl-private.d.ts +88 -0
  359. package/assets/plugin/venues/hyperliquid/hl-private.js +357 -0
  360. package/assets/plugin/venues/hyperliquid/hl-public.d.ts +79 -0
  361. package/assets/plugin/venues/hyperliquid/hl-public.js +436 -0
  362. package/assets/plugin/venues/hyperliquid/hl-rate-gate.d.ts +57 -0
  363. package/assets/plugin/venues/hyperliquid/hl-rate-gate.js +220 -0
  364. package/assets/plugin/venues/hyperliquid/hl-user-stream.d.ts +90 -0
  365. package/assets/plugin/venues/hyperliquid/hl-user-stream.js +220 -0
  366. package/assets/plugin/venues/registry.d.ts +38 -0
  367. package/assets/plugin/venues/registry.js +46 -0
  368. package/assets/plugin/venues/symbols.d.ts +43 -0
  369. package/assets/plugin/venues/symbols.js +107 -0
  370. package/assets/plugin/wave9/live-account-capture.d.ts +67 -0
  371. package/assets/plugin/wave9/live-account-capture.js +435 -0
  372. package/assets/plugin/wave9/live-autonomous-protection.d.ts +39 -0
  373. package/assets/plugin/wave9/live-autonomous-protection.js +112 -0
  374. package/assets/plugin/wave9/live-durable-reconciliation-scheduler.d.ts +33 -0
  375. package/assets/plugin/wave9/live-durable-reconciliation-scheduler.js +115 -0
  376. package/assets/plugin/wave9/live-execution-ledger.d.ts +107 -0
  377. package/assets/plugin/wave9/live-execution-ledger.js +498 -0
  378. package/assets/plugin/wave9/live-position-confirmation.d.ts +18 -0
  379. package/assets/plugin/wave9/live-position-confirmation.js +111 -0
  380. package/assets/plugin/wave9/live-residual-protection.d.ts +18 -0
  381. package/assets/plugin/wave9/live-residual-protection.js +250 -0
  382. package/assets/plugin/wave9/live-startup-reconciliation.d.ts +38 -0
  383. package/assets/plugin/wave9/live-startup-reconciliation.js +454 -0
  384. package/assets/plugin/wave9/live-symbol-ownership.d.ts +20 -0
  385. package/assets/plugin/wave9/live-symbol-ownership.js +132 -0
  386. package/assets/plugin/wave9/paper-admission-guard.d.ts +199 -0
  387. package/assets/plugin/wave9/paper-admission-guard.js +650 -0
  388. package/assets/plugin/wave9/usdm-evidence-provider.d.ts +42 -0
  389. package/assets/plugin/wave9/usdm-evidence-provider.js +133 -0
  390. package/package.json +1 -1
@@ -0,0 +1,58 @@
1
+ export type ExitGateMode = 'off' | 'shadow' | 'observe' | 'enforce';
2
+ export type ThesisStatusForGate = 'intact' | 'weakening' | 'invalidated' | 'evolving';
3
+ export type ReviewVerdictForGate = 'hold' | 'add_on' | 'close_recommended';
4
+ export interface ExitGateInputs {
5
+ /** The close_position reason the agent supplied. `operator_command` always
6
+ * passes; the other five reasons go through tier evaluation. */
7
+ reason: 'regime_flip' | 'scorecard_reversal' | 'risk_limit' | 'bracket_integrity' | 'operator_command';
8
+ /** Max favorable excursion in R-multiples ever reached on this position.
9
+ * Undefined => gate skips (PASS with code 'inputs_unavailable_mfe'). */
10
+ mfe_r_peak?: number;
11
+ /** Current R-multiple at the close price. Undefined => gate skips. */
12
+ current_r?: number;
13
+ /** Telemetry only (0a/0b) — provenance of the mfe_r_peak / current_r values
14
+ * above. Ignored by evaluateExitGate; set by buildExitGateInputs and
15
+ * persisted in gate_eval.inputs so the inputs_unavailable_* and
16
+ * computed-fallback paths are diagnosable from the journal. */
17
+ mfe_src?: 'assessment' | 'pos.mfeR' | 'computed_floor';
18
+ current_r_src?: 'assessment' | 'computed';
19
+ /** Implied or explicit vol-shock flag from the caller. The caller computes
20
+ * this from recent ATR vs latest adverse 5m bar. Default false. */
21
+ volShock?: boolean;
22
+ /** Position side — needed for the T2a stop-trail check (long stop ≥ entry,
23
+ * short stop ≤ entry). */
24
+ side?: 'long' | 'short';
25
+ /** Current bracket stop price. Undefined => T2a check is skipped (PASS with
26
+ * code 't2a_skipped_no_stop_known' rather than block). */
27
+ stopPrice?: number;
28
+ /** Entry price for the position. Used as the BE level in T2a. */
29
+ entryPrice?: number;
30
+ /** Most recent record_position_reviews entry for this position. Drives the
31
+ * contradicts-own-review block and the review-override pass. */
32
+ lastReview?: {
33
+ verdict: ReviewVerdictForGate;
34
+ thesis_status: ThesisStatusForGate;
35
+ review_at_ms: number;
36
+ };
37
+ /** Current time in ms — explicit for testability. */
38
+ now_ms: number;
39
+ }
40
+ export type GateOutcome = 'PASS' | 'BLOCK';
41
+ export interface GateVerdict {
42
+ outcome: GateOutcome;
43
+ /** Tier classification: T1 / T2a / T2b / override / skipped. */
44
+ tier: 'T1' | 'T2a' | 'T2b' | 'override' | 'skipped';
45
+ /** Stable code identifying the specific predicate that fired.
46
+ * e.g. 't1_premature_exit', 't2a_stop_not_trailed_to_BE',
47
+ * 'operator_command', 'vol_shock', 'contradicts_own_recent_hold_verdict'. */
48
+ code: string;
49
+ /** Optional recovery hint for BLOCK outcomes — surfaced back to the agent
50
+ * via the tool error so it can self-correct mid-turn. */
51
+ recovery_hint?: string;
52
+ /** Optional discipline-failure flag, currently only set on T2b passes so
53
+ * we capture "winner peaked, reversed, no stop-trail done". */
54
+ discipline_failure?: string;
55
+ }
56
+ /** Evaluate the exit gate against the supplied inputs. Pure; safe to call
57
+ * from anywhere. See module header for semantics. */
58
+ export declare function evaluateExitGate(inputs: ExitGateInputs): GateVerdict;
@@ -0,0 +1,162 @@
1
+ // Exit gate — prevents the agent from closing positions before they've
2
+ // meaningfully developed, while preserving override paths for genuine adverse
3
+ // signals. See docs/EXIT_GATE_DESIGN.md for the full spec and §3 for the
4
+ // tier table this function implements.
5
+ //
6
+ // Pure function — caller supplies all inputs, including the mode flag, and the
7
+ // function returns a structured verdict. Caller (close-position.ts) is
8
+ // responsible for actually blocking, soft-warning, or logging based on mode.
9
+ //
10
+ // Design contract:
11
+ // - In `off` mode the gate is never called at all (don't pay the input
12
+ // computation cost).
13
+ // - In `shadow` / `observe` / `enforce` the gate runs; the caller decides
14
+ // what to do with BLOCK verdicts.
15
+ // - If inputs are partial (e.g., MFE not supplied), the gate returns
16
+ // PASS('inputs_unavailable') — never BLOCK on missing data. The shadow
17
+ // soak surfaces these so we can fix plumbing before enforce.
18
+ // - The "contradicts-own-review" rule applies pre-tier (blocks T2b too).
19
+ // See §8 R4 in the design doc — this is the conservative default; we
20
+ // watch shadow telemetry and demote to T1-only if it blocks legit exits.
21
+ /** Window during which a hold-verdict review blocks a contradicting close. */
22
+ const CONTRADICTS_OWN_REVIEW_WINDOW_MS = 5 * 60 * 1000;
23
+ /** Developed-position threshold in R-multiples. */
24
+ const DEVELOPED_MFE_R = 0.5;
25
+ /** T1 escape threshold — position deteriorating fast. */
26
+ const T1_ESCAPE_CURRENT_R = -0.5;
27
+ /** 0c — floor for the 'weakening' review override. The t1_review_override pass
28
+ * was the dominant exit (~42% of agent closes) and, by construction, every one
29
+ * is a T1-premature position — the exact population the gate exists to BLOCK.
30
+ * It was fully agent-self-served: file verdict='close_recommended' +
31
+ * thesis_status='weakening' and the block lifted with zero objective
32
+ * corroboration. We now split by strength of claim: 'invalidated' (a strong,
33
+ * falsifiable thesis break — regime flip / level broken) keeps the FULL
34
+ * override even at breakeven; 'weakening' (a soft, abuse-prone signal) only
35
+ * overrides once price has ALSO moved adversely to at least this floor.
36
+ * ⚠ This threshold is a value to SOAK in shadow (compare would_have_blocked vs
37
+ * which positions later hit TP), NOT a derived optimum — tightening reclassifies
38
+ * a large population. See docs/EXIT_DISCIPLINE_BUILD_PLAN.md Step 0c. */
39
+ const T1_WEAKENING_OVERRIDE_FLOOR_R = -0.25;
40
+ /** Evaluate the exit gate against the supplied inputs. Pure; safe to call
41
+ * from anywhere. See module header for semantics. */
42
+ export function evaluateExitGate(inputs) {
43
+ // 0. Always-allow overrides — checked first, before any input-availability
44
+ // checks, so the operator can ALWAYS get out.
45
+ if (inputs.reason === 'operator_command') {
46
+ return { outcome: 'PASS', tier: 'override', code: 'operator_command' };
47
+ }
48
+ if (inputs.volShock === true) {
49
+ return { outcome: 'PASS', tier: 'override', code: 'vol_shock' };
50
+ }
51
+ // 1. Contradicts-own-review block — pre-tier.
52
+ // The "intact + hold → close" pattern from the May 12 analysis. If the
53
+ // agent's last review said hold AND was recent, refuse to immediately
54
+ // contradict it. Operator command (above) is the only override.
55
+ const lr = inputs.lastReview;
56
+ if (lr && lr.verdict === 'hold') {
57
+ const age = inputs.now_ms - lr.review_at_ms;
58
+ if (age < CONTRADICTS_OWN_REVIEW_WINDOW_MS && age >= 0) {
59
+ return {
60
+ outcome: 'BLOCK',
61
+ tier: 'override',
62
+ code: 'contradicts_own_recent_hold_verdict',
63
+ recovery_hint: `Last record_position_reviews filed verdict='hold' ${Math.round(age / 1000)}s ago. ` +
64
+ `If conditions have genuinely changed, file a fresh review with verdict='close_recommended' first. ` +
65
+ `Operator can override via reason='operator_command'.`,
66
+ };
67
+ }
68
+ }
69
+ // 2. Input availability — we need mfe_r_peak + current_r to do tier work.
70
+ // Missing => PASS with a skip code so shadow telemetry can surface the
71
+ // plumbing gap.
72
+ if (typeof inputs.mfe_r_peak !== 'number' || !Number.isFinite(inputs.mfe_r_peak)) {
73
+ return { outcome: 'PASS', tier: 'skipped', code: 'inputs_unavailable_mfe' };
74
+ }
75
+ if (typeof inputs.current_r !== 'number' || !Number.isFinite(inputs.current_r)) {
76
+ return { outcome: 'PASS', tier: 'skipped', code: 'inputs_unavailable_current_r' };
77
+ }
78
+ // 3. Review override — well-formed close_recommended on a genuine adverse
79
+ // signal. 0c split (see T1_WEAKENING_OVERRIDE_FLOOR_R): 'invalidated' (a
80
+ // strong, falsifiable break) overrides outright; 'weakening' (soft, the
81
+ // scratch-laundering vector) overrides ONLY with price confirmation
82
+ // (current_r ≤ the floor). inputs.current_r is guaranteed finite here
83
+ // (checked in step 2 above).
84
+ const reviewOverride = !!lr &&
85
+ lr.verdict === 'close_recommended' &&
86
+ (lr.thesis_status === 'invalidated' ||
87
+ (lr.thesis_status === 'weakening' && inputs.current_r <= T1_WEAKENING_OVERRIDE_FLOOR_R));
88
+ // 4. Tier classification.
89
+ const developed = inputs.mfe_r_peak >= DEVELOPED_MFE_R;
90
+ if (!developed) {
91
+ // ── Tier 1: never developed (mfe_r_peak < 0.5) ──
92
+ if (inputs.current_r <= T1_ESCAPE_CURRENT_R) {
93
+ return {
94
+ outcome: 'PASS',
95
+ tier: 'T1',
96
+ code: 't1_escape_deteriorating',
97
+ };
98
+ }
99
+ if (reviewOverride) {
100
+ return {
101
+ outcome: 'PASS',
102
+ tier: 'T1',
103
+ code: 't1_review_override',
104
+ };
105
+ }
106
+ return {
107
+ outcome: 'BLOCK',
108
+ tier: 'T1',
109
+ code: 't1_premature_exit',
110
+ recovery_hint: `Position has not developed (mfe_r_peak=${inputs.mfe_r_peak.toFixed(2)}R < 0.5R) and is not deteriorating ` +
111
+ `(current_r=${inputs.current_r.toFixed(2)}R > -0.5R). ` +
112
+ `Let the bracket be the exit. Override paths: ` +
113
+ `(a) file verdict='close_recommended' with thesis_status='invalidated' — a real, falsifiable ` +
114
+ `thesis break (regime flip, key level broken), not a soft read; ` +
115
+ `(b) thesis_status='weakening' overrides ONLY once current_r ≤ -0.25R (soft signals need price confirmation); ` +
116
+ `(c) wait for current_r ≤ -0.5R; (d) operator_command.`,
117
+ };
118
+ }
119
+ // ── Tier 2: developed (mfe_r_peak ≥ 0.5) ──
120
+ if (inputs.current_r >= 0) {
121
+ // T2a — in profit. Require stop has been trailed to BE-or-better.
122
+ // Need side + stopPrice + entryPrice to check; if any missing, pass with
123
+ // a skip code so shadow telemetry surfaces it.
124
+ if (!inputs.side ||
125
+ typeof inputs.stopPrice !== 'number' ||
126
+ !Number.isFinite(inputs.stopPrice) ||
127
+ typeof inputs.entryPrice !== 'number' ||
128
+ !Number.isFinite(inputs.entryPrice)) {
129
+ return {
130
+ outcome: 'PASS',
131
+ tier: 'T2a',
132
+ code: 't2a_skipped_no_stop_known',
133
+ };
134
+ }
135
+ const stopAtBE = inputs.side === 'long' ? inputs.stopPrice >= inputs.entryPrice : inputs.stopPrice <= inputs.entryPrice;
136
+ if (!stopAtBE) {
137
+ return {
138
+ outcome: 'BLOCK',
139
+ tier: 'T2a',
140
+ code: 't2a_stop_not_trailed_to_BE',
141
+ recovery_hint: `Position developed to mfe_r_peak=${inputs.mfe_r_peak.toFixed(2)}R and is currently in profit ` +
142
+ `(current_r=${inputs.current_r.toFixed(2)}R), but stop is still at original level ` +
143
+ `(stop=${inputs.stopPrice}, entry=${inputs.entryPrice}). ` +
144
+ `Call modify_stop to move stop to ${inputs.entryPrice} (break-even) or better before closing. ` +
145
+ `This locks in profit and is the v2.10.0 winner-protection rule.`,
146
+ };
147
+ }
148
+ return {
149
+ outcome: 'PASS',
150
+ tier: 'T2a',
151
+ code: 't2a_developed_in_profit_stop_trailed',
152
+ };
153
+ }
154
+ // T2b — developed, now in red. Horse has bolted; allow the exit but flag
155
+ // as discipline failure so we can study these later.
156
+ return {
157
+ outcome: 'PASS',
158
+ tier: 'T2b',
159
+ code: 't2b_developed_reversed',
160
+ discipline_failure: 'unmanaged_winner_reversed',
161
+ };
162
+ }
@@ -0,0 +1,5 @@
1
+ import type { IExchangeAdapter } from '../exchange-adapter.js';
2
+ import type { CcxtBalance } from '../types.js';
3
+ export declare function fetchBalanceTool(_args: Record<string, unknown>, deps: {
4
+ adapter: IExchangeAdapter;
5
+ }): Promise<CcxtBalance>;
@@ -0,0 +1,4 @@
1
+ // Tool: fetch_balance — wallet balance (paper or live)
2
+ export async function fetchBalanceTool(_args, deps) {
3
+ return deps.adapter.getBalance();
4
+ }
@@ -0,0 +1,11 @@
1
+ import type { PublicMarketDataApi } from '../ccxt/public-market-data-api.js';
2
+ import type { CcxtOHLCV } from '../types.js';
3
+ export declare function fetchOhlcvTool(args: {
4
+ symbol: string;
5
+ timeframe?: string;
6
+ limit?: number;
7
+ }, deps: {
8
+ binanceApi: PublicMarketDataApi;
9
+ }): Promise<CcxtOHLCV[] | {
10
+ error: string;
11
+ }>;
@@ -0,0 +1,8 @@
1
+ // Tool: fetch_ohlcv — real Binance OHLCV candles via CCXT
2
+ export async function fetchOhlcvTool(args, deps) {
3
+ const candles = await deps.binanceApi.fetchOHLCV(args.symbol, args.timeframe ?? '1h', args.limit ?? 100);
4
+ if (!candles) {
5
+ return { error: `Failed to fetch OHLCV for ${args.symbol}` };
6
+ }
7
+ return candles;
8
+ }
@@ -0,0 +1,7 @@
1
+ import type { IExchangeAdapter } from '../exchange-adapter.js';
2
+ import type { CcxtOrder } from '../types.js';
3
+ export declare function fetchOpenOrdersTool(args: {
4
+ symbol?: string;
5
+ }, deps: {
6
+ adapter: IExchangeAdapter;
7
+ }): Promise<CcxtOrder[]>;
@@ -0,0 +1,4 @@
1
+ // Tool: fetch_open_orders — pending orders (paper or live)
2
+ export async function fetchOpenOrdersTool(args, deps) {
3
+ return deps.adapter.getOpenOrders(args.symbol);
4
+ }
@@ -0,0 +1,7 @@
1
+ import type { IExchangeAdapter } from '../exchange-adapter.js';
2
+ import type { CcxtPosition } from '../types.js';
3
+ export declare function fetchPositionsTool(args: {
4
+ symbol?: string;
5
+ }, deps: {
6
+ adapter: IExchangeAdapter;
7
+ }): Promise<CcxtPosition[]>;
@@ -0,0 +1,4 @@
1
+ // Tool: fetch_positions — open positions (paper or live)
2
+ export async function fetchPositionsTool(args, deps) {
3
+ return deps.adapter.getPositions(args.symbol);
4
+ }
@@ -0,0 +1,11 @@
1
+ import type { PublicMarketDataApi } from '../ccxt/public-market-data-api.js';
2
+ import type { ExchangeSimulator } from '../simulator/exchange-simulator.js';
3
+ import type { CcxtTicker } from '../types.js';
4
+ export declare function fetchTickerTool(args: {
5
+ symbol: string;
6
+ }, deps: {
7
+ binanceApi: PublicMarketDataApi;
8
+ simulator: ExchangeSimulator;
9
+ }): Promise<CcxtTicker | {
10
+ error: string;
11
+ }>;
@@ -0,0 +1,5 @@
1
+ // Tool: fetch_ticker — real Binance market data via CCXT
2
+ import { fetchCurrentPrice } from './helpers.js';
3
+ export async function fetchTickerTool(args, deps) {
4
+ return fetchCurrentPrice(args.symbol, deps);
5
+ }
@@ -0,0 +1,4 @@
1
+ import type { IntelApiDeps } from './intel-api.js';
2
+ export declare function getAgentProfileTool(deps: IntelApiDeps): Promise<Record<string, unknown> | {
3
+ error: string;
4
+ }>;
@@ -0,0 +1,6 @@
1
+ // Tool: get_agent_profile — returns earned autonomy tier and permissions.
2
+ // The agent checks this at session start to know what it's allowed to adjust.
3
+ import { fetchIntelApi } from './intel-api.js';
4
+ export async function getAgentProfileTool(deps) {
5
+ return fetchIntelApi('/api/agent-profile', deps);
6
+ }
@@ -0,0 +1,6 @@
1
+ import type { IntelApiDeps } from './intel-api.js';
2
+ export declare function getAnalyticsTool(args: {
3
+ symbol: string;
4
+ }, deps: IntelApiDeps): Promise<Record<string, unknown> | {
5
+ error: string;
6
+ }>;
@@ -0,0 +1,7 @@
1
+ // Tool: get_analytics — fetches edge analytics from the Intelligence API.
2
+ // Returns per-strategy performance metrics (win rate, expectancy, Sharpe),
3
+ // regime breakdown, equity curve, and degradation alerts.
4
+ import { fetchIntelApi, enc, resolveIntelSymbol } from './intel-api.js';
5
+ export async function getAnalyticsTool(args, deps) {
6
+ return fetchIntelApi(`/api/analytics/${enc(resolveIntelSymbol(deps, args.symbol))}`, deps);
7
+ }
@@ -0,0 +1,12 @@
1
+ import type { IntelApiDeps } from './intel-api.js';
2
+ export interface BacktestArgs {
3
+ symbol: string;
4
+ strategy?: string;
5
+ months?: number;
6
+ sizing?: string;
7
+ regime_filter?: string;
8
+ timeframe?: string;
9
+ }
10
+ export declare function getBacktestTool(args: BacktestArgs, deps: IntelApiDeps): Promise<Record<string, unknown> | {
11
+ error: string;
12
+ }>;
@@ -0,0 +1,91 @@
1
+ // Tool: get_backtest — backtest a trading strategy against historical data.
2
+ // Calls Intelligence API to run walk-forward simulation and returns agent-friendly summary.
3
+ //
4
+ // Uses the async job pattern: POST /api/backtest/:symbol?async=true returns a
5
+ // job_id immediately; we then poll GET /api/backtest/job/:id every 5s until
6
+ // status='done' or timeout. This supports multi-year backtests (up to 15min
7
+ // wall-clock on the intel worker) without coupling client-side timeouts to
8
+ // server-side compute. See `docs/BACKTEST_CHUNKING_PLAN.md` for the engine-
9
+ // side chunking that makes the worker complete in bounded time.
10
+ import { fetchIntelApi, enc } from './intel-api.js';
11
+ /** How long the plugin will keep polling before giving up. Independent of
12
+ * the server-side worker timeout (currently 1800s = 30min); we add 60s
13
+ * slack so a job that finishes RIGHT AT the server cap still gets one
14
+ * last poll. Bump this in lockstep with `ASYNC_BACKTEST_TIMEOUT_MS` in
15
+ * `intelligence/src/health/server.ts` — otherwise the plugin bails
16
+ * before the worker is allowed to finish. */
17
+ const MAX_POLL_DURATION_MS = 1_860_000; // 31 min
18
+ const POLL_INTERVAL_MS = 5_000;
19
+ /** Consecutive transient poll-error tolerance before bailing. Single 502s
20
+ * during intel-api restarts are routine; >3 in a row indicates real
21
+ * network/service failure and we surface the error to the agent. */
22
+ const MAX_CONSECUTIVE_POLL_ERRORS = 5;
23
+ export async function getBacktestTool(args, deps) {
24
+ const intelSymbol = args.symbol.replace('/', '');
25
+ const months = args.months ?? 6;
26
+ // Round to hour boundary for cache key stability (repeated calls within same hour hit cache)
27
+ const nowHour = Math.floor(Date.now() / 3600000) * 3600000;
28
+ const endDate = new Date(nowHour).toISOString();
29
+ const startDate = new Date(nowHour - months * 30 * 86400000).toISOString();
30
+ const body = {
31
+ strategy: args.strategy ?? 'all',
32
+ startDate,
33
+ endDate,
34
+ timeframe: args.timeframe ?? '1h',
35
+ initialCapital: 10000,
36
+ sizingMethod: args.sizing === 'kelly' ? 'kelly' : 'fixed',
37
+ };
38
+ if (args.regime_filter) {
39
+ body.regimeFilter = args.regime_filter.split(',').map((s) => s.trim());
40
+ }
41
+ // Kick off the async job. The POST returns within seconds with either a
42
+ // cache-hit result (status='done' inline) or a queued job_id to poll.
43
+ const kickoffRaw = await fetchIntelApi(`/api/backtest/${enc(intelSymbol)}?async=true`, deps, { method: 'POST', body, timeoutMs: 30_000 });
44
+ if ('error' in kickoffRaw && typeof kickoffRaw.error === 'string') {
45
+ return { error: kickoffRaw.error };
46
+ }
47
+ const kickoff = kickoffRaw;
48
+ // Cache hit short-circuit: server already had the result, no polling needed.
49
+ if (kickoff.status === 'done' && kickoff.result) {
50
+ return kickoff.result;
51
+ }
52
+ if (kickoff.status === 'error') {
53
+ return { error: `Backtest failed: ${kickoff.error ?? 'unknown error'}` };
54
+ }
55
+ const jobId = kickoff.job_id;
56
+ if (!jobId) {
57
+ return { error: 'Intelligence API did not return a job_id for async backtest request.' };
58
+ }
59
+ // Poll loop. We tolerate up to MAX_CONSECUTIVE_POLL_ERRORS transient errors
60
+ // (intel-api restart, brief network hiccup) before giving up — those return
61
+ // strings from fetchIntelApi look like {error: "..."} but don't mean the
62
+ // backtest itself failed.
63
+ const pollStart = Date.now();
64
+ let consecutiveErrors = 0;
65
+ while (Date.now() - pollStart < MAX_POLL_DURATION_MS) {
66
+ await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
67
+ const statusRaw = await fetchIntelApi(`/api/backtest/job/${enc(jobId)}`, deps, { method: 'GET', timeoutMs: 15_000 });
68
+ if ('error' in statusRaw && typeof statusRaw.error === 'string') {
69
+ consecutiveErrors += 1;
70
+ if (consecutiveErrors >= MAX_CONSECUTIVE_POLL_ERRORS) {
71
+ return {
72
+ error: `Lost contact with intel API while polling backtest job ${jobId}: ${statusRaw.error}. Job may still complete server-side; retry the same call to pick up the cached result.`,
73
+ };
74
+ }
75
+ continue;
76
+ }
77
+ consecutiveErrors = 0;
78
+ const status = statusRaw;
79
+ if (status.status === 'done' && status.result) {
80
+ return status.result;
81
+ }
82
+ if (status.status === 'error') {
83
+ return { error: `Backtest job ${jobId} failed: ${status.error ?? 'unknown error'}` };
84
+ }
85
+ // 'queued' or 'running' — continue polling
86
+ }
87
+ const elapsedMin = Math.round((Date.now() - pollStart) / 60_000);
88
+ return {
89
+ error: `Backtest job ${jobId} still running after ${elapsedMin} min. The intel worker has a 15-min server-side cap; retry the same call (cached if it finished after we gave up) or shorten the window.`,
90
+ };
91
+ }
@@ -0,0 +1,7 @@
1
+ import type { IntelApiDeps } from './intel-api.js';
2
+ export declare function getBasisTool(args: {
3
+ symbol: string;
4
+ hours?: number;
5
+ }, deps: IntelApiDeps): Promise<Record<string, unknown> | {
6
+ error: string;
7
+ }>;
@@ -0,0 +1,7 @@
1
+ // Tool: get_basis — fetches spot-futures basis (mark-spot premium) analysis.
2
+ // Returns current premium/discount, historical basis, funding alignment, and dislocation detection.
3
+ import { fetchIntelApi, enc, resolveIntelSymbol } from './intel-api.js';
4
+ export async function getBasisTool(args, deps) {
5
+ const hours = args.hours ?? 24;
6
+ return fetchIntelApi(`/api/basis/${enc(resolveIntelSymbol(deps, args.symbol))}?hours=${hours}`, deps);
7
+ }
@@ -0,0 +1,11 @@
1
+ import type { BracketMode } from '../config/brackets-config.js';
2
+ export interface GetBracketConfigResult {
3
+ mode: BracketMode;
4
+ requireStopLoss: boolean;
5
+ requireTakeProfit: boolean;
6
+ }
7
+ export declare function getBracketConfigTool(_args: Record<string, never>, deps?: {
8
+ configPath?: string;
9
+ }): GetBracketConfigResult | {
10
+ error: string;
11
+ };
@@ -0,0 +1,24 @@
1
+ // get_bracket_config — read current brackets section from plugin-config.
2
+ //
3
+ // Operator-only in spirit (the agent shouldn't care about the value — the
4
+ // pre-trade gate already enforces it). Exposed so the dashboard's Trading
5
+ // Parameters panel can fetch current state before rendering the toggles.
6
+ import { readPluginConfig } from '../config/plugin-config-io.js';
7
+ import { getBracketMode, getBracketRequirements } from '../config/brackets-config.js';
8
+ import { formatError } from '../logger.js';
9
+ export function getBracketConfigTool(_args, deps) {
10
+ try {
11
+ const cfg = readPluginConfig(deps?.configPath);
12
+ const mode = getBracketMode(cfg);
13
+ const req = getBracketRequirements(cfg);
14
+ return {
15
+ mode,
16
+ requireStopLoss: req.requireStopLoss,
17
+ requireTakeProfit: req.requireTakeProfit,
18
+ };
19
+ }
20
+ catch (err) {
21
+ // Missing file → defaults; any other error → surface it.
22
+ return { error: formatError(err) };
23
+ }
24
+ }
@@ -0,0 +1,7 @@
1
+ import type { IntelApiDeps } from './intel-api.js';
2
+ export declare function getCascadeRiskTool(args: {
3
+ symbol: string;
4
+ hours?: number;
5
+ }, deps: IntelApiDeps): Promise<Record<string, unknown> | {
6
+ error: string;
7
+ }>;
@@ -0,0 +1,8 @@
1
+ // Tool: get_cascade_risk — fetches liquidation cascade risk assessment.
2
+ // Returns proximity to liquidation clusters, cascade impact estimates,
3
+ // recent liquidation activity, and overall risk score.
4
+ import { fetchIntelApi, enc, resolveIntelSymbol } from './intel-api.js';
5
+ export async function getCascadeRiskTool(args, deps) {
6
+ const hours = args.hours ?? 24;
7
+ return fetchIntelApi(`/api/cascade-risk/${enc(resolveIntelSymbol(deps, args.symbol))}?hours=${hours}`, deps);
8
+ }
@@ -0,0 +1,18 @@
1
+ import type { PublicMarketDataApi } from '../ccxt/public-market-data-api.js';
2
+ export interface CryptoMetricsResult {
3
+ symbol: string;
4
+ fundingRate: number | null;
5
+ fundingRateAnnualized: number | null;
6
+ openInterest: number | null;
7
+ openInterestUsd: number | null;
8
+ nextFundingTime: string | null;
9
+ lastPrice: number;
10
+ timestamp: string;
11
+ }
12
+ export declare function getCryptoMetricsTool(args: {
13
+ symbol: string;
14
+ }, deps: {
15
+ binanceApi: PublicMarketDataApi;
16
+ }): Promise<CryptoMetricsResult | {
17
+ error: string;
18
+ }>;
@@ -0,0 +1,62 @@
1
+ // Tool: get_crypto_metrics — funding rate + open interest from Binance perpetual futures
2
+ // Uses dedicated CCXT methods (fetchFundingRate + fetchOpenInterest) instead of fetchTicker,
3
+ // because Binance's 24hr ticker endpoint does NOT include funding/OI data.
4
+ import { fromIntelSymbol } from '../venues/symbols.js';
5
+ export async function getCryptoMetricsTool(args, deps) {
6
+ try {
7
+ // The agent routinely pastes intel-form ids into this tool ('ETHUSDT',
8
+ // 'HL_BTC' — ~100×/day live as of 2026-07-13). Handed to ccxt verbatim, a
9
+ // concatenated id resolves to the SPOT market and funding/OI fail
10
+ // ("supports linear and inverse contracts only"). Map both intel
11
+ // namespaces back to canonical BASE/QUOTE first; anything fromIntelSymbol
12
+ // can't map comes back verbatim (honest passthrough, no invented quote).
13
+ const canonical = args.symbol.includes('/') || args.symbol.includes(':')
14
+ ? args.symbol
15
+ : fromIntelSymbol(args.symbol.trim()).canonical;
16
+ // Funding rate & OI only exist on perpetual futures. Convert a canonical
17
+ // symbol to its linear-perp ccxt form by settling in the QUOTE currency
18
+ // (BTC/USDT → BTC/USDT:USDT on Binance, BTC/USDC → BTC/USDC:USDC on
19
+ // Hyperliquid). A hardcoded :USDT suffix produced the nonsense form
20
+ // BTC/USDC:USDT on the HL venue (seen live, wisekid soak 2026-07-12) —
21
+ // never silently translate quote assets across venues.
22
+ const quote = canonical.split('/')[1];
23
+ const perpSymbol = canonical.includes(':') || !quote
24
+ ? canonical
25
+ : `${canonical}:${quote}`;
26
+ // Fetch funding rate and open interest in parallel (separate API endpoints)
27
+ const [fundingData, oiData, tickerData] = await Promise.all([
28
+ deps.binanceApi.fetchFundingRate(perpSymbol),
29
+ deps.binanceApi.fetchOpenInterest(perpSymbol),
30
+ deps.binanceApi.fetchTickerRaw(perpSymbol), // for lastPrice
31
+ ]);
32
+ // Extract funding rate
33
+ const fundingRate = fundingData?.fundingRate ?? null;
34
+ const nextFundingTime = fundingData?.fundingDatetime
35
+ ?? (fundingData?.fundingTimestamp ? new Date(fundingData.fundingTimestamp).toISOString() : null);
36
+ // Annualized: funding rate * 3 periods/day * 365
37
+ const fundingRateAnnualized = fundingRate !== null
38
+ ? fundingRate * 3 * 365 * 100 // as percentage
39
+ : null;
40
+ // Extract open interest
41
+ const openInterest = oiData?.openInterestAmount ?? null;
42
+ let openInterestUsd = oiData?.openInterestValue ?? null;
43
+ // Estimate USD value if not provided directly
44
+ const lastPrice = tickerData?.last ?? 0;
45
+ if (openInterestUsd === null && openInterest !== null && lastPrice > 0) {
46
+ openInterestUsd = openInterest * lastPrice;
47
+ }
48
+ return {
49
+ symbol: args.symbol,
50
+ fundingRate: fundingRate !== null ? +fundingRate.toFixed(6) : null,
51
+ fundingRateAnnualized: fundingRateAnnualized !== null ? +fundingRateAnnualized.toFixed(2) : null,
52
+ openInterest: openInterest !== null ? +openInterest.toFixed(4) : null,
53
+ openInterestUsd: openInterestUsd !== null ? Math.round(openInterestUsd) : null,
54
+ nextFundingTime,
55
+ lastPrice,
56
+ timestamp: new Date().toISOString(),
57
+ };
58
+ }
59
+ catch (err) {
60
+ return { error: `get_crypto_metrics failed: ${err instanceof Error ? err.message : String(err)}` };
61
+ }
62
+ }
@@ -0,0 +1,6 @@
1
+ import type { IntelApiDeps } from './intel-api.js';
2
+ export declare function getCvdTool(args: {
3
+ symbol: string;
4
+ }, deps: IntelApiDeps): Promise<Record<string, unknown> | {
5
+ error: string;
6
+ }>;
@@ -0,0 +1,6 @@
1
+ // Tool: get_cvd — fetches CVD (Cumulative Volume Delta) analysis from the Intelligence API.
2
+ // Returns buy/sell pressure, divergence detection, slope, z-score, and interpretation.
3
+ import { fetchIntelApi, enc, resolveIntelSymbol } from './intel-api.js';
4
+ export async function getCvdTool(args, deps) {
5
+ return fetchIntelApi(`/api/cvd/${enc(resolveIntelSymbol(deps, args.symbol))}`, deps);
6
+ }
@@ -0,0 +1,6 @@
1
+ import type { IntelApiDeps } from './intel-api.js';
2
+ export declare function getDivergencesTool(args: {
3
+ symbol: string;
4
+ }, deps: IntelApiDeps): Promise<Record<string, unknown> | {
5
+ error: string;
6
+ }>;
@@ -0,0 +1,6 @@
1
+ // Tool: get_divergences — multi-timeframe RSI/MACD divergence scanner.
2
+ // Detects price-vs-indicator divergences across 15m, 1h, 4h, 1d timeframes.
3
+ import { fetchIntelApi, enc, resolveIntelSymbol } from './intel-api.js';
4
+ export async function getDivergencesTool(args, deps) {
5
+ return fetchIntelApi(`/api/divergences/${enc(resolveIntelSymbol(deps, args.symbol))}`, deps);
6
+ }
@@ -0,0 +1,6 @@
1
+ import type { IntelApiDeps } from './intel-api.js';
2
+ export declare function getFundingContextTool(args: {
3
+ symbol: string;
4
+ }, deps: IntelApiDeps): Promise<Record<string, unknown> | {
5
+ error: string;
6
+ }>;