@reefclaw/connect 0.1.10 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (396) hide show
  1. package/assets/bridge/gateway/event-parser.d.ts +6 -1
  2. package/assets/bridge/gateway/event-parser.js +19 -2
  3. package/assets/bridge/gateway/heartbeat-cron.d.ts +27 -0
  4. package/assets/bridge/gateway/heartbeat-cron.js +85 -0
  5. package/assets/bridge/gateway/poller.d.ts +1 -0
  6. package/assets/bridge/gateway/poller.js +14 -2
  7. package/assets/bridge/providers/gateway.d.ts +24 -2
  8. package/assets/bridge/providers/gateway.js +124 -25
  9. package/assets/bridge/setup.js +6 -51
  10. package/assets/shared/signals/conditions/registry.js +11 -2
  11. package/assets/shared/signals/strategy-adapter.js +17 -7
  12. package/assets/skill/SKILL.md +2 -0
  13. package/dist/deps.js +2 -2
  14. package/dist/plugin.js +35 -7
  15. package/package.json +1 -1
  16. package/assets/plugin/audit/mode-transition-audit.d.ts +0 -11
  17. package/assets/plugin/audit/mode-transition-audit.js +0 -29
  18. package/assets/plugin/balance-utils.d.ts +0 -36
  19. package/assets/plugin/balance-utils.js +0 -98
  20. package/assets/plugin/ccxt/binance-ban-gate.d.ts +0 -47
  21. package/assets/plugin/ccxt/binance-ban-gate.js +0 -420
  22. package/assets/plugin/ccxt/binance-private.d.ts +0 -346
  23. package/assets/plugin/ccxt/binance-private.js +0 -1525
  24. package/assets/plugin/ccxt/binance-public.d.ts +0 -34
  25. package/assets/plugin/ccxt/binance-public.js +0 -180
  26. package/assets/plugin/ccxt/intel-public.d.ts +0 -25
  27. package/assets/plugin/ccxt/intel-public.js +0 -80
  28. package/assets/plugin/ccxt/public-market-data-api.d.ts +0 -12
  29. package/assets/plugin/ccxt/public-market-data-api.js +0 -9
  30. package/assets/plugin/config/agent-config-client.d.ts +0 -77
  31. package/assets/plugin/config/agent-config-client.js +0 -188
  32. package/assets/plugin/config/agent-config-poller.d.ts +0 -32
  33. package/assets/plugin/config/agent-config-poller.js +0 -101
  34. package/assets/plugin/config/brackets-config.d.ts +0 -22
  35. package/assets/plugin/config/brackets-config.js +0 -58
  36. package/assets/plugin/config/entitlement-gate.d.ts +0 -51
  37. package/assets/plugin/config/entitlement-gate.js +0 -137
  38. package/assets/plugin/config/gate-store.d.ts +0 -18
  39. package/assets/plugin/config/gate-store.js +0 -61
  40. package/assets/plugin/config/plugin-config-io.d.ts +0 -215
  41. package/assets/plugin/config/plugin-config-io.js +0 -111
  42. package/assets/plugin/config/position-review-config.d.ts +0 -35
  43. package/assets/plugin/config/position-review-config.js +0 -105
  44. package/assets/plugin/config/tool-gate.d.ts +0 -53
  45. package/assets/plugin/config/tool-gate.js +0 -128
  46. package/assets/plugin/config/user-data-stream-config.d.ts +0 -89
  47. package/assets/plugin/config/user-data-stream-config.js +0 -239
  48. package/assets/plugin/connector-supervisor.d.ts +0 -36
  49. package/assets/plugin/connector-supervisor.js +0 -149
  50. package/assets/plugin/exchange-adapter.d.ts +0 -65
  51. package/assets/plugin/exchange-adapter.js +0 -4
  52. package/assets/plugin/index.d.ts +0 -30
  53. package/assets/plugin/index.js +0 -2678
  54. package/assets/plugin/ingest/pending-entry-metadata.d.ts +0 -74
  55. package/assets/plugin/ingest/pending-entry-metadata.js +0 -236
  56. package/assets/plugin/ingest/position-auto-capture.d.ts +0 -103
  57. package/assets/plugin/ingest/position-auto-capture.js +0 -411
  58. package/assets/plugin/ingest/position-decisions-client.d.ts +0 -322
  59. package/assets/plugin/ingest/position-decisions-client.js +0 -296
  60. package/assets/plugin/ingest/readiness-reporter.d.ts +0 -42
  61. package/assets/plugin/ingest/readiness-reporter.js +0 -163
  62. package/assets/plugin/ingest/reconcile-db-vs-exchange.d.ts +0 -13
  63. package/assets/plugin/ingest/reconcile-db-vs-exchange.js +0 -114
  64. package/assets/plugin/ingest/reconciler-cleanup.d.ts +0 -37
  65. package/assets/plugin/ingest/reconciler-cleanup.js +0 -147
  66. package/assets/plugin/ingest/rest-gap-filler.d.ts +0 -191
  67. package/assets/plugin/ingest/rest-gap-filler.js +0 -565
  68. package/assets/plugin/ingest/touched-symbols-store.d.ts +0 -25
  69. package/assets/plugin/ingest/touched-symbols-store.js +0 -96
  70. package/assets/plugin/ingest/trade-store-client.d.ts +0 -40
  71. package/assets/plugin/ingest/trade-store-client.js +0 -125
  72. package/assets/plugin/ingest/ws-ingest.d.ts +0 -43
  73. package/assets/plugin/ingest/ws-ingest.js +0 -126
  74. package/assets/plugin/learning/setup-family.d.ts +0 -21
  75. package/assets/plugin/learning/setup-family.js +0 -103
  76. package/assets/plugin/lifecycle/install-signal-handlers.d.ts +0 -33
  77. package/assets/plugin/lifecycle/install-signal-handlers.js +0 -112
  78. package/assets/plugin/lifecycle/shutdown-coordinator.d.ts +0 -43
  79. package/assets/plugin/lifecycle/shutdown-coordinator.js +0 -131
  80. package/assets/plugin/lifecycle/trading-operation-lock.d.ts +0 -17
  81. package/assets/plugin/lifecycle/trading-operation-lock.js +0 -14
  82. package/assets/plugin/live/bracket-id.d.ts +0 -26
  83. package/assets/plugin/live/bracket-id.js +0 -112
  84. package/assets/plugin/live/bracket-ledger.d.ts +0 -54
  85. package/assets/plugin/live/bracket-ledger.js +0 -267
  86. package/assets/plugin/live/bracket-manager.d.ts +0 -82
  87. package/assets/plugin/live/bracket-manager.js +0 -478
  88. package/assets/plugin/live/bracket-params.d.ts +0 -22
  89. package/assets/plugin/live/bracket-params.js +0 -124
  90. package/assets/plugin/live/bracket-reconciler.d.ts +0 -95
  91. package/assets/plugin/live/bracket-reconciler.js +0 -573
  92. package/assets/plugin/live/bracket-types.d.ts +0 -102
  93. package/assets/plugin/live/bracket-types.js +0 -8
  94. package/assets/plugin/live/deposit-tracker.d.ts +0 -62
  95. package/assets/plugin/live/deposit-tracker.js +0 -97
  96. package/assets/plugin/live/emergency-controls.d.ts +0 -32
  97. package/assets/plugin/live/emergency-controls.js +0 -226
  98. package/assets/plugin/live/exchange-errors.d.ts +0 -12
  99. package/assets/plugin/live/exchange-errors.js +0 -130
  100. package/assets/plugin/live/exchange-info-cache.d.ts +0 -37
  101. package/assets/plugin/live/exchange-info-cache.js +0 -134
  102. package/assets/plugin/live/fact-subscriber.d.ts +0 -78
  103. package/assets/plugin/live/fact-subscriber.js +0 -182
  104. package/assets/plugin/live/intent-journal.d.ts +0 -42
  105. package/assets/plugin/live/intent-journal.js +0 -122
  106. package/assets/plugin/live/listen-key-manager.d.ts +0 -70
  107. package/assets/plugin/live/listen-key-manager.js +0 -169
  108. package/assets/plugin/live/live-adapter.d.ts +0 -287
  109. package/assets/plugin/live/live-adapter.js +0 -1777
  110. package/assets/plugin/live/live-balance-enricher.d.ts +0 -32
  111. package/assets/plugin/live/live-balance-enricher.js +0 -104
  112. package/assets/plugin/live/live-bracket-api.d.ts +0 -13
  113. package/assets/plugin/live/live-bracket-api.js +0 -20
  114. package/assets/plugin/live/live-state-store.d.ts +0 -194
  115. package/assets/plugin/live/live-state-store.js +0 -450
  116. package/assets/plugin/live/local-signal-service.d.ts +0 -57
  117. package/assets/plugin/live/local-signal-service.js +0 -151
  118. package/assets/plugin/live/local-strategy-evaluator.d.ts +0 -62
  119. package/assets/plugin/live/local-strategy-evaluator.js +0 -131
  120. package/assets/plugin/live/microstructure-assembler.d.ts +0 -54
  121. package/assets/plugin/live/microstructure-assembler.js +0 -148
  122. package/assets/plugin/live/order-poller.d.ts +0 -29
  123. package/assets/plugin/live/order-poller.js +0 -125
  124. package/assets/plugin/live/position-state-store.d.ts +0 -83
  125. package/assets/plugin/live/position-state-store.js +0 -237
  126. package/assets/plugin/live/proposal-decision-listener.d.ts +0 -70
  127. package/assets/plugin/live/proposal-decision-listener.js +0 -292
  128. package/assets/plugin/live/proposal-manager.d.ts +0 -76
  129. package/assets/plugin/live/proposal-manager.js +0 -140
  130. package/assets/plugin/live/rate-limiter.d.ts +0 -47
  131. package/assets/plugin/live/rate-limiter.js +0 -159
  132. package/assets/plugin/live/reconciler.d.ts +0 -39
  133. package/assets/plugin/live/reconciler.js +0 -175
  134. package/assets/plugin/live/setup-buckets.d.ts +0 -7
  135. package/assets/plugin/live/setup-buckets.js +0 -33
  136. package/assets/plugin/live/slippage-tracker.d.ts +0 -45
  137. package/assets/plugin/live/slippage-tracker.js +0 -78
  138. package/assets/plugin/live/stop-watcher.d.ts +0 -60
  139. package/assets/plugin/live/stop-watcher.js +0 -215
  140. package/assets/plugin/live/user-data-active-probe.d.ts +0 -54
  141. package/assets/plugin/live/user-data-active-probe.js +0 -180
  142. package/assets/plugin/live/user-data-stream-controller.d.ts +0 -200
  143. package/assets/plugin/live/user-data-stream-controller.js +0 -579
  144. package/assets/plugin/live/user-data-stream-ws.d.ts +0 -22
  145. package/assets/plugin/live/user-data-stream-ws.js +0 -63
  146. package/assets/plugin/live/user-data-stream.d.ts +0 -243
  147. package/assets/plugin/live/user-data-stream.js +0 -704
  148. package/assets/plugin/logger.d.ts +0 -2
  149. package/assets/plugin/logger.js +0 -2
  150. package/assets/plugin/mfe.d.ts +0 -21
  151. package/assets/plugin/mfe.js +0 -68
  152. package/assets/plugin/onboarding/mode-ladder.d.ts +0 -1
  153. package/assets/plugin/onboarding/mode-ladder.js +0 -3
  154. package/assets/plugin/onboarding/runtime.d.ts +0 -84
  155. package/assets/plugin/onboarding/runtime.js +0 -173
  156. package/assets/plugin/openclaw.plugin.json +0 -92
  157. package/assets/plugin/paper-adapter.d.ts +0 -24
  158. package/assets/plugin/paper-adapter.js +0 -91
  159. package/assets/plugin/persistence/state-manager.d.ts +0 -66
  160. package/assets/plugin/persistence/state-manager.js +0 -222
  161. package/assets/plugin/pinned-plan.d.ts +0 -9
  162. package/assets/plugin/pinned-plan.js +0 -23
  163. package/assets/plugin/portfolio/wave9-admission.d.ts +0 -67
  164. package/assets/plugin/portfolio/wave9-admission.js +0 -262
  165. package/assets/plugin/portfolio/wave9-policy.d.ts +0 -36
  166. package/assets/plugin/portfolio/wave9-policy.js +0 -183
  167. package/assets/plugin/risk/pre-trade-check.d.ts +0 -38
  168. package/assets/plugin/risk/pre-trade-check.js +0 -345
  169. package/assets/plugin/risk/pre-trade-types.d.ts +0 -60
  170. package/assets/plugin/risk/pre-trade-types.js +0 -3
  171. package/assets/plugin/shadow/shadow-tracker.d.ts +0 -36
  172. package/assets/plugin/shadow/shadow-tracker.js +0 -151
  173. package/assets/plugin/shadow/types.d.ts +0 -42
  174. package/assets/plugin/shadow/types.js +0 -20
  175. package/assets/plugin/shared/indicators-extended.d.ts +0 -52
  176. package/assets/plugin/shared/indicators-extended.js +0 -291
  177. package/assets/plugin/shared/indicators.d.ts +0 -15
  178. package/assets/plugin/shared/indicators.js +0 -114
  179. package/assets/plugin/signals/conditions/registry.d.ts +0 -16
  180. package/assets/plugin/signals/conditions/registry.js +0 -1324
  181. package/assets/plugin/signals/conditions/types.d.ts +0 -1
  182. package/assets/plugin/signals/conditions/types.js +0 -4
  183. package/assets/plugin/signals/direction-rules.d.ts +0 -3
  184. package/assets/plugin/signals/direction-rules.js +0 -24
  185. package/assets/plugin/signals/entry-rules.d.ts +0 -6
  186. package/assets/plugin/signals/entry-rules.js +0 -33
  187. package/assets/plugin/signals/serialize-context.d.ts +0 -4
  188. package/assets/plugin/signals/serialize-context.js +0 -39
  189. package/assets/plugin/signals/stop-rules.d.ts +0 -3
  190. package/assets/plugin/signals/stop-rules.js +0 -48
  191. package/assets/plugin/signals/strategy-adapter.d.ts +0 -47
  192. package/assets/plugin/signals/strategy-adapter.js +0 -199
  193. package/assets/plugin/signals/types.d.ts +0 -1
  194. package/assets/plugin/signals/types.js +0 -8
  195. package/assets/plugin/simulator/exchange-simulator.d.ts +0 -93
  196. package/assets/plugin/simulator/exchange-simulator.js +0 -689
  197. package/assets/plugin/simulator/fill-engine.d.ts +0 -53
  198. package/assets/plugin/simulator/fill-engine.js +0 -280
  199. package/assets/plugin/simulator/paper-market-feed.d.ts +0 -26
  200. package/assets/plugin/simulator/paper-market-feed.js +0 -104
  201. package/assets/plugin/simulator/realistic-fills.d.ts +0 -59
  202. package/assets/plugin/simulator/realistic-fills.js +0 -175
  203. package/assets/plugin/simulator/types.d.ts +0 -224
  204. package/assets/plugin/simulator/types.js +0 -43
  205. package/assets/plugin/strategy/builtin-strategies.d.ts +0 -2
  206. package/assets/plugin/strategy/builtin-strategies.js +0 -113
  207. package/assets/plugin/strategy/condition-registry.d.ts +0 -3
  208. package/assets/plugin/strategy/condition-registry.js +0 -153
  209. package/assets/plugin/strategy/evaluator.d.ts +0 -70
  210. package/assets/plugin/strategy/evaluator.js +0 -98
  211. package/assets/plugin/tools/assessment-validation.d.ts +0 -120
  212. package/assets/plugin/tools/assessment-validation.js +0 -415
  213. package/assets/plugin/tools/attach-brackets.d.ts +0 -39
  214. package/assets/plugin/tools/attach-brackets.js +0 -399
  215. package/assets/plugin/tools/audit-bracket-protection.d.ts +0 -49
  216. package/assets/plugin/tools/audit-bracket-protection.js +0 -527
  217. package/assets/plugin/tools/cancel-all-orders.d.ts +0 -9
  218. package/assets/plugin/tools/cancel-all-orders.js +0 -8
  219. package/assets/plugin/tools/cancel-order.d.ts +0 -14
  220. package/assets/plugin/tools/cancel-order.js +0 -60
  221. package/assets/plugin/tools/check-position-health.d.ts +0 -46
  222. package/assets/plugin/tools/check-position-health.js +0 -194
  223. package/assets/plugin/tools/clear-exchange-credentials.d.ts +0 -24
  224. package/assets/plugin/tools/clear-exchange-credentials.js +0 -70
  225. package/assets/plugin/tools/close-position.d.ts +0 -45
  226. package/assets/plugin/tools/close-position.js +0 -722
  227. package/assets/plugin/tools/create-order.d.ts +0 -82
  228. package/assets/plugin/tools/create-order.js +0 -1516
  229. package/assets/plugin/tools/exit-gate.d.ts +0 -58
  230. package/assets/plugin/tools/exit-gate.js +0 -162
  231. package/assets/plugin/tools/fetch-balance.d.ts +0 -5
  232. package/assets/plugin/tools/fetch-balance.js +0 -4
  233. package/assets/plugin/tools/fetch-ohlcv.d.ts +0 -11
  234. package/assets/plugin/tools/fetch-ohlcv.js +0 -8
  235. package/assets/plugin/tools/fetch-open-orders.d.ts +0 -7
  236. package/assets/plugin/tools/fetch-open-orders.js +0 -4
  237. package/assets/plugin/tools/fetch-positions.d.ts +0 -7
  238. package/assets/plugin/tools/fetch-positions.js +0 -4
  239. package/assets/plugin/tools/fetch-ticker.d.ts +0 -11
  240. package/assets/plugin/tools/fetch-ticker.js +0 -5
  241. package/assets/plugin/tools/get-agent-profile.d.ts +0 -4
  242. package/assets/plugin/tools/get-agent-profile.js +0 -6
  243. package/assets/plugin/tools/get-analytics.d.ts +0 -6
  244. package/assets/plugin/tools/get-analytics.js +0 -7
  245. package/assets/plugin/tools/get-backtest.d.ts +0 -12
  246. package/assets/plugin/tools/get-backtest.js +0 -91
  247. package/assets/plugin/tools/get-basis.d.ts +0 -7
  248. package/assets/plugin/tools/get-basis.js +0 -7
  249. package/assets/plugin/tools/get-bracket-config.d.ts +0 -11
  250. package/assets/plugin/tools/get-bracket-config.js +0 -24
  251. package/assets/plugin/tools/get-cascade-risk.d.ts +0 -7
  252. package/assets/plugin/tools/get-cascade-risk.js +0 -8
  253. package/assets/plugin/tools/get-crypto-metrics.d.ts +0 -18
  254. package/assets/plugin/tools/get-crypto-metrics.js +0 -62
  255. package/assets/plugin/tools/get-cvd.d.ts +0 -6
  256. package/assets/plugin/tools/get-cvd.js +0 -6
  257. package/assets/plugin/tools/get-divergences.d.ts +0 -6
  258. package/assets/plugin/tools/get-divergences.js +0 -6
  259. package/assets/plugin/tools/get-funding-context.d.ts +0 -6
  260. package/assets/plugin/tools/get-funding-context.js +0 -16
  261. package/assets/plugin/tools/get-liquidation-levels.d.ts +0 -7
  262. package/assets/plugin/tools/get-liquidation-levels.js +0 -7
  263. package/assets/plugin/tools/get-liquidation-pulse.d.ts +0 -9
  264. package/assets/plugin/tools/get-liquidation-pulse.js +0 -22
  265. package/assets/plugin/tools/get-market-breadth.d.ts +0 -6
  266. package/assets/plugin/tools/get-market-breadth.js +0 -8
  267. package/assets/plugin/tools/get-market-intel.d.ts +0 -19
  268. package/assets/plugin/tools/get-market-intel.js +0 -116
  269. package/assets/plugin/tools/get-market-structure.d.ts +0 -47
  270. package/assets/plugin/tools/get-market-structure.js +0 -198
  271. package/assets/plugin/tools/get-my-mined-patterns.d.ts +0 -20
  272. package/assets/plugin/tools/get-my-mined-patterns.js +0 -61
  273. package/assets/plugin/tools/get-my-proposed-learnings.d.ts +0 -20
  274. package/assets/plugin/tools/get-my-proposed-learnings.js +0 -55
  275. package/assets/plugin/tools/get-my-recent-reviews.d.ts +0 -22
  276. package/assets/plugin/tools/get-my-recent-reviews.js +0 -66
  277. package/assets/plugin/tools/get-orderbook.d.ts +0 -21
  278. package/assets/plugin/tools/get-orderbook.js +0 -32
  279. package/assets/plugin/tools/get-pattern-scan.d.ts +0 -7
  280. package/assets/plugin/tools/get-pattern-scan.js +0 -8
  281. package/assets/plugin/tools/get-regime.d.ts +0 -6
  282. package/assets/plugin/tools/get-regime.js +0 -7
  283. package/assets/plugin/tools/get-relevant-learnings.d.ts +0 -21
  284. package/assets/plugin/tools/get-relevant-learnings.js +0 -65
  285. package/assets/plugin/tools/get-resting-liquidity.d.ts +0 -6
  286. package/assets/plugin/tools/get-resting-liquidity.js +0 -11
  287. package/assets/plugin/tools/get-risk-scenario.d.ts +0 -29
  288. package/assets/plugin/tools/get-risk-scenario.js +0 -47
  289. package/assets/plugin/tools/get-risk-summary.d.ts +0 -51
  290. package/assets/plugin/tools/get-risk-summary.js +0 -118
  291. package/assets/plugin/tools/get-sentiment.d.ts +0 -4
  292. package/assets/plugin/tools/get-sentiment.js +0 -6
  293. package/assets/plugin/tools/get-session-review.d.ts +0 -7
  294. package/assets/plugin/tools/get-session-review.js +0 -8
  295. package/assets/plugin/tools/get-setup-detail.d.ts +0 -7
  296. package/assets/plugin/tools/get-setup-detail.js +0 -311
  297. package/assets/plugin/tools/get-signals.d.ts +0 -15
  298. package/assets/plugin/tools/get-signals.js +0 -54
  299. package/assets/plugin/tools/get-sizing.d.ts +0 -6
  300. package/assets/plugin/tools/get-sizing.js +0 -6
  301. package/assets/plugin/tools/get-trade-feedback.d.ts +0 -7
  302. package/assets/plugin/tools/get-trade-feedback.js +0 -8
  303. package/assets/plugin/tools/get-trade-flow.d.ts +0 -7
  304. package/assets/plugin/tools/get-trade-flow.js +0 -7
  305. package/assets/plugin/tools/get-volume-analysis.d.ts +0 -21
  306. package/assets/plugin/tools/get-volume-analysis.js +0 -74
  307. package/assets/plugin/tools/get-volume-profile.d.ts +0 -7
  308. package/assets/plugin/tools/get-volume-profile.js +0 -7
  309. package/assets/plugin/tools/get-wave9-status.d.ts +0 -127
  310. package/assets/plugin/tools/get-wave9-status.js +0 -796
  311. package/assets/plugin/tools/helpers.d.ts +0 -26
  312. package/assets/plugin/tools/helpers.js +0 -39
  313. package/assets/plugin/tools/intel-api.d.ts +0 -34
  314. package/assets/plugin/tools/intel-api.js +0 -119
  315. package/assets/plugin/tools/intel-cache.d.ts +0 -25
  316. package/assets/plugin/tools/intel-cache.js +0 -148
  317. package/assets/plugin/tools/list-strategies.d.ts +0 -17
  318. package/assets/plugin/tools/list-strategies.js +0 -23
  319. package/assets/plugin/tools/modify-stop.d.ts +0 -21
  320. package/assets/plugin/tools/modify-stop.js +0 -120
  321. package/assets/plugin/tools/modify-target.d.ts +0 -21
  322. package/assets/plugin/tools/modify-target.js +0 -110
  323. package/assets/plugin/tools/propose-learning.d.ts +0 -22
  324. package/assets/plugin/tools/propose-learning.js +0 -65
  325. package/assets/plugin/tools/query-review-outcomes.d.ts +0 -30
  326. package/assets/plugin/tools/query-review-outcomes.js +0 -64
  327. package/assets/plugin/tools/query-trades.d.ts +0 -21
  328. package/assets/plugin/tools/query-trades.js +0 -37
  329. package/assets/plugin/tools/record-position-reviews.d.ts +0 -38
  330. package/assets/plugin/tools/record-position-reviews.js +0 -147
  331. package/assets/plugin/tools/save-strategy.d.ts +0 -16
  332. package/assets/plugin/tools/save-strategy.js +0 -46
  333. package/assets/plugin/tools/scan-pairs.d.ts +0 -18
  334. package/assets/plugin/tools/scan-pairs.js +0 -231
  335. package/assets/plugin/tools/score-setup.d.ts +0 -31
  336. package/assets/plugin/tools/score-setup.js +0 -268
  337. package/assets/plugin/tools/set-bracket-requirement.d.ts +0 -18
  338. package/assets/plugin/tools/set-bracket-requirement.js +0 -81
  339. package/assets/plugin/tools/set-exchange-credentials.d.ts +0 -25
  340. package/assets/plugin/tools/set-exchange-credentials.js +0 -80
  341. package/assets/plugin/tools/set-trading-mode.d.ts +0 -26
  342. package/assets/plugin/tools/set-trading-mode.js +0 -135
  343. package/assets/plugin/tools/test-exchange-credentials.d.ts +0 -16
  344. package/assets/plugin/tools/test-exchange-credentials.js +0 -100
  345. package/assets/plugin/tools/toggle-strategy.d.ts +0 -8
  346. package/assets/plugin/tools/toggle-strategy.js +0 -15
  347. package/assets/plugin/trading-params-cache.d.ts +0 -26
  348. package/assets/plugin/trading-params-cache.js +0 -52
  349. package/assets/plugin/types.d.ts +0 -134
  350. package/assets/plugin/types.js +0 -7
  351. package/assets/plugin/util/plugin-paths.d.ts +0 -3
  352. package/assets/plugin/util/plugin-paths.js +0 -15
  353. package/assets/plugin/venues/hyperliquid/hl-balance.d.ts +0 -116
  354. package/assets/plugin/venues/hyperliquid/hl-balance.js +0 -145
  355. package/assets/plugin/venues/hyperliquid/hl-brackets.d.ts +0 -102
  356. package/assets/plugin/venues/hyperliquid/hl-brackets.js +0 -172
  357. package/assets/plugin/venues/hyperliquid/hl-cloid.d.ts +0 -22
  358. package/assets/plugin/venues/hyperliquid/hl-cloid.js +0 -82
  359. package/assets/plugin/venues/hyperliquid/hl-info-cache.d.ts +0 -46
  360. package/assets/plugin/venues/hyperliquid/hl-info-cache.js +0 -125
  361. package/assets/plugin/venues/hyperliquid/hl-live-adapter.d.ts +0 -88
  362. package/assets/plugin/venues/hyperliquid/hl-live-adapter.js +0 -353
  363. package/assets/plugin/venues/hyperliquid/hl-precision.d.ts +0 -61
  364. package/assets/plugin/venues/hyperliquid/hl-precision.js +0 -176
  365. package/assets/plugin/venues/hyperliquid/hl-private.d.ts +0 -88
  366. package/assets/plugin/venues/hyperliquid/hl-private.js +0 -357
  367. package/assets/plugin/venues/hyperliquid/hl-public.d.ts +0 -79
  368. package/assets/plugin/venues/hyperliquid/hl-public.js +0 -429
  369. package/assets/plugin/venues/hyperliquid/hl-rate-gate.d.ts +0 -57
  370. package/assets/plugin/venues/hyperliquid/hl-rate-gate.js +0 -220
  371. package/assets/plugin/venues/hyperliquid/hl-user-stream.d.ts +0 -90
  372. package/assets/plugin/venues/hyperliquid/hl-user-stream.js +0 -220
  373. package/assets/plugin/venues/registry.d.ts +0 -38
  374. package/assets/plugin/venues/registry.js +0 -46
  375. package/assets/plugin/venues/symbols.d.ts +0 -43
  376. package/assets/plugin/venues/symbols.js +0 -107
  377. package/assets/plugin/wave9/live-account-capture.d.ts +0 -67
  378. package/assets/plugin/wave9/live-account-capture.js +0 -435
  379. package/assets/plugin/wave9/live-autonomous-protection.d.ts +0 -39
  380. package/assets/plugin/wave9/live-autonomous-protection.js +0 -112
  381. package/assets/plugin/wave9/live-durable-reconciliation-scheduler.d.ts +0 -33
  382. package/assets/plugin/wave9/live-durable-reconciliation-scheduler.js +0 -115
  383. package/assets/plugin/wave9/live-execution-ledger.d.ts +0 -107
  384. package/assets/plugin/wave9/live-execution-ledger.js +0 -498
  385. package/assets/plugin/wave9/live-position-confirmation.d.ts +0 -18
  386. package/assets/plugin/wave9/live-position-confirmation.js +0 -111
  387. package/assets/plugin/wave9/live-residual-protection.d.ts +0 -18
  388. package/assets/plugin/wave9/live-residual-protection.js +0 -250
  389. package/assets/plugin/wave9/live-startup-reconciliation.d.ts +0 -38
  390. package/assets/plugin/wave9/live-startup-reconciliation.js +0 -454
  391. package/assets/plugin/wave9/live-symbol-ownership.d.ts +0 -20
  392. package/assets/plugin/wave9/live-symbol-ownership.js +0 -132
  393. package/assets/plugin/wave9/paper-admission-guard.d.ts +0 -199
  394. package/assets/plugin/wave9/paper-admission-guard.js +0 -650
  395. package/assets/plugin/wave9/usdm-evidence-provider.d.ts +0 -42
  396. package/assets/plugin/wave9/usdm-evidence-provider.js +0 -133
