@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,70 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { BinancePrivateApi } from '../ccxt/binance-private.js';
3
+ /** Injectable timer/clock deps β€” makes fake-timer tests trivial. */
4
+ export interface ListenKeyTimerDeps {
5
+ setTimeout: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;
6
+ clearTimeout: (handle: ReturnType<typeof setTimeout>) => void;
7
+ now: () => number;
8
+ }
9
+ export interface ListenKeyManagerOptions {
10
+ /** Defaults to 25 * 60_000 (25 min). */
11
+ refreshIntervalMs?: number;
12
+ /** How many consecutive keep-alive failures before emitting 'keyKeepAliveFailed'.
13
+ * Defaults to 3 β€” transient network failures self-recover; a sustained
14
+ * failure probably means the key is gone and the parent must reconnect. */
15
+ maxConsecutiveFailures?: number;
16
+ /** Timer injection for tests. Defaults to real setTimeout/Date. */
17
+ timers?: Partial<ListenKeyTimerDeps>;
18
+ }
19
+ /** Emitted events. Callers should treat 'keyKeepAliveFailed' as "drop the WS
20
+ * and restart from scratch" β€” the current key is presumed dead. */
21
+ export type ListenKeyEvents = {
22
+ /** Fresh key minted via POST /fapi/v1/listenKey. Fires on start() and
23
+ * after every successful re-mint. */
24
+ keyMinted: (listenKey: string) => void;
25
+ /** A keep-alive (PUT) succeeded. Informational β€” mostly for observability. */
26
+ keyRefreshed: () => void;
27
+ /** Consecutive keep-alive failures reached `maxConsecutiveFailures`. The
28
+ * parent should treat the stream as dead and reconnect from scratch. */
29
+ keyKeepAliveFailed: (reason: string) => void;
30
+ };
31
+ /** Lightweight typed emitter β€” EventEmitter with a phantom type. */
32
+ export declare class ListenKeyManager extends EventEmitter {
33
+ private readonly api;
34
+ private readonly refreshIntervalMs;
35
+ private readonly maxConsecutiveFailures;
36
+ private readonly timers;
37
+ private currentKey;
38
+ private keyMintedAt;
39
+ private refreshTimer;
40
+ private consecutiveFailures;
41
+ private running;
42
+ constructor(api: BinancePrivateApi, options?: ListenKeyManagerOptions);
43
+ /** Mint a listenKey and start the refresh loop. Returns the minted key.
44
+ * Throws if the first POST fails β€” caller decides how to back off. */
45
+ start(): Promise<string>;
46
+ /** Stop the refresh loop and best-effort close the key. Idempotent.
47
+ * For GRACEFUL shutdown only β€” a reconnect-driven teardown must use
48
+ * `stopKeepAlive()` instead (see below). */
49
+ stop(): Promise<void>;
50
+ /** Stop the refresh loop WITHOUT the DELETE β€” for reconnect-driven closes.
51
+ * Binance returns the SAME active listenKey on a re-POST and merely
52
+ * extends its validity (doc-verified 2026-07-02: "Doing a POST on an
53
+ * account with an active listenKey will return the currently active
54
+ * listenKey and extend its validity for 60 minutes"), so an in-flight
55
+ * DELETE racing the reconnect's POST can land AFTER it and invalidate the
56
+ * key the fresh socket just authenticated with β€” a silent dead stream.
57
+ * Skipping the DELETE is safe: an unused key expires on its own after
58
+ * 60 min of no keep-alive. Synchronous + idempotent. */
59
+ stopKeepAlive(): void;
60
+ /** Current listenKey, or null if stopped. */
61
+ getKey(): string | null;
62
+ /** Age in ms since the key was last minted. Null if stopped. Useful for
63
+ * observability dashboards β€” a key far beyond refreshIntervalMs but still
64
+ * alive means Binance is tolerating us past the nominal window. */
65
+ getKeyAge(): number | null;
66
+ /** Number of consecutive failed keep-alive probes. Exposed for diagnostics. */
67
+ getConsecutiveFailures(): number;
68
+ private scheduleRefresh;
69
+ private refresh;
70
+ }
@@ -0,0 +1,169 @@
1
+ // ListenKeyManager β€” owns the Binance Futures user-data listenKey lifecycle.
2
+ //
3
+ // Flow:
4
+ // 1. `start()` β€” POST /fapi/v1/listenKey β†’ emit 'keyMinted' with the listenKey.
5
+ // 2. Schedule PUT /fapi/v1/listenKey every `refreshIntervalMs` (default 25 min).
6
+ // Binance expires idle keys at 60 min; 25 min gives a 2x safety margin.
7
+ // 3. On failed keep-alive, re-mint (POST) a fresh key and emit 'keyRotated'.
8
+ // Binance returns the SAME listenKey for repeat POSTs from the same API
9
+ // key, so "re-mint" is effectively a probe that the key is still valid.
10
+ // If the probe succeeds, we accept its answer; if it fails, we emit
11
+ // 'keyKeepAliveFailed' and stop β€” the parent UserDataStream schedules
12
+ // a reconnect that re-enters `start()`.
13
+ // 4. `stop()` β€” clear timer + DELETE /fapi/v1/listenKey (best-effort).
14
+ //
15
+ // Why this is a separate component:
16
+ // - Testable in isolation with fake timers + a mock API.
17
+ // - UserDataStream can stay focused on frame parsing + reconnect logic.
18
+ // - Graduated alert thresholds live here (3 failed refreshes = WARN,
19
+ // 10 = ERROR) rather than being spread through the WS state machine.
20
+ import { EventEmitter } from 'node:events';
21
+ import { logger, formatError } from '../logger.js';
22
+ const TAG = 'listen-key-manager';
23
+ const REAL_TIMER_DEPS = {
24
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
25
+ clearTimeout: (h) => clearTimeout(h),
26
+ now: () => Date.now(),
27
+ };
28
+ /** Lightweight typed emitter β€” EventEmitter with a phantom type. */
29
+ export class ListenKeyManager extends EventEmitter {
30
+ api;
31
+ refreshIntervalMs;
32
+ maxConsecutiveFailures;
33
+ timers;
34
+ currentKey = null;
35
+ keyMintedAt = null;
36
+ refreshTimer = null;
37
+ consecutiveFailures = 0;
38
+ running = false;
39
+ constructor(api, options = {}) {
40
+ super();
41
+ this.api = api;
42
+ this.refreshIntervalMs = options.refreshIntervalMs ?? 25 * 60_000;
43
+ this.maxConsecutiveFailures = options.maxConsecutiveFailures ?? 3;
44
+ this.timers = {
45
+ setTimeout: options.timers?.setTimeout ?? REAL_TIMER_DEPS.setTimeout,
46
+ clearTimeout: options.timers?.clearTimeout ?? REAL_TIMER_DEPS.clearTimeout,
47
+ now: options.timers?.now ?? REAL_TIMER_DEPS.now,
48
+ };
49
+ }
50
+ /** Mint a listenKey and start the refresh loop. Returns the minted key.
51
+ * Throws if the first POST fails β€” caller decides how to back off. */
52
+ async start() {
53
+ if (this.running) {
54
+ throw new Error('ListenKeyManager already started');
55
+ }
56
+ const key = await this.api.createListenKey();
57
+ this.currentKey = key;
58
+ this.keyMintedAt = this.timers.now();
59
+ this.consecutiveFailures = 0;
60
+ this.running = true;
61
+ this.emit('keyMinted', key);
62
+ this.scheduleRefresh();
63
+ logger.info(TAG, `listenKey minted (hash=${hashKey(key)}), refresh every ${this.refreshIntervalMs / 1000}s`);
64
+ return key;
65
+ }
66
+ /** Stop the refresh loop and best-effort close the key. Idempotent.
67
+ * For GRACEFUL shutdown only β€” a reconnect-driven teardown must use
68
+ * `stopKeepAlive()` instead (see below). */
69
+ async stop() {
70
+ if (!this.running)
71
+ return;
72
+ this.running = false;
73
+ if (this.refreshTimer) {
74
+ this.timers.clearTimeout(this.refreshTimer);
75
+ this.refreshTimer = null;
76
+ }
77
+ if (this.currentKey) {
78
+ try {
79
+ await this.api.closeListenKey();
80
+ }
81
+ catch (err) {
82
+ // Not worth retrying on shutdown β€” Binance expires idle keys anyway.
83
+ logger.warn(TAG, `closeListenKey failed on stop (non-fatal): ${formatError(err)}`);
84
+ }
85
+ this.currentKey = null;
86
+ this.keyMintedAt = null;
87
+ }
88
+ }
89
+ /** Stop the refresh loop WITHOUT the DELETE β€” for reconnect-driven closes.
90
+ * Binance returns the SAME active listenKey on a re-POST and merely
91
+ * extends its validity (doc-verified 2026-07-02: "Doing a POST on an
92
+ * account with an active listenKey will return the currently active
93
+ * listenKey and extend its validity for 60 minutes"), so an in-flight
94
+ * DELETE racing the reconnect's POST can land AFTER it and invalidate the
95
+ * key the fresh socket just authenticated with β€” a silent dead stream.
96
+ * Skipping the DELETE is safe: an unused key expires on its own after
97
+ * 60 min of no keep-alive. Synchronous + idempotent. */
98
+ stopKeepAlive() {
99
+ if (!this.running)
100
+ return;
101
+ this.running = false;
102
+ if (this.refreshTimer) {
103
+ this.timers.clearTimeout(this.refreshTimer);
104
+ this.refreshTimer = null;
105
+ }
106
+ this.currentKey = null;
107
+ this.keyMintedAt = null;
108
+ }
109
+ /** Current listenKey, or null if stopped. */
110
+ getKey() {
111
+ return this.currentKey;
112
+ }
113
+ /** Age in ms since the key was last minted. Null if stopped. Useful for
114
+ * observability dashboards β€” a key far beyond refreshIntervalMs but still
115
+ * alive means Binance is tolerating us past the nominal window. */
116
+ getKeyAge() {
117
+ if (this.keyMintedAt == null)
118
+ return null;
119
+ return this.timers.now() - this.keyMintedAt;
120
+ }
121
+ /** Number of consecutive failed keep-alive probes. Exposed for diagnostics. */
122
+ getConsecutiveFailures() {
123
+ return this.consecutiveFailures;
124
+ }
125
+ // ---- Internal ----
126
+ scheduleRefresh() {
127
+ if (!this.running)
128
+ return;
129
+ this.refreshTimer = this.timers.setTimeout(() => {
130
+ this.refreshTimer = null;
131
+ void this.refresh();
132
+ }, this.refreshIntervalMs);
133
+ }
134
+ async refresh() {
135
+ if (!this.running)
136
+ return;
137
+ try {
138
+ await this.api.keepAliveListenKey();
139
+ this.consecutiveFailures = 0;
140
+ this.emit('keyRefreshed');
141
+ logger.info(TAG, `listenKey refreshed (age=${Math.round((this.getKeyAge() ?? 0) / 1000)}s)`);
142
+ this.scheduleRefresh();
143
+ }
144
+ catch (err) {
145
+ this.consecutiveFailures += 1;
146
+ const reason = formatError(err);
147
+ if (this.consecutiveFailures >= this.maxConsecutiveFailures) {
148
+ // Stream is dead. Don't reschedule β€” parent will restart us.
149
+ logger.error(TAG, `listenKey keep-alive failed ${this.consecutiveFailures} times (last: ${reason}) β€” giving up`);
150
+ this.running = false;
151
+ if (this.refreshTimer) {
152
+ this.timers.clearTimeout(this.refreshTimer);
153
+ this.refreshTimer = null;
154
+ }
155
+ this.emit('keyKeepAliveFailed', reason);
156
+ return;
157
+ }
158
+ // Transient β€” log and retry on the normal cadence. We deliberately do
159
+ // NOT shrink the interval on failure; the keep-alive window is 60 min
160
+ // so we can afford up to 2 more tries before the key expires.
161
+ logger.warn(TAG, `listenKey keep-alive failed (${this.consecutiveFailures}/${this.maxConsecutiveFailures}): ${reason}`);
162
+ this.scheduleRefresh();
163
+ }
164
+ }
165
+ }
166
+ /** First 8 chars of a listenKey for log correlation without leaking the key. */
167
+ function hashKey(key) {
168
+ return key.length > 8 ? key.slice(0, 8) : '(short)';
169
+ }
@@ -0,0 +1,319 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { IExchangeAdapter, AdapterReadiness, ClientOrderResolution, OrderOptions } from '../exchange-adapter.js';
3
+ import { BinancePrivateApi } from '../ccxt/binance-private.js';
4
+ import type { BinanceAlgoOrderProof } from '../ccxt/binance-private.js';
5
+ import type { CcxtOrder, CcxtBalance, CcxtPosition, TradingMode, ExchangeConfig } from '../types.js';
6
+ import type { PositionMetadata, CloseReason } from '../simulator/types.js';
7
+ import { ExchangeInfoCache } from './exchange-info-cache.js';
8
+ import { BinanceRateLimiter } from './rate-limiter.js';
9
+ import { IntentJournal } from './intent-journal.js';
10
+ import { OrderPoller } from './order-poller.js';
11
+ import { SlippageTracker } from './slippage-tracker.js';
12
+ import { PositionReconciler } from './reconciler.js';
13
+ import { LiveBalanceEnricher } from './live-balance-enricher.js';
14
+ import { DepositTracker } from './deposit-tracker.js';
15
+ import { BracketLedger } from './bracket-ledger.js';
16
+ import { BracketManager } from './bracket-manager.js';
17
+ import { type BracketMode } from '../config/brackets-config.js';
18
+ import { type UserDataStreamMode, type UserDataStreamTunables } from '../config/user-data-stream-config.js';
19
+ import { UserDataStreamController } from './user-data-stream-controller.js';
20
+ import { type AutoCaptureContext } from '../ingest/position-auto-capture.js';
21
+ import type { TradeStoreClient } from '../ingest/trade-store-client.js';
22
+ /** Optional audit-trail wiring (TRADE_AUDIT_TRAIL_PLAN Phase 1). Caller
23
+ * passes this only when userDataStream.dbWrite='on' AND the WEBAPP_INGEST_TOKEN
24
+ * + REEFCLAW_USER_ID env vars are present. Forwarded into the controller
25
+ * which spins up a WsIngest alongside the existing read path. */
26
+ export interface TradeIngestWiring {
27
+ client: TradeStoreClient;
28
+ userId: string;
29
+ exchange?: string;
30
+ }
31
+ export interface Wave9ProtectionLossEvent {
32
+ source: 'algo_canceled' | 'algo_rejected' | 'reconciler_missing';
33
+ symbol: string;
34
+ bracketId: string;
35
+ entryClientOrderId: string;
36
+ entrySide: 'buy' | 'sell';
37
+ stopClientOrderId?: string;
38
+ detail: string;
39
+ }
40
+ export type Wave9ProtectionLossHandler = (event: Wave9ProtectionLossEvent) => Promise<void> | void;
41
+ /**
42
+ * Backfill `balance.free[cur] = total[cur]` for currencies where Binance's CCXT
43
+ * response left the per-currency `free` and `used` at zero despite a non-zero
44
+ * total. Only safe when `used` is zero β€” otherwise the exchange really is
45
+ * reserving margin and we must not inflate availability.
46
+ */
47
+ export declare function repairFreeFromTotal(balance: CcxtBalance): void;
48
+ export declare class LiveAdapter extends EventEmitter implements IExchangeAdapter {
49
+ readonly mode: TradingMode;
50
+ readonly isLive = true;
51
+ private api;
52
+ private sizeCapMultiplier;
53
+ private maxPositionUSDT;
54
+ private exchangeInfo;
55
+ private isHedgeMode;
56
+ private getOpenOrdersUnavailableUntil;
57
+ private static readonly OPEN_ORDERS_RL_COOLDOWN_MS;
58
+ private rateLimiter;
59
+ private intentJournal;
60
+ private orderPoller;
61
+ private slippageTracker;
62
+ private reconciler;
63
+ private enricher;
64
+ private depositTracker;
65
+ private readonly bracketMode;
66
+ private bracketLedger;
67
+ private bracketManager;
68
+ private bracketReconciler;
69
+ private wave9ProtectionLossHandler?;
70
+ private readonly wave9ProtectionLossInFlight;
71
+ private readonly pendingWave9ProtectionLossBySymbol;
72
+ private static readonly PENDING_WAVE9_PROTECTION_LOSS_CAP;
73
+ private readonly userDataStreamMode;
74
+ private userDataStream;
75
+ private readonly wsAlgoStatusByCid;
76
+ private static readonly WS_ALGO_STATUS_CAP;
77
+ private static readonly WS_LIVE_LEG_MAX_AGE_MS;
78
+ private _sessionStartNav;
79
+ private lastIncomeRefreshMs;
80
+ private incomeAnchorUtcDay;
81
+ private liveMetadata;
82
+ private autoCapture?;
83
+ private _readiness;
84
+ get readiness(): AdapterReadiness;
85
+ /** Session-start NAV, captured once at initialization. Used for drawdown calculation. */
86
+ getSessionStartNav(): number | null;
87
+ constructor(config: ExchangeConfig, mode: 'MICRO_LIVE' | 'LIVE', microLiveConfig?: {
88
+ sizeCapPercent?: number;
89
+ maxPositionUSDT?: number;
90
+ }, bracketMode?: BracketMode, userDataStreamMode?: UserDataStreamMode, userDataStreamTunables?: UserDataStreamTunables,
91
+ /** TRADE_AUDIT_TRAIL_PLAN Phase 1 β€” optional audit-trail wiring. Wired
92
+ * through to UserDataStreamController. Absent today on every existing
93
+ * call site (default off); operator-driven once activation is approved. */
94
+ tradeIngest?: TradeIngestWiring,
95
+ /** Position-decision auto-capture wiring. When provided alongside
96
+ * tradeIngest, ws-ingest also routes every TRADE event through
97
+ * `onWsFillObserved` to capture limit-order entries + scale-ins
98
+ * (PR1 deferral resolution, 2026-05-03). Optional for back-compat. */
99
+ autoCapture?: AutoCaptureContext);
100
+ /** Get the underlying BinancePrivateApi (for advanced queries like fetchTicker). */
101
+ getApi(): BinancePrivateApi;
102
+ /** Get the exchange info cache (for symbol rules). */
103
+ getExchangeInfo(): ExchangeInfoCache;
104
+ /** Whether the account is in hedge mode. */
105
+ getIsHedgeMode(): boolean;
106
+ /** Get safety modules for external access (dashboard, tools, etc.). */
107
+ getRateLimiter(): BinanceRateLimiter;
108
+ getIntentJournal(): IntentJournal;
109
+ getOrderPoller(): OrderPoller;
110
+ getSlippageTracker(): SlippageTracker;
111
+ getReconciler(): PositionReconciler;
112
+ getEnricher(): LiveBalanceEnricher;
113
+ getDepositTracker(): DepositTracker;
114
+ /** Active user-data-stream mode. `'off'` when the feature flag is disabled. */
115
+ getUserDataStreamMode(): UserDataStreamMode;
116
+ /** User-data stream controller, or null if mode='off'. Used by dashboards
117
+ * and diagnostic tools to read the live-state store + health. */
118
+ getUserDataStream(): UserDataStreamController | null;
119
+ /**
120
+ * Post-registration async initialization.
121
+ * Must complete before create_order is allowed (readiness gate).
122
+ * Emergency controls (cancel, close) work regardless of readiness.
123
+ */
124
+ initialize(): Promise<void>;
125
+ /**
126
+ * Acknowledge existing positions on startup.
127
+ * Transitions DEGRADED β†’ READY. Exchange info + position mode are already loaded
128
+ * (they're loaded before the position check in initialize()).
129
+ */
130
+ acknowledgePositions(): Promise<void>;
131
+ /**
132
+ * Tear down background loops so the adapter can be replaced at runtime
133
+ * (e.g. when the operator changes credentials or trading mode from the
134
+ * dashboard). Must be called before discarding the LiveAdapter reference
135
+ * or the poller + reconciler timers will keep firing against stale state.
136
+ *
137
+ * Idempotent β€” safe to call multiple times.
138
+ */
139
+ shutdown(): void;
140
+ createOrder(symbol: string, side: 'buy' | 'sell', type: 'market' | 'limit', amount: number, price?: number, metadata?: PositionMetadata, options?: OrderOptions): Promise<CcxtOrder>;
141
+ /**
142
+ * Attach brackets in the background. Auto-flattens on failure per locked
143
+ * decision #2. Never throws β€” errors are surfaced via emitted events and
144
+ * the subsequent flatten.
145
+ */
146
+ private attachBracketsAsync;
147
+ /**
148
+ * Patch `order.average` with the authoritative average fill price when a
149
+ * filled order came back without one (marketable-limit RESULT quirk, #196).
150
+ * Re-queries by clientOrderId (GET /fapi/v1/order, weight 1). Best-effort:
151
+ * on any failure or an unresolvable re-query the order is left as-is β€”
152
+ * downstream then falls back to a mark price / skips capture, NEVER to the
153
+ * limit price. Mutates `order` in place.
154
+ */
155
+ private enrichFilledAvgPrice;
156
+ /**
157
+ * Journal the close produced by an internal auto-flatten
158
+ * (`bracket_attach_failed`), so the position row can't orphan as
159
+ * status='open' (issue #196). These flattens go straight to
160
+ * `this.closePosition`, bypassing the close_position tool, so
161
+ * `onClosePositionFilled` never runs for them. Fire-and-forget + fail-open β€”
162
+ * never blocks or throws into the flatten path. The entry journal may not be
163
+ * ready at flatten time (the entry's WS fill can land ~1-2s later), so
164
+ * `onAutoFlattenClose` polls briefly for the webappPositionId; the boot DB
165
+ * reconcile sweep is the backstop if the entry never journals.
166
+ */
167
+ private captureAutoFlattenClose;
168
+ /** Install the Wave 9-only autonomous recovery bridge. With no handler,
169
+ * every generic bracket lifecycle remains byte-for-byte behaviorally
170
+ * unchanged. Runtime reapplies this setter after adapter reconnects. */
171
+ setWave9ProtectionLossHandler(handler?: Wave9ProtectionLossHandler): void;
172
+ private notifyWave9ProtectionLoss;
173
+ /**
174
+ * AUTHORITATIVE bracket-lifecycle handler β€” Binance's ALGO_UPDATE push.
175
+ *
176
+ * Why this exists (2026-05-15 RCA, doc-verified): pre-fix the plugin
177
+ * learned bracket state by REST-polling `audit_bracket_protection` /
178
+ * `fetchOpenOrders` and *guessing* β€” under a 429 storm that produced the
179
+ * audit→re-attach→cancel spiral that flushed live positions. Binance
180
+ * already PUSHES authoritative conditional-order lifecycle. Doc-exact
181
+ * status semantics (developers.binance.com β†’ Event Algo Order Update):
182
+ *
183
+ * EXPIRED = SYSTEM cancel. The canonical trigger is "GTE_GTC
184
+ * conditional + position closed β†’ Binance auto-cancels the
185
+ * surviving sibling". So EXPIRED on our bracket cid β‡’ the
186
+ * position just closed by a non-close_position path (bracket
187
+ * fill, manual, opposite-side). EXPECTED β€” not a fault.
188
+ * TRIGGERED / FINISHED = the bracket fired (SL/TP hit) β†’ position closed.
189
+ * CANCELED = MANUAL cancel (an explicit cancelOrder from us). Post the
190
+ * bracket-reconciler fix we should NOT be doing this while a
191
+ * position is open; if we see it, it's the canary that some
192
+ * *other* path still strips protection β€” WARN loudly.
193
+ *
194
+ * For EXPIRED/TRIGGERED/FINISHED we (a) mark the ledger terminal so the
195
+ * attach-brackets re-attach loop STOPS chasing a bracket Binance already
196
+ * removed, and (b) emit the SAME `drift_detected` shape the position
197
+ * reconciler emits, so the existing, tested close-bypass cleanup
198
+ * (`onReconcilerObservedClose` in index.ts) runs immediately instead of
199
+ * up to 60 s later β€” which is what clears the stale state-store entry and
200
+ * stops the NEXT entry on the symbol being mis-classified as a scale-in
201
+ * (the bug that left fresh positions naked). No auto-flatten here: that
202
+ * stays deferred until this signal has soaked.
203
+ */
204
+ private onAlgoUpdate;
205
+ /** Expose the bracket manager for agent-facing tools (modify_stop, etc.).
206
+ * Returns null when bracket mode is 'off'. */
207
+ getBracketManager(): BracketManager | null;
208
+ /** Expose the bracket ledger for reconciliation + admin queries. */
209
+ getBracketLedger(): BracketLedger | null;
210
+ /** Is the user-data WS store currently trusted (seeded + fresh + no gap)?
211
+ * The Tier-1 gate for resolveBracketLegLiveness β€” when false the WS
212
+ * per-cid signal is NOT consulted (a stale/gapped stream that missed a
213
+ * CANCELED would otherwise yield a false 'live' on a naked leg β€” the exact
214
+ * flaw the layered design exists to prevent). Null stream (mode=off) β‡’
215
+ * never trusted β‡’ always the REST authority. */
216
+ isUserDataStoreTrusted(): boolean;
217
+ /** Authoritative per-bracket-leg liveness β€” the Phase 2 disambiguator that
218
+ * replaces inferring presence/absence from a broad openOrders snapshot
219
+ * (the SOL/INJ spiral root: a *successful* empty /fapi/v1/openAlgoOrders
220
+ * is NOT proof a leg is gone).
221
+ *
222
+ * Precedence (the agreed layering):
223
+ * 1. WS fast-path β€” ONLY behind isUserDataStoreTrusted(): the real
224
+ * per-cid ALGO_UPDATE status (incl. CANCELED, which the ledger does
225
+ * NOT record). Zero weight, sub-second. No record for the cid β‡’ no
226
+ * WS opinion β‡’ fall through (never infer from absence).
227
+ * 2. REST authority β€” queryAlgoOrderStatus(cid): a DIRECT weight-1
228
+ * question about that exact order id. Used when WS is untrusted or
229
+ * silent on the cid.
230
+ * 3. 'unknown' β€” both unavailable. The d59e51b safe floor: callers MUST
231
+ * refuse destructive action and retry; NEVER treat 'unknown' as
232
+ * 'terminal'/'stale'.
233
+ *
234
+ * 'live' = leg is on the exchange (do NOT reattach/clobber).
235
+ * 'terminal' = positively confirmed gone (CANCELED/EXPIRED/REJECTED) or
236
+ * fired (TRIGGERED/FINISHED) β€” only this licenses repair.
237
+ * 'unknown' = could not get an answer β€” safe-wait. */
238
+ resolveBracketLegLiveness(cid: string): Promise<'live' | 'terminal' | 'unknown'>;
239
+ /** Immediate full-shape proof for one exact native conditional order. */
240
+ resolveBracketLegProof(cid: string): Promise<BinanceAlgoOrderProof | null>;
241
+ /** Symbol-scoped generalization of the trusted-WS fast-path β€” the
242
+ * authoritative action-layer guard for the 2026-05-16 INJ bracket spiral.
243
+ *
244
+ * `resolveBracketLegLiveness(cid)` answers about ONE cid. The spiral is:
245
+ * a prior `attach_brackets` reattach placed a FRESH bracket that is live
246
+ * on the exchange under a NEW cid, while the ledger row still holds the
247
+ * PREVIOUS, genuinely-terminal cids. Classifying only the ledger's cids
248
+ * yields a false 'stale' β†’ clear+reattach cancels the live fresh bracket
249
+ * β†’ naked β†’ audit unprotected β†’ attach β†’ spiral (prod: INJ/USDT cancelled
250
+ * every ~15-40s for hours). This asks the question the ledger cids can't:
251
+ * "is ANY rc-* bracket leg for this symbol live RIGHT NOW, under any cid?"
252
+ *
253
+ * Trust model (identical to resolveBracketLegLiveness Tier-1): the WS map
254
+ * is consulted ONLY when `isUserDataStoreTrusted()` (seeded + fresh +
255
+ * no-gap β€” the property that guarantees no missed CANCELED, so a record
256
+ * reading 'live' really is live). When the store is NOT trusted this
257
+ * returns `{ trusted:false, liveCids:[] }` and the caller must NOT infer
258
+ * "no live leg" from it β€” it falls back to the per-leg REST authority and,
259
+ * failing that, refuses the destructive action (the d59e51b safe floor).
260
+ * A record older than WS_LIVE_LEG_MAX_AGE_MS is ignored (caller falls back
261
+ * too) so a stale 'live' can never suppress a genuine repair forever. */
262
+ findTrustedLiveBracketCidsForSymbol(symbol: string): {
263
+ trusted: boolean;
264
+ liveCids: string[];
265
+ };
266
+ /** Cancel every bracket-tagged (SL or TP) open order for a symbol. Used by
267
+ * the `attach_brackets` recovery tool to clear stale bracket orders before
268
+ * re-attaching a fresh pair. Does not touch non-bracket orders. Returns
269
+ * the number successfully cancelled. Errors are logged + swallowed β€”
270
+ * "already gone" is treated as success by the underlying cancel path. */
271
+ cancelSymbolBracketOrders(symbol: string): Promise<number>;
272
+ cancelOrder(orderId: string, symbol?: string): Promise<CcxtOrder>;
273
+ cancelAllOrders(symbol?: string): Promise<CcxtOrder[]>;
274
+ closePosition(symbol: string, closeReason?: CloseReason): Promise<CcxtOrder>;
275
+ /** Re-arm protection on a position whose closePosition flow cancelled the
276
+ * brackets and then failed every market-close attempt. Reuses the normal
277
+ * attach machinery: re-register the ledger row (terminal row β†’ fresh
278
+ * pending_entry with the SAME stop/target levels) and run the standard
279
+ * 3-retry attach. Never throws β€” this runs on the already-failing close
280
+ * path; on any failure it emits the reconciler's `position_unprotected`
281
+ * drift shape (re-emitted upstream as `bracket_drift`) plus a loud log so
282
+ * the operator knows re-protection is required. */
283
+ private reattachBracketsAfterFailedClose;
284
+ /** Null-honest balance read: null = the fetch FAILED (429 / weight-paced /
285
+ * banned) β€” the caller MUST treat it as UNKNOWN, never as a zero balance.
286
+ * Same null≠empty contract as getPositionsOrNull. Decision paths (sizing,
287
+ * pre-trade risk) must use this: the legacy getBalance() collapse below
288
+ * reads as walletTotal=0 β†’ ~βˆ’100% drawdown β†’ RED zone. */
289
+ getBalanceOrNull(): Promise<CcxtBalance | null>;
290
+ /** Legacy display-path read. Collapses a FAILED fetch to an empty balance
291
+ * object β€” acceptable for read-only surfaces (fetch_balance tool,
292
+ * risk-summary display), a phantom-zero hazard for anything that decides.
293
+ * Decision paths use getBalanceOrNull(). */
294
+ getBalance(): Promise<CcxtBalance>;
295
+ /** Re-anchor the realized-today seed + sessionStartNav from /fapi/v1/income.
296
+ * Throttled to {@link INCOME_REFRESH_MIN_INTERVAL_MS}; UTC date rollover
297
+ * forces an immediate refresh. Best-effort β€” failures are logged and
298
+ * swallowed so a transient income-endpoint blip never blocks a balance
299
+ * read. Called from getBalance() with the fresh quote wallet so we don't
300
+ * fetch balance twice.
301
+ */
302
+ private refreshIncomeAnchor;
303
+ getPositions(symbol?: string): Promise<CcxtPosition[]>;
304
+ getPositionsOrNull(symbol?: string): Promise<CcxtPosition[] | null>;
305
+ /** Merge agent-supplied entry metadata + ratchet MFE state into the raw
306
+ * CCXT position list. Side effect: drops metadata for symbols no longer
307
+ * in the open-positions snapshot (only when called without a symbol filter
308
+ * β€” symbol-scoped calls skip cleanup so we don't lose context for other
309
+ * open positions). */
310
+ private decoratePositionsWithMetadata;
311
+ getOpenOrders(symbol?: string): Promise<CcxtOrder[]>;
312
+ fetchOrder(orderId: string, symbol?: string): Promise<CcxtOrder | null>;
313
+ resolveOrderByClientId(clientOrderId: string, symbol: string): Promise<ClientOrderResolution>;
314
+ getLastPrice(symbol: string): Promise<number | null>;
315
+ /** Sync rate limiter from exchange response headers after every private API call. */
316
+ private syncRateLimits;
317
+ private loadExchangeInfo;
318
+ private detectPositionMode;
319
+ }