@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,102 +0,0 @@
1
- /** Role of a clientOrderId within a bracket. */
2
- export type BracketRole = 'entry' | 'stop' | 'target';
3
- /** Short tag stored inside clientOrderId suffix. */
4
- export type BracketRoleTag = 'e' | 's' | 't';
5
- /** Immutable opaque identifier tying entry + SL + TP together. */
6
- export type BracketId = string;
7
- /** Lifecycle state of a bracket attached to an open position. */
8
- export type BracketState = 'pending_entry' | 'attaching' | 'active' | 'partial' | 'triggered_sl' | 'triggered_tp' | 'cancelled' | 'failed';
9
- /** Operator-provided bracket parameters for a new entry. */
10
- export interface BracketRequest {
11
- symbol: string;
12
- side: 'buy' | 'sell';
13
- stopPrice?: number;
14
- targetPrice?: number;
15
- }
16
- /** A single ledger entry representing one bracket. Authoritative on disk;
17
- * mirrored to intelligence DB for durability. */
18
- export interface BracketLedgerEntry {
19
- bracketId: BracketId;
20
- symbol: string;
21
- entrySide: 'buy' | 'sell';
22
- entryCid: string;
23
- slCid?: string;
24
- tpCid?: string;
25
- stopPrice?: number;
26
- targetPrice?: number;
27
- /** Filled entry quantity the bracket legs were sized to (reduceOnly +
28
- * explicit amount, NOT closePosition). modifyStop/modifyTarget MUST reuse
29
- * this — rebuilding a leg with a placeholder size silently under-protects
30
- * the position to that size. Set at attach time. */
31
- qty?: number;
32
- state: BracketState;
33
- attachStartedAt?: string;
34
- attachCompletedAt?: string;
35
- attachLatencyMs?: number;
36
- closedAt?: string;
37
- closeReason?: 'triggered_sl' | 'triggered_tp' | 'cancelled_manual' | 'cancelled_auto' | 'attach_failed';
38
- lastError?: string;
39
- createdAt: string;
40
- updatedAt: string;
41
- }
42
- /** Event emitted by BracketManager for telemetry + logging. */
43
- export type BracketEvent = {
44
- type: 'bracket.entry_submitted';
45
- bracketId: BracketId;
46
- symbol: string;
47
- ts: string;
48
- } | {
49
- type: 'bracket.entry_filled';
50
- bracketId: BracketId;
51
- symbol: string;
52
- ts: string;
53
- } | {
54
- type: 'bracket.attached';
55
- bracketId: BracketId;
56
- symbol: string;
57
- latencyMs: number;
58
- ts: string;
59
- } | {
60
- type: 'bracket.attach_failed';
61
- bracketId: BracketId;
62
- symbol: string;
63
- error: string;
64
- retryCount: number;
65
- ts: string;
66
- } | {
67
- type: 'bracket.sla_breach';
68
- bracketId: BracketId;
69
- symbol: string;
70
- latencyMs: number;
71
- ts: string;
72
- } | {
73
- type: 'bracket.triggered';
74
- bracketId: BracketId;
75
- symbol: string;
76
- side: 'sl' | 'tp';
77
- ts: string;
78
- } | {
79
- type: 'bracket.cancelled';
80
- bracketId: BracketId;
81
- symbol: string;
82
- reason: string;
83
- ts: string;
84
- } | {
85
- type: 'bracket.orphan_detected';
86
- bracketId: BracketId;
87
- symbol: string;
88
- ts: string;
89
- } | {
90
- type: 'bracket.orphan_cancelled';
91
- bracketId: BracketId;
92
- symbol: string;
93
- ts: string;
94
- } | {
95
- type: 'bracket.modified';
96
- bracketId: BracketId;
97
- symbol: string;
98
- field: 'stop' | 'target';
99
- oldValue: number;
100
- newValue: number;
101
- ts: string;
102
- };
@@ -1,8 +0,0 @@
1
- // Bracket order types — shared across BracketManager, BracketLedger,
2
- // BracketReconciler, and the telemetry pusher.
3
- //
4
- // A "bracket" is the pair of exchange-side protective orders attached to a
5
- // live position: a STOP_MARKET (stop-loss) and a TAKE_PROFIT_MARKET
6
- // (take-profit), both reduceOnly + closePosition. One entry → one bracketId
7
- // → three clientOrderIds (entry/stop/target).
8
- export {};
@@ -1,62 +0,0 @@
1
- import type { BinancePrivateApi } from '../ccxt/binance-private.js';
2
- interface TransferFetcher {
3
- fetchTransfers(startMs: number, endMs: number): Promise<Array<{
4
- tranId: string;
5
- time: number;
6
- amount: number;
7
- asset: string;
8
- }>>;
9
- }
10
- export interface DepositTrackerOptions {
11
- /** Earliest transfer time to consider (ms). Defaults to `Date.now()`. */
12
- sessionStartMs?: number;
13
- /** Minimum gap between polls (ms). Transfers (deposits/withdrawals/spot↔
14
- * futures moves) are RARE and only affect the cosmetic Day-P&L anchor —
15
- * never a safety path. `fetchTransfers` is 30 Binance weight; at the old
16
- * 30s default that was ~60 weight/min PERMANENT on an IP budget already
17
- * pinned at the pacer ceiling 24/7 (2026-05-16 RCA). 5 min cuts it to
18
- * ~6 weight/min; the only cost is a capital flow taking ≤5 min to be
19
- * subtracted from Day P&L. Default: 5 min. */
20
- minPollIntervalMs?: number;
21
- /** Currencies to sum as quote (1:1 with USD assumed). Anything else is
22
- * logged and ignored. */
23
- quoteCurrencies?: readonly string[];
24
- /** Injectable clock for tests. */
25
- now?: () => number;
26
- }
27
- export declare class DepositTracker {
28
- private api;
29
- private seenTranIds;
30
- /** Last SUCCESSFUL poll — anchors the fetch window so transfers that land
31
- * between a success and a run of failures are still covered by the next
32
- * successful poll. */
33
- private lastPollMs;
34
- /** Last poll ATTEMPT (success or failure) — drives the throttle. Advancing
35
- * this on failure too is what stops a sustained income-endpoint outage
36
- * from retrying the 30-weight call on every balance cycle (~seconds
37
- * apart) instead of once per minPollIntervalMs. */
38
- private lastAttemptMs;
39
- private sessionStartMs;
40
- private netSinceSessionStart;
41
- private readonly minPollIntervalMs;
42
- private readonly quoteCurrencies;
43
- private readonly now;
44
- constructor(api: TransferFetcher | BinancePrivateApi, opts?: DepositTrackerOptions);
45
- /** Reset the tracker — used when the agent re-anchors the session NAV for
46
- * any reason (date rollover, operator-triggered reset). */
47
- reset(sessionStartMs?: number): void;
48
- getSessionStartMs(): number;
49
- /** Net quote-currency transfers into (positive) or out of (negative) the
50
- * futures wallet since the tracker was armed. */
51
- getNetTransfers(): number;
52
- /**
53
- * Check the exchange for new transfers. Returns the delta (signed) that
54
- * happened since the last poll — callers should add this to their session
55
- * NAV anchor so the new wallet level doesn't register as trading P&L.
56
- *
57
- * The fetch is throttled by `minPollIntervalMs`; rapid calls return 0 without
58
- * hitting the API.
59
- */
60
- refresh(): Promise<number>;
61
- }
62
- export {};
@@ -1,97 +0,0 @@
1
- // DepositTracker — detects wallet-transfer deltas (spot↔futures moves,
2
- // deposits, withdrawals) and feeds them to the enricher so capital flows
3
- // are subtracted from Day P&L instead of being mistaken for trading gains.
4
- import { logger } from '../logger.js';
5
- const TAG = 'deposit-tracker';
6
- export class DepositTracker {
7
- api;
8
- seenTranIds = new Set();
9
- /** Last SUCCESSFUL poll — anchors the fetch window so transfers that land
10
- * between a success and a run of failures are still covered by the next
11
- * successful poll. */
12
- lastPollMs;
13
- /** Last poll ATTEMPT (success or failure) — drives the throttle. Advancing
14
- * this on failure too is what stops a sustained income-endpoint outage
15
- * from retrying the 30-weight call on every balance cycle (~seconds
16
- * apart) instead of once per minPollIntervalMs. */
17
- lastAttemptMs;
18
- sessionStartMs;
19
- netSinceSessionStart = 0;
20
- minPollIntervalMs;
21
- quoteCurrencies;
22
- now;
23
- constructor(api, opts = {}) {
24
- this.api = api;
25
- this.now = opts.now ?? (() => Date.now());
26
- this.sessionStartMs = opts.sessionStartMs ?? this.now();
27
- this.lastPollMs = this.sessionStartMs;
28
- this.lastAttemptMs = this.sessionStartMs;
29
- this.minPollIntervalMs = opts.minPollIntervalMs ?? 300_000;
30
- this.quoteCurrencies = opts.quoteCurrencies ?? ['USDT', 'USDC'];
31
- }
32
- /** Reset the tracker — used when the agent re-anchors the session NAV for
33
- * any reason (date rollover, operator-triggered reset). */
34
- reset(sessionStartMs) {
35
- this.seenTranIds.clear();
36
- this.sessionStartMs = sessionStartMs ?? this.now();
37
- this.lastPollMs = this.sessionStartMs;
38
- this.lastAttemptMs = this.sessionStartMs;
39
- this.netSinceSessionStart = 0;
40
- }
41
- getSessionStartMs() {
42
- return this.sessionStartMs;
43
- }
44
- /** Net quote-currency transfers into (positive) or out of (negative) the
45
- * futures wallet since the tracker was armed. */
46
- getNetTransfers() {
47
- return this.netSinceSessionStart;
48
- }
49
- /**
50
- * Check the exchange for new transfers. Returns the delta (signed) that
51
- * happened since the last poll — callers should add this to their session
52
- * NAV anchor so the new wallet level doesn't register as trading P&L.
53
- *
54
- * The fetch is throttled by `minPollIntervalMs`; rapid calls return 0 without
55
- * hitting the API.
56
- */
57
- async refresh() {
58
- const now = this.now();
59
- // Throttle on the last ATTEMPT (not the last success) — otherwise a
60
- // sustained fetch failure bypasses the throttle entirely and every
61
- // balance cycle re-fires the 30-weight income call into the outage.
62
- if (now - this.lastAttemptMs < this.minPollIntervalMs)
63
- return 0;
64
- this.lastAttemptMs = now;
65
- // A small lookback overlap guards against clock skew between our host and
66
- // Binance's edge — duplicate entries get filtered via seenTranIds. The
67
- // window anchors on the last SUCCESS so transfers that landed during a
68
- // run of failed polls are still picked up.
69
- const start = Math.max(this.sessionStartMs, this.lastPollMs - 5_000);
70
- let entries;
71
- try {
72
- entries = await this.api.fetchTransfers(start, now);
73
- }
74
- catch (err) {
75
- logger.warn(TAG, `Transfer poll failed: ${err instanceof Error ? err.message : String(err)}`);
76
- return 0;
77
- }
78
- this.lastPollMs = now;
79
- let delta = 0;
80
- for (const e of entries) {
81
- if (!e.tranId || this.seenTranIds.has(e.tranId))
82
- continue;
83
- this.seenTranIds.add(e.tranId);
84
- if (this.quoteCurrencies.includes(e.asset)) {
85
- delta += e.amount;
86
- }
87
- else if (e.amount !== 0) {
88
- logger.warn(TAG, `Non-quote transfer ignored: ${e.amount} ${e.asset} (tranId=${e.tranId})`);
89
- }
90
- }
91
- if (delta !== 0) {
92
- this.netSinceSessionStart += delta;
93
- logger.info(TAG, `Capital flow detected: ${delta > 0 ? '+' : ''}${delta.toFixed(4)} (session total: ${this.netSinceSessionStart.toFixed(4)})`);
94
- }
95
- return delta;
96
- }
97
- }
@@ -1,32 +0,0 @@
1
- import { EventEmitter } from 'node:events';
2
- import type { IExchangeAdapter } from '../exchange-adapter.js';
3
- export interface EmergencyStep {
4
- description: string;
5
- status: 'pending' | 'done' | 'failed';
6
- error?: string;
7
- }
8
- export interface EmergencyProgress {
9
- action: 'kill' | 'flatten';
10
- status: 'in_progress' | 'completed' | 'failed' | 'partial';
11
- steps: EmergencyStep[];
12
- startedAt: string;
13
- completedAt?: string;
14
- }
15
- export declare class EmergencyControls extends EventEmitter {
16
- private adapter;
17
- private isHedgeMode;
18
- constructor(adapter: IExchangeAdapter, isHedgeMode?: boolean);
19
- /**
20
- * Kill switch: cancel all open orders on exchange.
21
- * Retries up to 3 times on transient failure.
22
- */
23
- kill(): Promise<EmergencyProgress>;
24
- /**
25
- * Flatten: close all positions at market.
26
- * Loop-verifies: re-fetches positions after close, retries remainder.
27
- * Uses reduceOnly to prevent accidental position reversal.
28
- */
29
- flatten(): Promise<EmergencyProgress>;
30
- private closePositionWithRetry;
31
- private emitProgress;
32
- }
@@ -1,226 +0,0 @@
1
- // Emergency controls for live trading — kill switch and flatten with retry logic.
2
- // These NEVER have a readiness gate — they must work in ALL adapter states.
3
- import { EventEmitter } from 'node:events';
4
- import { logger, formatError } from '../logger.js';
5
- const TAG = 'emergency';
6
- const MAX_RETRIES = 3;
7
- const RETRY_DELAY_MS = 1_000;
8
- const MAX_FLATTEN_ATTEMPTS = 3;
9
- export class EmergencyControls extends EventEmitter {
10
- adapter;
11
- isHedgeMode;
12
- constructor(adapter, isHedgeMode = false) {
13
- super();
14
- this.adapter = adapter;
15
- this.isHedgeMode = isHedgeMode;
16
- }
17
- /**
18
- * Kill switch: cancel all open orders on exchange.
19
- * Retries up to 3 times on transient failure.
20
- */
21
- async kill() {
22
- const progress = {
23
- action: 'kill',
24
- status: 'in_progress',
25
- steps: [],
26
- startedAt: new Date().toISOString(),
27
- };
28
- this.emitProgress(progress);
29
- logger.warn(TAG, '🔴 KILL SWITCH ACTIVATED');
30
- try {
31
- // Fetch current open orders
32
- const openOrders = await this.adapter.getOpenOrders();
33
- if (openOrders.length === 0) {
34
- progress.steps.push({ description: 'No open orders to cancel', status: 'done' });
35
- progress.status = 'completed';
36
- progress.completedAt = new Date().toISOString();
37
- this.emitProgress(progress);
38
- logger.info(TAG, 'Kill: no open orders');
39
- return progress;
40
- }
41
- progress.steps.push({ description: `Cancelling ${openOrders.length} orders...`, status: 'pending' });
42
- this.emitProgress(progress);
43
- // Cancel all with retry
44
- let success = false;
45
- for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
46
- try {
47
- await this.adapter.cancelAllOrders();
48
- success = true;
49
- break;
50
- }
51
- catch (err) {
52
- logger.warn(TAG, `Kill attempt ${attempt}/${MAX_RETRIES} failed: ${formatError(err)}`);
53
- if (attempt < MAX_RETRIES) {
54
- await sleep(RETRY_DELAY_MS);
55
- }
56
- }
57
- }
58
- if (success) {
59
- progress.steps[progress.steps.length - 1].status = 'done';
60
- progress.steps[progress.steps.length - 1].description = `${openOrders.length} orders cancelled`;
61
- progress.status = 'completed';
62
- }
63
- else {
64
- progress.steps[progress.steps.length - 1].status = 'failed';
65
- progress.steps[progress.steps.length - 1].error = 'Failed after 3 retries';
66
- progress.steps.push({
67
- description: 'MANUAL INTERVENTION REQUIRED — cancel orders manually on Binance',
68
- status: 'failed',
69
- });
70
- progress.status = 'failed';
71
- }
72
- progress.completedAt = new Date().toISOString();
73
- this.emitProgress(progress);
74
- return progress;
75
- }
76
- catch (err) {
77
- logger.error(TAG, `Kill switch error: ${formatError(err)}`);
78
- progress.status = 'failed';
79
- progress.steps.push({
80
- description: `MANUAL INTERVENTION REQUIRED: ${formatError(err)}`,
81
- status: 'failed',
82
- error: formatError(err),
83
- });
84
- progress.completedAt = new Date().toISOString();
85
- this.emitProgress(progress);
86
- return progress;
87
- }
88
- }
89
- /**
90
- * Flatten: close all positions at market.
91
- * Loop-verifies: re-fetches positions after close, retries remainder.
92
- * Uses reduceOnly to prevent accidental position reversal.
93
- */
94
- async flatten() {
95
- const progress = {
96
- action: 'flatten',
97
- status: 'in_progress',
98
- steps: [],
99
- startedAt: new Date().toISOString(),
100
- };
101
- this.emitProgress(progress);
102
- logger.warn(TAG, '🟠 FLATTEN ALL ACTIVATED');
103
- try {
104
- for (let attempt = 1; attempt <= MAX_FLATTEN_ATTEMPTS; attempt++) {
105
- // Fresh snapshot of positions from exchange. getPositionsOrNull()
106
- // returns null when the fetch FAILED (429 / weight-paced / transient)
107
- // — position state is UNKNOWN, NOT "flat". Treating a failed fetch as
108
- // "all closed" would make the single most safety-critical control
109
- // report a green "Flatten complete" to the operator mid-crisis while
110
- // positions are still live on Binance. Never declare success on null;
111
- // skip this attempt's close work and retry (final verification below
112
- // delivers an honest partial/MANUAL-INTERVENTION verdict if it
113
- // persists). Same null≠empty contract as closePosition/reconciler.
114
- const positions = await this.adapter.getPositionsOrNull();
115
- if (positions === null) {
116
- logger.warn(TAG, `Flatten attempt ${attempt}/${MAX_FLATTEN_ATTEMPTS}: position fetch failed (exchange data unavailable) — cannot confirm flat, retrying`);
117
- continue;
118
- }
119
- if (positions.length === 0) {
120
- progress.steps.push({ description: 'All positions closed', status: 'done' });
121
- progress.status = 'completed';
122
- progress.completedAt = new Date().toISOString();
123
- this.emitProgress(progress);
124
- logger.info(TAG, 'Flatten complete — no positions remaining');
125
- return progress;
126
- }
127
- if (attempt > 1) {
128
- logger.warn(TAG, `Flatten retry ${attempt}/${MAX_FLATTEN_ATTEMPTS}: ${positions.length} positions still open`);
129
- }
130
- // Close each position
131
- for (const position of positions) {
132
- const step = {
133
- description: `Closing ${position.symbol} ${position.side} ${position.contracts}`,
134
- status: 'pending',
135
- };
136
- progress.steps.push(step);
137
- this.emitProgress(progress);
138
- try {
139
- await this.closePositionWithRetry(position);
140
- step.status = 'done';
141
- step.description = `Closed ${position.symbol} ${position.side} ${position.contracts}`;
142
- }
143
- catch (err) {
144
- step.status = 'failed';
145
- step.error = formatError(err);
146
- logger.error(TAG, `Failed to close ${position.symbol}: ${formatError(err)}`);
147
- }
148
- this.emitProgress(progress);
149
- }
150
- }
151
- // Final verification. A null here means we exhausted all attempts
152
- // without ever getting a trustworthy snapshot — we CANNOT confirm the
153
- // account is flat, so we must NOT report `completed`. Surface it as
154
- // partial + MANUAL INTERVENTION (operator must check Binance directly)
155
- // rather than the false-green that motivated this fix.
156
- const remaining = await this.adapter.getPositionsOrNull();
157
- if (remaining === null) {
158
- progress.status = 'partial';
159
- progress.steps.push({
160
- description: 'MANUAL INTERVENTION REQUIRED — could not verify positions are closed (exchange data unavailable); check Binance directly',
161
- status: 'failed',
162
- });
163
- logger.error(TAG, 'Flatten verification failed: position fetch unavailable — flat state UNCONFIRMED');
164
- }
165
- else if (remaining.length > 0) {
166
- progress.status = 'partial';
167
- progress.steps.push({
168
- description: `MANUAL INTERVENTION REQUIRED — ${remaining.length} positions still open on Binance`,
169
- status: 'failed',
170
- });
171
- logger.error(TAG, `Flatten incomplete: ${remaining.length} positions remain`);
172
- }
173
- else {
174
- progress.status = 'completed';
175
- }
176
- progress.completedAt = new Date().toISOString();
177
- this.emitProgress(progress);
178
- return progress;
179
- }
180
- catch (err) {
181
- logger.error(TAG, `Flatten error: ${formatError(err)}`);
182
- progress.status = 'failed';
183
- progress.steps.push({
184
- description: `MANUAL INTERVENTION REQUIRED: ${formatError(err)}`,
185
- status: 'failed',
186
- error: formatError(err),
187
- });
188
- progress.completedAt = new Date().toISOString();
189
- this.emitProgress(progress);
190
- return progress;
191
- }
192
- }
193
- // ---- Internal ----
194
- async closePositionWithRetry(position) {
195
- const closeSide = position.side === 'long' ? 'sell' : 'buy';
196
- const options = { emergency: true };
197
- if (this.isHedgeMode) {
198
- options.positionSide = position.side === 'long' ? 'LONG' : 'SHORT';
199
- }
200
- else {
201
- options.reduceOnly = true;
202
- }
203
- for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
204
- try {
205
- return await this.adapter.createOrder(position.symbol, closeSide, 'market', position.contracts, undefined, undefined, options);
206
- }
207
- catch (err) {
208
- logger.warn(TAG, `Close ${position.symbol} attempt ${attempt}/${MAX_RETRIES}: ${formatError(err)}`);
209
- if (attempt < MAX_RETRIES) {
210
- await sleep(RETRY_DELAY_MS);
211
- }
212
- else {
213
- throw err;
214
- }
215
- }
216
- }
217
- // TypeScript: unreachable, but satisfies return type
218
- throw new Error(`Failed to close ${position.symbol} after ${MAX_RETRIES} attempts`);
219
- }
220
- emitProgress(progress) {
221
- this.emit('progress', progress);
222
- }
223
- }
224
- function sleep(ms) {
225
- return new Promise(resolve => setTimeout(resolve, ms));
226
- }
@@ -1,12 +0,0 @@
1
- export type ErrorAction = 'report' | 'wait_and_retry' | 'check_and_retry' | 'fix_precision' | 'sync_time';
2
- export interface ParsedExchangeError {
3
- code: number | null;
4
- message: string;
5
- action: ErrorAction;
6
- retryAfterMs: number;
7
- isRetryable: boolean;
8
- isNetworkError: boolean;
9
- humanMessage: string;
10
- }
11
- /** Parse a CCXT/Binance error into a structured response. */
12
- export declare function parseExchangeError(err: unknown): ParsedExchangeError;
@@ -1,130 +0,0 @@
1
- // Exchange error handler — maps Binance error codes to human-readable messages
2
- // and determines appropriate recovery action.
3
- import { logger } from '../logger.js';
4
- const TAG = 'exchange-error';
5
- /** Known Binance Futures error codes and their human-readable meanings. */
6
- const BINANCE_ERRORS = {
7
- // Order errors
8
- [-2019]: { message: 'Insufficient margin', action: 'report' },
9
- [-1111]: { message: 'Precision error (lot size or tick size mismatch)', action: 'fix_precision' },
10
- [-4131]: { message: 'Order below minimum notional value', action: 'report' },
11
- [-1015]: { message: 'Too many orders — exchange rate limit hit', action: 'wait_and_retry' },
12
- [-2022]: { message: 'Stop price invalid (must be above/below current price depending on side)', action: 'report' },
13
- [-1021]: { message: 'Timestamp sync error — clock drift', action: 'sync_time' },
14
- [-1003]: { message: 'IP rate limit exceeded', action: 'wait_and_retry' },
15
- [-1010]: { message: 'Order not found', action: 'report' },
16
- [-2021]: { message: 'Order would immediately trigger', action: 'report' },
17
- [-4164]: { message: 'Order price exceeds MAX_PRICE filter', action: 'report' },
18
- [-4165]: { message: 'Order price below MIN_PRICE filter', action: 'report' },
19
- [-4028]: { message: 'Reduce only rejected — no open position', action: 'report' },
20
- [-4005]: { message: 'Order quantity too small', action: 'report' },
21
- [-4003]: { message: 'Order quantity exceeds MAX_QTY', action: 'report' },
22
- [-4014]: { message: 'Too many open orders', action: 'report' },
23
- // System errors
24
- [-1000]: { message: 'Unknown exchange error', action: 'report' },
25
- [-1001]: { message: 'Exchange internal error — try again later', action: 'wait_and_retry' },
26
- [-1002]: { message: 'Unauthorized — API key invalid or insufficient permissions', action: 'report' },
27
- [-1006]: { message: 'Unexpected response from exchange', action: 'wait_and_retry' },
28
- [-1007]: { message: 'Exchange request timeout', action: 'check_and_retry' },
29
- [-1014]: { message: 'Unsupported order combination', action: 'report' },
30
- [-1016]: { message: 'Service shutting down', action: 'report' },
31
- [-1020]: { message: 'Unsupported operation', action: 'report' },
32
- };
33
- /** Parse a CCXT/Binance error into a structured response. */
34
- export function parseExchangeError(err) {
35
- const error = err;
36
- // Extract error code (CCXT wraps Binance errors)
37
- let code = null;
38
- let rawMessage = '';
39
- if (typeof error === 'object' && error !== null) {
40
- // CCXT errors often have a message like "binance {...}" or structured fields
41
- rawMessage = String(error.message ?? error);
42
- // Try to extract Binance error code from message
43
- const codeMatch = rawMessage.match(/"code"\s*:\s*(-?\d+)/);
44
- if (codeMatch) {
45
- code = parseInt(codeMatch[1], 10);
46
- }
47
- // Also check if CCXT provides it directly
48
- if (typeof error.code === 'number') {
49
- code = error.code;
50
- }
51
- }
52
- else {
53
- rawMessage = String(err);
54
- }
55
- // Check for network errors
56
- const isNetworkError = isNetworkRelated(rawMessage);
57
- if (isNetworkError) {
58
- return {
59
- code: null,
60
- message: rawMessage,
61
- action: 'check_and_retry',
62
- retryAfterMs: 1000,
63
- isRetryable: true,
64
- isNetworkError: true,
65
- humanMessage: 'Network error communicating with exchange. Checking if order went through...',
66
- };
67
- }
68
- // Look up known error code
69
- if (code !== null && BINANCE_ERRORS[code]) {
70
- const known = BINANCE_ERRORS[code];
71
- const retryAfterMs = known.action === 'wait_and_retry' ? (code === -1015 || code === -1003 ? 60_000 : 5_000) : 0;
72
- return {
73
- code,
74
- message: rawMessage,
75
- action: known.action,
76
- retryAfterMs,
77
- isRetryable: known.action !== 'report',
78
- isNetworkError: false,
79
- humanMessage: buildHumanMessage(code, known.message, rawMessage),
80
- };
81
- }
82
- // Unknown error
83
- logger.warn(TAG, `Unknown exchange error (code=${code}): ${rawMessage}`);
84
- return {
85
- code,
86
- message: rawMessage,
87
- action: 'report',
88
- retryAfterMs: 0,
89
- isRetryable: false,
90
- isNetworkError: false,
91
- humanMessage: `Exchange error: ${rawMessage}`,
92
- };
93
- }
94
- /** Check if an error is network-related (timeout, connection reset, etc.). */
95
- function isNetworkRelated(message) {
96
- const patterns = [
97
- 'ETIMEDOUT', 'ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND',
98
- 'network', 'timeout', 'socket hang up', 'EPIPE',
99
- 'EAI_AGAIN', 'EHOSTUNREACH', 'fetch failed',
100
- ];
101
- const lower = message.toLowerCase();
102
- return patterns.some(p => lower.includes(p.toLowerCase()));
103
- }
104
- /** Build a human-friendly error message. */
105
- function buildHumanMessage(code, knownMessage, rawMessage) {
106
- switch (code) {
107
- case -2019: {
108
- // Try to extract balance info from raw message
109
- const match = rawMessage.match(/(\d+\.?\d*)\s*USDT/);
110
- if (match)
111
- return `Insufficient margin: available ${match[1]} USDT`;
112
- return 'Insufficient margin — check your balance';
113
- }
114
- case -4131:
115
- return `Order too small: below this symbol's minimum notional value. Check exchange info for the exact minimum.`;
116
- case -1111:
117
- return `Precision error: amount or price has too many decimal places. Order will be auto-corrected on retry.`;
118
- case -1015:
119
- case -1003:
120
- return `Exchange rate limit hit. Wait 60 seconds before retrying.`;
121
- case -2022:
122
- return `Invalid stop price. For buy stops: stop must be above current price. For sell stops: stop must be below.`;
123
- case -1021:
124
- return `Clock out of sync with exchange. Syncing time automatically...`;
125
- case -4028:
126
- return `Cannot reduce position — no open position found. The position may have already been closed.`;
127
- default:
128
- return `Exchange error ${code}: ${knownMessage}`;
129
- }
130
- }