@@ -1,37 +0,0 @@
1
- export interface SymbolRules {
2
- minNotional: number;
3
- minQty: number;
4
- stepSize: number;
5
- tickSize: number;
6
- maxQty: number;
7
- pricePrecision: number;
8
- amountPrecision: number;
9
- }
10
- export interface ValidationResult {
11
- valid: boolean;
12
- error?: string;
13
- roundedAmount: number;
14
- roundedPrice?: number;
15
- }
16
- /**
17
- * Normalize symbol format for consistent lookups.
18
- * Tools use "BTC/USDT", CCXT futures markets are "BTC/USDT:USDT".
19
- * This function tries both formats to find a match.
20
- */
21
- export declare function normalizeSymbol(symbol: string, knownSymbols: Set<string>): string;
22
- export declare class ExchangeInfoCache {
23
- private rules;
24
- /** Set of all known symbols for normalization lookups. */
25
- private knownSymbols;
26
- /** Load market info from CCXT exchange instance. Throws on failure (incl.
27
- * an active ban — the gate short-circuits with zero network so a boot
28
- * during a 418 can't extend it); callers treat a throw as init failure. */
29
- load(exchange: any): Promise<void>;
30
- /** Get rules for a symbol (tries both BTC/USDT and BTC/USDT:USDT formats). */
31
- getRules(symbol: string): SymbolRules | undefined;
32
- /** Validate and round order parameters before submission. */
33
- validate(symbol: string, amount: number, price?: number, lastPrice?: number): ValidationResult;
34
- /** Round value to step size and precision. */
35
- private roundToStep;
36
- get size(): number;
37
- }
@@ -1,134 +0,0 @@
1
- // Exchange info cache — caches per-symbol trading rules (min notional, lot sizes, tick sizes).
2
- // Loaded once on startup from CCXT loadMarkets(), used to validate and round orders before submission.
3
- import { logger } from '../logger.js';
4
- import { assertNotBanned, noteBinanceError, noteSuccess } from '../ccxt/binance-ban-gate.js';
5
- const TAG = 'exchange-info';
6
- /**
7
- * Normalize symbol format for consistent lookups.
8
- * Tools use "BTC/USDT", CCXT futures markets are "BTC/USDT:USDT".
9
- * This function tries both formats to find a match.
10
- */
11
- export function normalizeSymbol(symbol, knownSymbols) {
12
- // Exact match first
13
- if (knownSymbols.has(symbol))
14
- return symbol;
15
- // Try adding :USDT suffix (most common futures pattern)
16
- const withSuffix = `${symbol}:USDT`;
17
- if (knownSymbols.has(withSuffix))
18
- return withSuffix;
19
- // Try removing :USDT suffix
20
- const withoutSuffix = symbol.replace(/:USDT$/, '');
21
- if (knownSymbols.has(withoutSuffix))
22
- return withoutSuffix;
23
- // No match — return as-is (will fail validation with "Unknown symbol")
24
- return symbol;
25
- }
26
- export class ExchangeInfoCache {
27
- rules = new Map();
28
- /** Set of all known symbols for normalization lookups. */
29
- knownSymbols = new Set();
30
- /** Load market info from CCXT exchange instance. Throws on failure (incl.
31
- * an active ban — the gate short-circuits with zero network so a boot
32
- * during a 418 can't extend it); callers treat a throw as init failure. */
33
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
34
- async load(exchange) {
35
- let info;
36
- try {
37
- // GET /fapi/v1/exchangeInfo via ccxt loadMarkets — IP weight 1
38
- // (doc-verified). Ban-gated but never weight-paced (NEVER_PACE):
39
- // once-per-boot and required for order validation + emergency close.
40
- assertNotBanned('loadMarkets');
41
- info = await exchange.loadMarkets(true); // force refresh
42
- noteSuccess();
43
- }
44
- catch (err) {
45
- noteBinanceError(err);
46
- throw err;
47
- }
48
- for (const [symbol, market] of Object.entries(info)) {
49
- const m = market;
50
- // Only cache futures (swap) markets
51
- if (m.type !== 'swap')
52
- continue;
53
- const limits = m.limits;
54
- const precision = m.precision;
55
- const rules = {
56
- minNotional: limits?.cost?.min ?? 5,
57
- minQty: limits?.amount?.min ?? 0.001,
58
- stepSize: precision?.amount != null ? Math.pow(10, -precision.amount) : 0.001,
59
- tickSize: precision?.price != null ? Math.pow(10, -precision.price) : 0.01,
60
- maxQty: limits?.amount?.max ?? Infinity,
61
- pricePrecision: precision?.price ?? 2,
62
- amountPrecision: precision?.amount ?? 3,
63
- };
64
- // Store under both "BTC/USDT:USDT" and "BTC/USDT" keys for lookup flexibility
65
- this.rules.set(symbol, rules);
66
- this.knownSymbols.add(symbol);
67
- const shortSymbol = symbol.replace(/:USDT$/, '');
68
- if (shortSymbol !== symbol && !this.rules.has(shortSymbol)) {
69
- this.rules.set(shortSymbol, rules);
70
- this.knownSymbols.add(shortSymbol);
71
- }
72
- }
73
- logger.info(TAG, `Loaded exchange rules for ${this.knownSymbols.size} symbols`);
74
- }
75
- /** Get rules for a symbol (tries both BTC/USDT and BTC/USDT:USDT formats). */
76
- getRules(symbol) {
77
- return this.rules.get(symbol) ?? this.rules.get(normalizeSymbol(symbol, this.knownSymbols));
78
- }
79
- /** Validate and round order parameters before submission. */
80
- validate(symbol, amount, price, lastPrice) {
81
- const normalized = normalizeSymbol(symbol, this.knownSymbols);
82
- const rules = this.rules.get(normalized);
83
- if (!rules)
84
- return { valid: false, error: `Unknown symbol: ${symbol}`, roundedAmount: amount };
85
- const roundedAmount = this.roundToStep(amount, rules.stepSize, rules.amountPrecision);
86
- const roundedPrice = price != null
87
- ? this.roundToStep(price, rules.tickSize, rules.pricePrecision)
88
- : undefined;
89
- if (roundedAmount < rules.minQty) {
90
- // Include the requested amount + the rule context. Without this, sub-step
91
- // requests floor to 0 and the agent reads "Amount 0 below min 0.001"
92
- // as a validator bug rather than as "your size is below the exchange
93
- // minimum". Surface the dollar minimum too when we know the price —
94
- // tells the agent exactly how much to size up.
95
- const refPrice = roundedPrice ?? price ?? lastPrice;
96
- const minNotionalAtPrice = refPrice != null && refPrice > 0
97
- ? ` (~$${(rules.minQty * refPrice).toFixed(2)})`
98
- : '';
99
- const requestedDesc = roundedAmount === amount
100
- ? `${roundedAmount}`
101
- : `${amount} (rounded to ${roundedAmount} by step ${rules.stepSize})`;
102
- return {
103
- valid: false,
104
- error: `Amount ${requestedDesc} below min ${rules.minQty}${minNotionalAtPrice} for ${symbol}`,
105
- roundedAmount,
106
- };
107
- }
108
- if (roundedAmount > rules.maxQty) {
109
- return { valid: false, error: `Amount ${roundedAmount} above max ${rules.maxQty} for ${symbol}`, roundedAmount };
110
- }
111
- // Check min notional (order value)
112
- const refPrice = roundedPrice ?? lastPrice;
113
- if (refPrice != null && refPrice > 0) {
114
- const notional = roundedAmount * refPrice;
115
- if (notional < rules.minNotional) {
116
- return {
117
- valid: false,
118
- error: `Order notional $${notional.toFixed(2)} below minimum $${rules.minNotional} for ${symbol}`,
119
- roundedAmount,
120
- roundedPrice,
121
- };
122
- }
123
- }
124
- return { valid: true, roundedAmount, roundedPrice };
125
- }
126
- /** Round value to step size and precision. */
127
- roundToStep(value, stepSize, precision) {
128
- const stepped = Math.floor(value / stepSize) * stepSize;
129
- return Number(stepped.toFixed(precision));
130
- }
131
- get size() {
132
- return this.rules.size;
133
- }
134
- }
@@ -1,78 +0,0 @@
1
- import type { MarketContext } from '@reefclaw/shared';
2
- export interface ParsedEvent {
3
- id?: number;
4
- event: string;
5
- data: string;
6
- }
7
- /**
8
- * Incremental SSE parser. Feed raw text; returns the complete events plus the
9
- * unparsed remainder (a partial event still arriving at the buffer tail). Pure.
10
- */
11
- export declare function parseSse(buffer: string): {
12
- events: ParsedEvent[];
13
- remainder: string;
14
- };
15
- export interface FactSubscriberOptions {
16
- /** Intel base URL, e.g. https://intel.reefclaw.com */
17
- baseUrl: string;
18
- /** rc_ connection token. */
19
- token: string;
20
- symbols: string[];
21
- /** Injected for tests; defaults to global fetch. */
22
- fetchImpl?: typeof fetch;
23
- /** Base reconnect delay (ms). Doubles per consecutive failure with ±20%
24
- * jitter up to reconnectCapMs — a fixed delay would hard-loop a 401/404
25
- * (token misconfig / stream disabled) at max rate forever. */
26
- reconnectDelayMs?: number;
27
- /** Reconnect backoff cap (ms, default 60s). */
28
- reconnectCapMs?: number;
29
- /** Abort + reconnect when a LIVE connection delivers no bytes for this
30
- * long (default 30s = 6× the broadcaster's 5s cadence). Without this, a
31
- * silently stalled stream (no close, no RST) leaves `reader.read()`
32
- * pending forever while the evaluator keeps serving ever-staler facts —
33
- * same class as the user-data-stream / routed-WS staleness watchdogs. */
34
- stallThresholdMs?: number;
35
- /** Injected for tests. */
36
- now?: () => number;
37
- }
38
- export declare class FactSubscriber {
39
- private readonly opts;
40
- private readonly latest;
41
- /** Per-symbol wall-clock receipt time of the latest fact (now()-based). */
42
- private readonly latestAt;
43
- private buffer;
44
- private lastEventId;
45
- private running;
46
- private controller;
47
- private applied;
48
- private errors;
49
- private stalls;
50
- private consecutiveFailures;
51
- /** 0 = no live connection; otherwise last byte-activity time. */
52
- private lastChunkAt;
53
- private watchdog;
54
- private readonly now;
55
- constructor(opts: FactSubscriberOptions);
56
- /** Latest streamed context for a symbol — what the evaluator reads. */
57
- getLatest(symbol: string): MarketContext | null;
58
- /** When the latest fact for a symbol ARRIVED (receipt clock, not the
59
- * context's own timestamp). Null when no fact has ever arrived. Callers
60
- * use this to refuse stale facts (LocalSignalService.getSnapshot). */
61
- getLatestFactAt(symbol: string): number | null;
62
- getStats(): {
63
- applied: number;
64
- errors: number;
65
- stalls: number;
66
- lastEventId: number | undefined;
67
- symbols: number;
68
- };
69
- /** Apply one parsed event: deserialize a `fact` and store it as the latest
70
- * context for its symbol. No I/O — exposed for tests. */
71
- applyEvent(ev: ParsedEvent): void;
72
- /** Feed a raw text chunk; handles events split across chunk boundaries. */
73
- ingest(chunk: string): void;
74
- start(): void;
75
- stop(): void;
76
- private backoffMs;
77
- private loop;
78
- }
@@ -1,182 +0,0 @@
1
- // Plugin-side fact stream subscriber — facts-out (docs/FACTS_OUT_ARCHITECTURE.md)
2
- // step 4. Connects to the intel broadcaster's SSE endpoint
3
- // (/api/facts/subscribe), maintains the latest MarketContext per symbol, and
4
- // feeds it to the LocalStrategyEvaluator (PR #45). Reconnects with Last-Event-ID.
5
- //
6
- // Uses the SAME matched (de)serializer the broadcaster uses (shared via the sync
7
- // manifest), so the wire round-trip is byte-identical — the Date fields are
8
- // rehydrated rather than left as strings.
9
- //
10
- // NOT wired into the heartbeat yet — built + tested standalone. The parse /
11
- // apply core is pure and unit-tested; the fetch loop is thin plumbing.
12
- import { deserializeContext } from '../signals/serialize-context.js';
13
- /**
14
- * Incremental SSE parser. Feed raw text; returns the complete events plus the
15
- * unparsed remainder (a partial event still arriving at the buffer tail). Pure.
16
- */
17
- export function parseSse(buffer) {
18
- const events = [];
19
- let sep;
20
- // Events are terminated by a blank line ("\n\n").
21
- while ((sep = buffer.indexOf('\n\n')) !== -1) {
22
- const raw = buffer.slice(0, sep);
23
- buffer = buffer.slice(sep + 2);
24
- let id;
25
- let event = 'message';
26
- const dataLines = [];
27
- for (const line of raw.split('\n')) {
28
- if (line.startsWith('id:')) {
29
- const v = Number(line.slice(3).trim());
30
- if (Number.isFinite(v))
31
- id = v;
32
- }
33
- else if (line.startsWith('event:')) {
34
- event = line.slice(6).trim();
35
- }
36
- else if (line.startsWith('data:')) {
37
- dataLines.push(line.slice(5).replace(/^ /, ''));
38
- }
39
- // ":" comment lines and unknown fields are ignored, per the SSE spec.
40
- }
41
- events.push({ id, event, data: dataLines.join('\n') });
42
- }
43
- return { events, remainder: buffer };
44
- }
45
- export class FactSubscriber {
46
- opts;
47
- latest = new Map();
48
- /** Per-symbol wall-clock receipt time of the latest fact (now()-based). */
49
- latestAt = new Map();
50
- buffer = '';
51
- lastEventId;
52
- running = false;
53
- controller = null;
54
- applied = 0;
55
- errors = 0;
56
- stalls = 0;
57
- consecutiveFailures = 0;
58
- /** 0 = no live connection; otherwise last byte-activity time. */
59
- lastChunkAt = 0;
60
- watchdog = null;
61
- now;
62
- constructor(opts) {
63
- this.opts = opts;
64
- this.now = opts.now ?? Date.now;
65
- }
66
- /** Latest streamed context for a symbol — what the evaluator reads. */
67
- getLatest(symbol) {
68
- return this.latest.get(symbol) ?? null;
69
- }
70
- /** When the latest fact for a symbol ARRIVED (receipt clock, not the
71
- * context's own timestamp). Null when no fact has ever arrived. Callers
72
- * use this to refuse stale facts (LocalSignalService.getSnapshot). */
73
- getLatestFactAt(symbol) {
74
- return this.latestAt.get(symbol) ?? null;
75
- }
76
- getStats() {
77
- return {
78
- applied: this.applied,
79
- errors: this.errors,
80
- stalls: this.stalls,
81
- lastEventId: this.lastEventId,
82
- symbols: this.latest.size,
83
- };
84
- }
85
- /** Apply one parsed event: deserialize a `fact` and store it as the latest
86
- * context for its symbol. No I/O — exposed for tests. */
87
- applyEvent(ev) {
88
- if (ev.id !== undefined)
89
- this.lastEventId = ev.id;
90
- if (ev.event !== 'fact')
91
- return;
92
- try {
93
- const ctx = deserializeContext(ev.data);
94
- this.latest.set(ctx.symbol, ctx);
95
- this.latestAt.set(ctx.symbol, this.now());
96
- this.applied++;
97
- }
98
- catch {
99
- this.errors++;
100
- }
101
- }
102
- /** Feed a raw text chunk; handles events split across chunk boundaries. */
103
- ingest(chunk) {
104
- this.buffer += chunk;
105
- const { events, remainder } = parseSse(this.buffer);
106
- this.buffer = remainder;
107
- for (const ev of events)
108
- this.applyEvent(ev);
109
- }
110
- start() {
111
- if (this.running)
112
- return;
113
- this.running = true;
114
- const stallMs = this.opts.stallThresholdMs ?? 30_000;
115
- this.watchdog = setInterval(() => {
116
- if (!this.running || this.lastChunkAt === 0)
117
- return;
118
- if (this.now() - this.lastChunkAt > stallMs) {
119
- this.stalls++;
120
- this.lastChunkAt = 0; // one abort per stall — reset until reconnect
121
- this.controller?.abort();
122
- }
123
- }, Math.max(1_000, Math.floor(stallMs / 3)));
124
- this.watchdog.unref?.();
125
- void this.loop();
126
- }
127
- stop() {
128
- this.running = false;
129
- if (this.watchdog) {
130
- clearInterval(this.watchdog);
131
- this.watchdog = null;
132
- }
133
- this.controller?.abort();
134
- }
135
- backoffMs() {
136
- const base = this.opts.reconnectDelayMs ?? 3_000;
137
- const cap = this.opts.reconnectCapMs ?? 60_000;
138
- const exp = Math.min(base * 2 ** Math.min(this.consecutiveFailures, 10), cap);
139
- return Math.round(exp * (0.8 + Math.random() * 0.4)); // ±20% jitter
140
- }
141
- async loop() {
142
- const doFetch = this.opts.fetchImpl ?? fetch;
143
- const url = `${this.opts.baseUrl}/api/facts/subscribe?symbols=${encodeURIComponent(this.opts.symbols.join(','))}`;
144
- while (this.running) {
145
- this.controller = new AbortController();
146
- let gotData = false;
147
- try {
148
- const headers = {
149
- Authorization: `Bearer ${this.opts.token}`,
150
- Accept: 'text/event-stream',
151
- };
152
- if (this.lastEventId !== undefined)
153
- headers['Last-Event-ID'] = String(this.lastEventId);
154
- const resp = await doFetch(url, { headers, signal: this.controller.signal });
155
- if (!resp.ok || !resp.body)
156
- throw new Error(`fact stream HTTP ${resp.status}`);
157
- this.buffer = '';
158
- this.lastChunkAt = this.now(); // arm the stall watchdog
159
- const reader = resp.body.getReader();
160
- const decoder = new TextDecoder();
161
- while (this.running) {
162
- const { done, value } = await reader.read();
163
- if (done)
164
- break;
165
- this.lastChunkAt = this.now();
166
- gotData = true;
167
- this.ingest(decoder.decode(value, { stream: true }));
168
- }
169
- }
170
- catch {
171
- if (!this.running)
172
- return;
173
- this.errors++;
174
- }
175
- this.lastChunkAt = 0; // no live connection — watchdog idle
176
- if (!this.running)
177
- return;
178
- this.consecutiveFailures = gotData ? 0 : this.consecutiveFailures + 1;
179
- await new Promise((r) => setTimeout(r, this.backoffMs()));
180
- }
181
- }
182
- }
@@ -1,42 +0,0 @@
1
- export interface OrderIntent {
2
- clientOrderId: string;
3
- symbol: string;
4
- side: 'buy' | 'sell';
5
- type: 'market' | 'limit';
6
- amount: number;
7
- price?: number;
8
- createdAt: string;
9
- status: 'pending' | 'submitted' | 'confirmed' | 'failed';
10
- exchangeOrderId?: string;
11
- error?: string;
12
- resolvedAt?: string;
13
- }
14
- export declare class IntentJournal {
15
- private readonly filePath;
16
- private intents;
17
- /** `basePath` overrides the storage root (default `~/.openclaw/plugins`).
18
- * Tests pass a temp dir to keep runs hermetic; production omits it.
19
- * `OPENCLAW_HOME` env var, when set, also reroutes the default base. */
20
- constructor(pluginId?: string, opts?: {
21
- basePath?: string;
22
- });
23
- /** Record a new order intent BEFORE submitting to exchange. */
24
- recordIntent(intent: Omit<OrderIntent, 'createdAt' | 'status'>): OrderIntent;
25
- /** Update intent status after exchange response. */
26
- updateIntent(clientOrderId: string, update: Partial<Pick<OrderIntent, 'status' | 'exchangeOrderId' | 'error'>>): void;
27
- /** Get all unresolved intents (pending or submitted). */
28
- getUnresolved(): OrderIntent[];
29
- /** Get intent by clientOrderId. */
30
- getIntent(clientOrderId: string): OrderIntent | undefined;
31
- /** Get the journal file path. */
32
- getFilePath(): string;
33
- /** Load existing intents from JSONL file. Later entries override earlier ones (last-write-wins). */
34
- private loadExisting;
35
- /** Append a line to the JSONL file. */
36
- private appendLine;
37
- /**
38
- * Compact the journal — rewrite with only the latest state of each intent.
39
- * Call periodically (e.g., daily) to prevent unbounded file growth.
40
- */
41
- compact(): void;
42
- }
@@ -1,122 +0,0 @@
1
- // Order intent journal — append-only JSONL file for crash recovery and idempotency.
2
- // Every live order intent is written BEFORE submission. On network timeout,
3
- // check exchange by clientOrderId before retry. On restart, resolve all pending intents.
4
- import { appendFileSync, readFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';
5
- import { join } from 'node:path';
6
- import { logger, formatError } from '../logger.js';
7
- import { resolvePluginsBaseDir } from '../util/plugin-paths.js';
8
- const TAG = 'intent-journal';
9
- export class IntentJournal {
10
- filePath;
11
- intents = new Map();
12
- /** `basePath` overrides the storage root (default `~/.openclaw/plugins`).
13
- * Tests pass a temp dir to keep runs hermetic; production omits it.
14
- * `OPENCLAW_HOME` env var, when set, also reroutes the default base. */
15
- constructor(pluginId, opts) {
16
- const base = resolvePluginsBaseDir(opts?.basePath);
17
- const dir = join(base, pluginId ?? 'reefclaw-paper-trading');
18
- if (!existsSync(dir)) {
19
- mkdirSync(dir, { recursive: true });
20
- }
21
- this.filePath = join(dir, 'order-intents.jsonl');
22
- this.loadExisting();
23
- }
24
- /** Record a new order intent BEFORE submitting to exchange. */
25
- recordIntent(intent) {
26
- const full = {
27
- ...intent,
28
- createdAt: new Date().toISOString(),
29
- status: 'pending',
30
- };
31
- this.intents.set(full.clientOrderId, full);
32
- this.appendLine(full);
33
- logger.info(TAG, `Intent recorded: ${full.clientOrderId} ${full.side} ${full.amount} ${full.symbol}`);
34
- return full;
35
- }
36
- /** Update intent status after exchange response. */
37
- updateIntent(clientOrderId, update) {
38
- const intent = this.intents.get(clientOrderId);
39
- if (!intent) {
40
- logger.warn(TAG, `Intent not found for update: ${clientOrderId}`);
41
- return;
42
- }
43
- if (update.status)
44
- intent.status = update.status;
45
- if (update.exchangeOrderId)
46
- intent.exchangeOrderId = update.exchangeOrderId;
47
- if (update.error)
48
- intent.error = update.error;
49
- if (update.status === 'confirmed' || update.status === 'failed') {
50
- intent.resolvedAt = new Date().toISOString();
51
- }
52
- this.appendLine(intent);
53
- }
54
- /** Get all unresolved intents (pending or submitted). */
55
- getUnresolved() {
56
- return Array.from(this.intents.values()).filter(i => i.status === 'pending' || i.status === 'submitted');
57
- }
58
- /** Get intent by clientOrderId. */
59
- getIntent(clientOrderId) {
60
- return this.intents.get(clientOrderId);
61
- }
62
- /** Get the journal file path. */
63
- getFilePath() {
64
- return this.filePath;
65
- }
66
- // ---- Internal ----
67
- /** Load existing intents from JSONL file. Later entries override earlier ones (last-write-wins). */
68
- loadExisting() {
69
- if (!existsSync(this.filePath))
70
- return;
71
- try {
72
- const content = readFileSync(this.filePath, 'utf-8');
73
- const lines = content.split('\n').filter(l => l.trim());
74
- for (const line of lines) {
75
- try {
76
- const intent = JSON.parse(line);
77
- if (intent.clientOrderId) {
78
- this.intents.set(intent.clientOrderId, intent);
79
- }
80
- }
81
- catch {
82
- // Skip malformed lines
83
- }
84
- }
85
- const unresolved = this.getUnresolved();
86
- if (unresolved.length > 0) {
87
- logger.warn(TAG, `Loaded ${this.intents.size} intents, ${unresolved.length} unresolved`);
88
- }
89
- else {
90
- logger.info(TAG, `Loaded ${this.intents.size} intents, all resolved`);
91
- }
92
- }
93
- catch (err) {
94
- logger.error(TAG, `Failed to load intent journal: ${formatError(err)}`);
95
- }
96
- }
97
- /** Append a line to the JSONL file. */
98
- appendLine(intent) {
99
- try {
100
- appendFileSync(this.filePath, JSON.stringify(intent) + '\n');
101
- }
102
- catch (err) {
103
- logger.error(TAG, `Failed to write intent: ${formatError(err)}`);
104
- }
105
- }
106
- /**
107
- * Compact the journal — rewrite with only the latest state of each intent.
108
- * Call periodically (e.g., daily) to prevent unbounded file growth.
109
- */
110
- compact() {
111
- try {
112
- const lines = Array.from(this.intents.values())
113
- .map(i => JSON.stringify(i))
114
- .join('\n') + '\n';
115
- writeFileSync(this.filePath, lines);
116
- logger.info(TAG, `Compacted journal: ${this.intents.size} intents`);
117
- }
118
- catch (err) {
119
- logger.error(TAG, `Failed to compact journal: ${formatError(err)}`);
120
- }
121
- }
122
- }
@@ -1,70 +0,0 @@
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
- }