@reefclaw/connect 0.1.11 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (397) hide show
  1. package/assets/bridge/gateway/heartbeat-cron.d.ts +27 -0
  2. package/assets/bridge/gateway/heartbeat-cron.js +85 -0
  3. package/assets/bridge/providers/gateway.d.ts +2 -0
  4. package/assets/bridge/providers/gateway.js +57 -16
  5. package/assets/bridge/setup.js +6 -51
  6. package/dist/deps.js +2 -2
  7. package/dist/plugin.js +35 -7
  8. package/package.json +1 -1
  9. package/assets/plugin/audit/mode-transition-audit.d.ts +0 -11
  10. package/assets/plugin/audit/mode-transition-audit.js +0 -29
  11. package/assets/plugin/balance-utils.d.ts +0 -36
  12. package/assets/plugin/balance-utils.js +0 -98
  13. package/assets/plugin/ccxt/binance-ban-gate.d.ts +0 -47
  14. package/assets/plugin/ccxt/binance-ban-gate.js +0 -420
  15. package/assets/plugin/ccxt/binance-private.d.ts +0 -346
  16. package/assets/plugin/ccxt/binance-private.js +0 -1525
  17. package/assets/plugin/ccxt/binance-public.d.ts +0 -34
  18. package/assets/plugin/ccxt/binance-public.js +0 -180
  19. package/assets/plugin/ccxt/intel-public.d.ts +0 -25
  20. package/assets/plugin/ccxt/intel-public.js +0 -80
  21. package/assets/plugin/ccxt/public-market-data-api.d.ts +0 -26
  22. package/assets/plugin/ccxt/public-market-data-api.js +0 -23
  23. package/assets/plugin/config/agent-config-client.d.ts +0 -77
  24. package/assets/plugin/config/agent-config-client.js +0 -188
  25. package/assets/plugin/config/agent-config-poller.d.ts +0 -32
  26. package/assets/plugin/config/agent-config-poller.js +0 -101
  27. package/assets/plugin/config/brackets-config.d.ts +0 -22
  28. package/assets/plugin/config/brackets-config.js +0 -58
  29. package/assets/plugin/config/entitlement-gate.d.ts +0 -51
  30. package/assets/plugin/config/entitlement-gate.js +0 -137
  31. package/assets/plugin/config/gate-store.d.ts +0 -18
  32. package/assets/plugin/config/gate-store.js +0 -61
  33. package/assets/plugin/config/plugin-config-io.d.ts +0 -222
  34. package/assets/plugin/config/plugin-config-io.js +0 -126
  35. package/assets/plugin/config/position-review-config.d.ts +0 -35
  36. package/assets/plugin/config/position-review-config.js +0 -105
  37. package/assets/plugin/config/tool-gate.d.ts +0 -53
  38. package/assets/plugin/config/tool-gate.js +0 -128
  39. package/assets/plugin/config/user-data-stream-config.d.ts +0 -89
  40. package/assets/plugin/config/user-data-stream-config.js +0 -239
  41. package/assets/plugin/connector-supervisor.d.ts +0 -36
  42. package/assets/plugin/connector-supervisor.js +0 -149
  43. package/assets/plugin/exchange-adapter.d.ts +0 -65
  44. package/assets/plugin/exchange-adapter.js +0 -4
  45. package/assets/plugin/index.d.ts +0 -30
  46. package/assets/plugin/index.js +0 -2756
  47. package/assets/plugin/ingest/pending-entry-metadata.d.ts +0 -74
  48. package/assets/plugin/ingest/pending-entry-metadata.js +0 -236
  49. package/assets/plugin/ingest/position-auto-capture.d.ts +0 -171
  50. package/assets/plugin/ingest/position-auto-capture.js +0 -709
  51. package/assets/plugin/ingest/position-decisions-client.d.ts +0 -327
  52. package/assets/plugin/ingest/position-decisions-client.js +0 -306
  53. package/assets/plugin/ingest/readiness-reporter.d.ts +0 -42
  54. package/assets/plugin/ingest/readiness-reporter.js +0 -163
  55. package/assets/plugin/ingest/reconcile-db-vs-exchange.d.ts +0 -51
  56. package/assets/plugin/ingest/reconcile-db-vs-exchange.js +0 -170
  57. package/assets/plugin/ingest/reconciler-cleanup.d.ts +0 -37
  58. package/assets/plugin/ingest/reconciler-cleanup.js +0 -147
  59. package/assets/plugin/ingest/rest-gap-filler.d.ts +0 -191
  60. package/assets/plugin/ingest/rest-gap-filler.js +0 -565
  61. package/assets/plugin/ingest/touched-symbols-store.d.ts +0 -25
  62. package/assets/plugin/ingest/touched-symbols-store.js +0 -96
  63. package/assets/plugin/ingest/trade-store-client.d.ts +0 -40
  64. package/assets/plugin/ingest/trade-store-client.js +0 -125
  65. package/assets/plugin/ingest/ws-ingest.d.ts +0 -43
  66. package/assets/plugin/ingest/ws-ingest.js +0 -126
  67. package/assets/plugin/learning/setup-family.d.ts +0 -21
  68. package/assets/plugin/learning/setup-family.js +0 -103
  69. package/assets/plugin/lifecycle/install-signal-handlers.d.ts +0 -33
  70. package/assets/plugin/lifecycle/install-signal-handlers.js +0 -112
  71. package/assets/plugin/lifecycle/shutdown-coordinator.d.ts +0 -43
  72. package/assets/plugin/lifecycle/shutdown-coordinator.js +0 -131
  73. package/assets/plugin/lifecycle/trading-operation-lock.d.ts +0 -17
  74. package/assets/plugin/lifecycle/trading-operation-lock.js +0 -14
  75. package/assets/plugin/live/bracket-id.d.ts +0 -26
  76. package/assets/plugin/live/bracket-id.js +0 -112
  77. package/assets/plugin/live/bracket-ledger.d.ts +0 -54
  78. package/assets/plugin/live/bracket-ledger.js +0 -267
  79. package/assets/plugin/live/bracket-manager.d.ts +0 -82
  80. package/assets/plugin/live/bracket-manager.js +0 -478
  81. package/assets/plugin/live/bracket-params.d.ts +0 -22
  82. package/assets/plugin/live/bracket-params.js +0 -124
  83. package/assets/plugin/live/bracket-reconciler.d.ts +0 -95
  84. package/assets/plugin/live/bracket-reconciler.js +0 -573
  85. package/assets/plugin/live/bracket-types.d.ts +0 -102
  86. package/assets/plugin/live/bracket-types.js +0 -8
  87. package/assets/plugin/live/deposit-tracker.d.ts +0 -62
  88. package/assets/plugin/live/deposit-tracker.js +0 -97
  89. package/assets/plugin/live/emergency-controls.d.ts +0 -32
  90. package/assets/plugin/live/emergency-controls.js +0 -226
  91. package/assets/plugin/live/exchange-errors.d.ts +0 -12
  92. package/assets/plugin/live/exchange-errors.js +0 -130
  93. package/assets/plugin/live/exchange-info-cache.d.ts +0 -37
  94. package/assets/plugin/live/exchange-info-cache.js +0 -134
  95. package/assets/plugin/live/fact-subscriber.d.ts +0 -78
  96. package/assets/plugin/live/fact-subscriber.js +0 -182
  97. package/assets/plugin/live/fill-price.d.ts +0 -13
  98. package/assets/plugin/live/fill-price.js +0 -37
  99. package/assets/plugin/live/intent-journal.d.ts +0 -42
  100. package/assets/plugin/live/intent-journal.js +0 -122
  101. package/assets/plugin/live/listen-key-manager.d.ts +0 -70
  102. package/assets/plugin/live/listen-key-manager.js +0 -169
  103. package/assets/plugin/live/live-adapter.d.ts +0 -319
  104. package/assets/plugin/live/live-adapter.js +0 -1906
  105. package/assets/plugin/live/live-balance-enricher.d.ts +0 -32
  106. package/assets/plugin/live/live-balance-enricher.js +0 -104
  107. package/assets/plugin/live/live-bracket-api.d.ts +0 -13
  108. package/assets/plugin/live/live-bracket-api.js +0 -20
  109. package/assets/plugin/live/live-state-store.d.ts +0 -194
  110. package/assets/plugin/live/live-state-store.js +0 -450
  111. package/assets/plugin/live/local-signal-service.d.ts +0 -57
  112. package/assets/plugin/live/local-signal-service.js +0 -151
  113. package/assets/plugin/live/local-strategy-evaluator.d.ts +0 -62
  114. package/assets/plugin/live/local-strategy-evaluator.js +0 -131
  115. package/assets/plugin/live/microstructure-assembler.d.ts +0 -54
  116. package/assets/plugin/live/microstructure-assembler.js +0 -148
  117. package/assets/plugin/live/order-poller.d.ts +0 -29
  118. package/assets/plugin/live/order-poller.js +0 -125
  119. package/assets/plugin/live/position-state-store.d.ts +0 -87
  120. package/assets/plugin/live/position-state-store.js +0 -237
  121. package/assets/plugin/live/proposal-decision-listener.d.ts +0 -70
  122. package/assets/plugin/live/proposal-decision-listener.js +0 -292
  123. package/assets/plugin/live/proposal-manager.d.ts +0 -76
  124. package/assets/plugin/live/proposal-manager.js +0 -140
  125. package/assets/plugin/live/rate-limiter.d.ts +0 -47
  126. package/assets/plugin/live/rate-limiter.js +0 -159
  127. package/assets/plugin/live/reconciler.d.ts +0 -39
  128. package/assets/plugin/live/reconciler.js +0 -175
  129. package/assets/plugin/live/setup-buckets.d.ts +0 -7
  130. package/assets/plugin/live/setup-buckets.js +0 -33
  131. package/assets/plugin/live/slippage-tracker.d.ts +0 -45
  132. package/assets/plugin/live/slippage-tracker.js +0 -78
  133. package/assets/plugin/live/stop-watcher.d.ts +0 -67
  134. package/assets/plugin/live/stop-watcher.js +0 -218
  135. package/assets/plugin/live/user-data-active-probe.d.ts +0 -54
  136. package/assets/plugin/live/user-data-active-probe.js +0 -180
  137. package/assets/plugin/live/user-data-stream-controller.d.ts +0 -200
  138. package/assets/plugin/live/user-data-stream-controller.js +0 -579
  139. package/assets/plugin/live/user-data-stream-ws.d.ts +0 -22
  140. package/assets/plugin/live/user-data-stream-ws.js +0 -63
  141. package/assets/plugin/live/user-data-stream.d.ts +0 -243
  142. package/assets/plugin/live/user-data-stream.js +0 -704
  143. package/assets/plugin/logger.d.ts +0 -2
  144. package/assets/plugin/logger.js +0 -2
  145. package/assets/plugin/mfe.d.ts +0 -21
  146. package/assets/plugin/mfe.js +0 -68
  147. package/assets/plugin/onboarding/mode-ladder.d.ts +0 -1
  148. package/assets/plugin/onboarding/mode-ladder.js +0 -3
  149. package/assets/plugin/onboarding/runtime.d.ts +0 -90
  150. package/assets/plugin/onboarding/runtime.js +0 -184
  151. package/assets/plugin/openclaw.plugin.json +0 -92
  152. package/assets/plugin/paper-adapter.d.ts +0 -24
  153. package/assets/plugin/paper-adapter.js +0 -91
  154. package/assets/plugin/persistence/state-manager.d.ts +0 -66
  155. package/assets/plugin/persistence/state-manager.js +0 -222
  156. package/assets/plugin/pinned-plan.d.ts +0 -9
  157. package/assets/plugin/pinned-plan.js +0 -23
  158. package/assets/plugin/portfolio/reentry-tracker.d.ts +0 -36
  159. package/assets/plugin/portfolio/reentry-tracker.js +0 -127
  160. package/assets/plugin/portfolio/wave9-admission.d.ts +0 -67
  161. package/assets/plugin/portfolio/wave9-admission.js +0 -262
  162. package/assets/plugin/portfolio/wave9-policy.d.ts +0 -36
  163. package/assets/plugin/portfolio/wave9-policy.js +0 -183
  164. package/assets/plugin/risk/pre-trade-check.d.ts +0 -38
  165. package/assets/plugin/risk/pre-trade-check.js +0 -345
  166. package/assets/plugin/risk/pre-trade-types.d.ts +0 -60
  167. package/assets/plugin/risk/pre-trade-types.js +0 -3
  168. package/assets/plugin/shadow/shadow-tracker.d.ts +0 -36
  169. package/assets/plugin/shadow/shadow-tracker.js +0 -151
  170. package/assets/plugin/shadow/types.d.ts +0 -42
  171. package/assets/plugin/shadow/types.js +0 -20
  172. package/assets/plugin/shared/indicators-extended.d.ts +0 -52
  173. package/assets/plugin/shared/indicators-extended.js +0 -291
  174. package/assets/plugin/shared/indicators.d.ts +0 -15
  175. package/assets/plugin/shared/indicators.js +0 -114
  176. package/assets/plugin/signals/conditions/registry.d.ts +0 -16
  177. package/assets/plugin/signals/conditions/registry.js +0 -1333
  178. package/assets/plugin/signals/conditions/types.d.ts +0 -1
  179. package/assets/plugin/signals/conditions/types.js +0 -4
  180. package/assets/plugin/signals/direction-rules.d.ts +0 -3
  181. package/assets/plugin/signals/direction-rules.js +0 -24
  182. package/assets/plugin/signals/entry-rules.d.ts +0 -6
  183. package/assets/plugin/signals/entry-rules.js +0 -33
  184. package/assets/plugin/signals/serialize-context.d.ts +0 -4
  185. package/assets/plugin/signals/serialize-context.js +0 -39
  186. package/assets/plugin/signals/stop-rules.d.ts +0 -3
  187. package/assets/plugin/signals/stop-rules.js +0 -48
  188. package/assets/plugin/signals/strategy-adapter.d.ts +0 -47
  189. package/assets/plugin/signals/strategy-adapter.js +0 -209
  190. package/assets/plugin/signals/types.d.ts +0 -1
  191. package/assets/plugin/signals/types.js +0 -8
  192. package/assets/plugin/simulator/exchange-simulator.d.ts +0 -105
  193. package/assets/plugin/simulator/exchange-simulator.js +0 -759
  194. package/assets/plugin/simulator/fill-engine.d.ts +0 -53
  195. package/assets/plugin/simulator/fill-engine.js +0 -280
  196. package/assets/plugin/simulator/paper-market-feed.d.ts +0 -26
  197. package/assets/plugin/simulator/paper-market-feed.js +0 -104
  198. package/assets/plugin/simulator/realistic-fills.d.ts +0 -59
  199. package/assets/plugin/simulator/realistic-fills.js +0 -175
  200. package/assets/plugin/simulator/types.d.ts +0 -228
  201. package/assets/plugin/simulator/types.js +0 -43
  202. package/assets/plugin/strategy/builtin-strategies.d.ts +0 -2
  203. package/assets/plugin/strategy/builtin-strategies.js +0 -113
  204. package/assets/plugin/strategy/condition-registry.d.ts +0 -3
  205. package/assets/plugin/strategy/condition-registry.js +0 -153
  206. package/assets/plugin/strategy/evaluator.d.ts +0 -70
  207. package/assets/plugin/strategy/evaluator.js +0 -98
  208. package/assets/plugin/tools/assessment-validation.d.ts +0 -141
  209. package/assets/plugin/tools/assessment-validation.js +0 -473
  210. package/assets/plugin/tools/attach-brackets.d.ts +0 -39
  211. package/assets/plugin/tools/attach-brackets.js +0 -564
  212. package/assets/plugin/tools/audit-bracket-protection.d.ts +0 -49
  213. package/assets/plugin/tools/audit-bracket-protection.js +0 -683
  214. package/assets/plugin/tools/bracket-control.d.ts +0 -12
  215. package/assets/plugin/tools/bracket-control.js +0 -35
  216. package/assets/plugin/tools/cancel-all-orders.d.ts +0 -9
  217. package/assets/plugin/tools/cancel-all-orders.js +0 -8
  218. package/assets/plugin/tools/cancel-order.d.ts +0 -14
  219. package/assets/plugin/tools/cancel-order.js +0 -60
  220. package/assets/plugin/tools/check-position-health.d.ts +0 -46
  221. package/assets/plugin/tools/check-position-health.js +0 -194
  222. package/assets/plugin/tools/clear-exchange-credentials.d.ts +0 -24
  223. package/assets/plugin/tools/clear-exchange-credentials.js +0 -70
  224. package/assets/plugin/tools/close-position.d.ts +0 -45
  225. package/assets/plugin/tools/close-position.js +0 -722
  226. package/assets/plugin/tools/create-order.d.ts +0 -82
  227. package/assets/plugin/tools/create-order.js +0 -1544
  228. package/assets/plugin/tools/exit-gate.d.ts +0 -58
  229. package/assets/plugin/tools/exit-gate.js +0 -162
  230. package/assets/plugin/tools/fetch-balance.d.ts +0 -5
  231. package/assets/plugin/tools/fetch-balance.js +0 -4
  232. package/assets/plugin/tools/fetch-ohlcv.d.ts +0 -11
  233. package/assets/plugin/tools/fetch-ohlcv.js +0 -8
  234. package/assets/plugin/tools/fetch-open-orders.d.ts +0 -7
  235. package/assets/plugin/tools/fetch-open-orders.js +0 -4
  236. package/assets/plugin/tools/fetch-positions.d.ts +0 -7
  237. package/assets/plugin/tools/fetch-positions.js +0 -4
  238. package/assets/plugin/tools/fetch-ticker.d.ts +0 -11
  239. package/assets/plugin/tools/fetch-ticker.js +0 -5
  240. package/assets/plugin/tools/get-agent-profile.d.ts +0 -4
  241. package/assets/plugin/tools/get-agent-profile.js +0 -6
  242. package/assets/plugin/tools/get-analytics.d.ts +0 -6
  243. package/assets/plugin/tools/get-analytics.js +0 -7
  244. package/assets/plugin/tools/get-backtest.d.ts +0 -12
  245. package/assets/plugin/tools/get-backtest.js +0 -91
  246. package/assets/plugin/tools/get-basis.d.ts +0 -7
  247. package/assets/plugin/tools/get-basis.js +0 -7
  248. package/assets/plugin/tools/get-bracket-config.d.ts +0 -11
  249. package/assets/plugin/tools/get-bracket-config.js +0 -24
  250. package/assets/plugin/tools/get-cascade-risk.d.ts +0 -7
  251. package/assets/plugin/tools/get-cascade-risk.js +0 -8
  252. package/assets/plugin/tools/get-crypto-metrics.d.ts +0 -18
  253. package/assets/plugin/tools/get-crypto-metrics.js +0 -62
  254. package/assets/plugin/tools/get-cvd.d.ts +0 -6
  255. package/assets/plugin/tools/get-cvd.js +0 -6
  256. package/assets/plugin/tools/get-divergences.d.ts +0 -6
  257. package/assets/plugin/tools/get-divergences.js +0 -6
  258. package/assets/plugin/tools/get-funding-context.d.ts +0 -6
  259. package/assets/plugin/tools/get-funding-context.js +0 -16
  260. package/assets/plugin/tools/get-liquidation-levels.d.ts +0 -7
  261. package/assets/plugin/tools/get-liquidation-levels.js +0 -7
  262. package/assets/plugin/tools/get-liquidation-pulse.d.ts +0 -9
  263. package/assets/plugin/tools/get-liquidation-pulse.js +0 -22
  264. package/assets/plugin/tools/get-market-breadth.d.ts +0 -6
  265. package/assets/plugin/tools/get-market-breadth.js +0 -8
  266. package/assets/plugin/tools/get-market-intel.d.ts +0 -19
  267. package/assets/plugin/tools/get-market-intel.js +0 -116
  268. package/assets/plugin/tools/get-market-structure.d.ts +0 -47
  269. package/assets/plugin/tools/get-market-structure.js +0 -198
  270. package/assets/plugin/tools/get-my-mined-patterns.d.ts +0 -20
  271. package/assets/plugin/tools/get-my-mined-patterns.js +0 -61
  272. package/assets/plugin/tools/get-my-proposed-learnings.d.ts +0 -20
  273. package/assets/plugin/tools/get-my-proposed-learnings.js +0 -55
  274. package/assets/plugin/tools/get-my-recent-reviews.d.ts +0 -22
  275. package/assets/plugin/tools/get-my-recent-reviews.js +0 -66
  276. package/assets/plugin/tools/get-orderbook.d.ts +0 -21
  277. package/assets/plugin/tools/get-orderbook.js +0 -32
  278. package/assets/plugin/tools/get-pattern-scan.d.ts +0 -7
  279. package/assets/plugin/tools/get-pattern-scan.js +0 -8
  280. package/assets/plugin/tools/get-regime.d.ts +0 -6
  281. package/assets/plugin/tools/get-regime.js +0 -7
  282. package/assets/plugin/tools/get-relevant-learnings.d.ts +0 -21
  283. package/assets/plugin/tools/get-relevant-learnings.js +0 -65
  284. package/assets/plugin/tools/get-resting-liquidity.d.ts +0 -6
  285. package/assets/plugin/tools/get-resting-liquidity.js +0 -11
  286. package/assets/plugin/tools/get-risk-scenario.d.ts +0 -29
  287. package/assets/plugin/tools/get-risk-scenario.js +0 -47
  288. package/assets/plugin/tools/get-risk-summary.d.ts +0 -51
  289. package/assets/plugin/tools/get-risk-summary.js +0 -118
  290. package/assets/plugin/tools/get-sentiment.d.ts +0 -4
  291. package/assets/plugin/tools/get-sentiment.js +0 -6
  292. package/assets/plugin/tools/get-session-review.d.ts +0 -7
  293. package/assets/plugin/tools/get-session-review.js +0 -8
  294. package/assets/plugin/tools/get-setup-detail.d.ts +0 -7
  295. package/assets/plugin/tools/get-setup-detail.js +0 -322
  296. package/assets/plugin/tools/get-signals.d.ts +0 -15
  297. package/assets/plugin/tools/get-signals.js +0 -54
  298. package/assets/plugin/tools/get-sizing.d.ts +0 -6
  299. package/assets/plugin/tools/get-sizing.js +0 -6
  300. package/assets/plugin/tools/get-trade-feedback.d.ts +0 -7
  301. package/assets/plugin/tools/get-trade-feedback.js +0 -8
  302. package/assets/plugin/tools/get-trade-flow.d.ts +0 -7
  303. package/assets/plugin/tools/get-trade-flow.js +0 -7
  304. package/assets/plugin/tools/get-volume-analysis.d.ts +0 -21
  305. package/assets/plugin/tools/get-volume-analysis.js +0 -74
  306. package/assets/plugin/tools/get-volume-profile.d.ts +0 -7
  307. package/assets/plugin/tools/get-volume-profile.js +0 -7
  308. package/assets/plugin/tools/get-wave9-status.d.ts +0 -127
  309. package/assets/plugin/tools/get-wave9-status.js +0 -796
  310. package/assets/plugin/tools/helpers.d.ts +0 -26
  311. package/assets/plugin/tools/helpers.js +0 -39
  312. package/assets/plugin/tools/intel-api.d.ts +0 -34
  313. package/assets/plugin/tools/intel-api.js +0 -119
  314. package/assets/plugin/tools/intel-cache.d.ts +0 -25
  315. package/assets/plugin/tools/intel-cache.js +0 -148
  316. package/assets/plugin/tools/list-strategies.d.ts +0 -17
  317. package/assets/plugin/tools/list-strategies.js +0 -23
  318. package/assets/plugin/tools/modify-stop.d.ts +0 -21
  319. package/assets/plugin/tools/modify-stop.js +0 -120
  320. package/assets/plugin/tools/modify-target.d.ts +0 -21
  321. package/assets/plugin/tools/modify-target.js +0 -110
  322. package/assets/plugin/tools/propose-learning.d.ts +0 -22
  323. package/assets/plugin/tools/propose-learning.js +0 -65
  324. package/assets/plugin/tools/query-review-outcomes.d.ts +0 -30
  325. package/assets/plugin/tools/query-review-outcomes.js +0 -64
  326. package/assets/plugin/tools/query-trades.d.ts +0 -21
  327. package/assets/plugin/tools/query-trades.js +0 -37
  328. package/assets/plugin/tools/record-position-reviews.d.ts +0 -38
  329. package/assets/plugin/tools/record-position-reviews.js +0 -147
  330. package/assets/plugin/tools/save-strategy.d.ts +0 -16
  331. package/assets/plugin/tools/save-strategy.js +0 -46
  332. package/assets/plugin/tools/scan-pairs.d.ts +0 -22
  333. package/assets/plugin/tools/scan-pairs.js +0 -234
  334. package/assets/plugin/tools/score-setup.d.ts +0 -31
  335. package/assets/plugin/tools/score-setup.js +0 -268
  336. package/assets/plugin/tools/set-bracket-requirement.d.ts +0 -18
  337. package/assets/plugin/tools/set-bracket-requirement.js +0 -81
  338. package/assets/plugin/tools/set-exchange-credentials.d.ts +0 -25
  339. package/assets/plugin/tools/set-exchange-credentials.js +0 -80
  340. package/assets/plugin/tools/set-trading-mode.d.ts +0 -26
  341. package/assets/plugin/tools/set-trading-mode.js +0 -135
  342. package/assets/plugin/tools/test-exchange-credentials.d.ts +0 -16
  343. package/assets/plugin/tools/test-exchange-credentials.js +0 -100
  344. package/assets/plugin/tools/toggle-strategy.d.ts +0 -8
  345. package/assets/plugin/tools/toggle-strategy.js +0 -15
  346. package/assets/plugin/trading-params-cache.d.ts +0 -26
  347. package/assets/plugin/trading-params-cache.js +0 -52
  348. package/assets/plugin/types.d.ts +0 -134
  349. package/assets/plugin/types.js +0 -7
  350. package/assets/plugin/util/plugin-paths.d.ts +0 -3
  351. package/assets/plugin/util/plugin-paths.js +0 -15
  352. package/assets/plugin/venues/hyperliquid/hl-balance.d.ts +0 -116
  353. package/assets/plugin/venues/hyperliquid/hl-balance.js +0 -145
  354. package/assets/plugin/venues/hyperliquid/hl-bracket-coordinator.d.ts +0 -123
  355. package/assets/plugin/venues/hyperliquid/hl-bracket-coordinator.js +0 -533
  356. package/assets/plugin/venues/hyperliquid/hl-brackets.d.ts +0 -102
  357. package/assets/plugin/venues/hyperliquid/hl-brackets.js +0 -172
  358. package/assets/plugin/venues/hyperliquid/hl-cloid.d.ts +0 -22
  359. package/assets/plugin/venues/hyperliquid/hl-cloid.js +0 -82
  360. package/assets/plugin/venues/hyperliquid/hl-info-cache.d.ts +0 -46
  361. package/assets/plugin/venues/hyperliquid/hl-info-cache.js +0 -125
  362. package/assets/plugin/venues/hyperliquid/hl-live-adapter.d.ts +0 -146
  363. package/assets/plugin/venues/hyperliquid/hl-live-adapter.js +0 -728
  364. package/assets/plugin/venues/hyperliquid/hl-precision.d.ts +0 -61
  365. package/assets/plugin/venues/hyperliquid/hl-precision.js +0 -176
  366. package/assets/plugin/venues/hyperliquid/hl-private.d.ts +0 -88
  367. package/assets/plugin/venues/hyperliquid/hl-private.js +0 -357
  368. package/assets/plugin/venues/hyperliquid/hl-public.d.ts +0 -79
  369. package/assets/plugin/venues/hyperliquid/hl-public.js +0 -436
  370. package/assets/plugin/venues/hyperliquid/hl-rate-gate.d.ts +0 -57
  371. package/assets/plugin/venues/hyperliquid/hl-rate-gate.js +0 -220
  372. package/assets/plugin/venues/hyperliquid/hl-user-stream.d.ts +0 -90
  373. package/assets/plugin/venues/hyperliquid/hl-user-stream.js +0 -220
  374. package/assets/plugin/venues/registry.d.ts +0 -38
  375. package/assets/plugin/venues/registry.js +0 -46
  376. package/assets/plugin/venues/symbols.d.ts +0 -43
  377. package/assets/plugin/venues/symbols.js +0 -107
  378. package/assets/plugin/wave9/live-account-capture.d.ts +0 -67
  379. package/assets/plugin/wave9/live-account-capture.js +0 -435
  380. package/assets/plugin/wave9/live-autonomous-protection.d.ts +0 -39
  381. package/assets/plugin/wave9/live-autonomous-protection.js +0 -112
  382. package/assets/plugin/wave9/live-durable-reconciliation-scheduler.d.ts +0 -33
  383. package/assets/plugin/wave9/live-durable-reconciliation-scheduler.js +0 -115
  384. package/assets/plugin/wave9/live-execution-ledger.d.ts +0 -107
  385. package/assets/plugin/wave9/live-execution-ledger.js +0 -498
  386. package/assets/plugin/wave9/live-position-confirmation.d.ts +0 -18
  387. package/assets/plugin/wave9/live-position-confirmation.js +0 -111
  388. package/assets/plugin/wave9/live-residual-protection.d.ts +0 -18
  389. package/assets/plugin/wave9/live-residual-protection.js +0 -250
  390. package/assets/plugin/wave9/live-startup-reconciliation.d.ts +0 -38
  391. package/assets/plugin/wave9/live-startup-reconciliation.js +0 -454
  392. package/assets/plugin/wave9/live-symbol-ownership.d.ts +0 -20
  393. package/assets/plugin/wave9/live-symbol-ownership.js +0 -132
  394. package/assets/plugin/wave9/paper-admission-guard.d.ts +0 -199
  395. package/assets/plugin/wave9/paper-admission-guard.js +0 -650
  396. package/assets/plugin/wave9/usdm-evidence-provider.d.ts +0 -42
  397. package/assets/plugin/wave9/usdm-evidence-provider.js +0 -133
@@ -1,478 +0,0 @@
1
- // BracketManager — orchestrates the lifecycle of exchange-side bracket orders.
2
- //
3
- // Separation of concerns:
4
- // - LiveAdapter owns the ENTRY order (submit, wait for fill).
5
- // - BracketManager owns the SL/TP orders (attach, modify, cancel).
6
- // - BracketLedger owns persistent state (survives restart).
7
- //
8
- // Retry policy (locked decision #2):
9
- // - 3 attempts over ~5s total
10
- // - On any leg failure, cancel the successful sibling from that attempt
11
- // before retrying, so the exchange state never runs ahead of the ledger.
12
- // - After exhausting retries, transitions ledger to 'failed' and emits a
13
- // critical event. LiveAdapter listens for that event and triggers the
14
- // auto-flatten (the manager itself does not close positions).
15
- //
16
- // Modes:
17
- // - Both SL and TP provided → target state 'active'
18
- // - Only one provided → target state 'partial' (matches requireStopLoss /
19
- // requireTakeProfit toggles being independently flippable)
20
- // - Neither provided → Manager.registerEntry rejects; LiveAdapter
21
- // should skip bracket registration entirely in that case.
22
- import { EventEmitter } from 'node:events';
23
- import { logger, formatError } from '../logger.js';
24
- import { buildStopLossParams, buildTakeProfitParams } from './bracket-params.js';
25
- import { assertNotShuttingDown, trackOp } from '../lifecycle/shutdown-coordinator.js';
26
- const TAG = 'bracket-manager';
27
- const DEFAULT_MAX_ATTEMPTS = 3;
28
- const DEFAULT_BACKOFF = (attempt) => attempt === 1 ? 1_000 : 2_000;
29
- const DEFAULT_SLA_MS = 3_000;
30
- const TERMINAL_STATES = new Set([
31
- 'triggered_sl',
32
- 'triggered_tp',
33
- 'cancelled',
34
- 'failed',
35
- ]);
36
- function isTerminalState(state) {
37
- return TERMINAL_STATES.has(state);
38
- }
39
- export class BracketManager extends EventEmitter {
40
- api;
41
- ledger;
42
- maxAttempts;
43
- backoff;
44
- slaMs;
45
- now;
46
- sleep;
47
- constructor(api, ledger, opts = {}) {
48
- super();
49
- this.api = api;
50
- this.ledger = ledger;
51
- this.maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
52
- this.backoff = opts.retryBackoffMs ?? DEFAULT_BACKOFF;
53
- this.slaMs = opts.slaMs ?? DEFAULT_SLA_MS;
54
- this.now = opts.now ?? Date.now;
55
- this.sleep = opts.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
56
- }
57
- /** Called by LiveAdapter after submitting the entry but before fill.
58
- * Creates the ledger row in 'pending_entry' state.
59
- *
60
- * Ledger hygiene: if a terminal-state row exists for this symbol (from a
61
- * prior trade cycle that closed, got cancelled, or had its brackets
62
- * stripped), remove it before inserting the new pending_entry. Otherwise
63
- * the stale row's bracketId/slCid/tpCid would survive the upsert and
64
- * mislead later callers — most visibly, `modify_stop` / `modify_target`
65
- * would see `state: 'cancelled'` and refuse to operate even though a fresh
66
- * bracket is now active. */
67
- registerEntry(req, bracketId, entryCid) {
68
- if (req.stopPrice === undefined && req.targetPrice === undefined) {
69
- throw new Error('registerEntry: at least one of stopPrice or targetPrice is required');
70
- }
71
- const existing = this.ledger.getBySymbol(req.symbol);
72
- // ANTI-CLOBBER ROOT FIX (2026-05-16 SOL/INJ spiral disease). A
73
- // NON-terminal row (pending_entry / attaching / active / partial) is a
74
- // live or in-flight bracket for the CURRENT position cycle, holding the
75
- // bracketId + slCid/tpCid that match the orders live on the exchange.
76
- // A single entry produces MULTIPLE fill signals — the real WS
77
- // ORDER_TRADE_UPDATE, the create_order confirmation, the (stale-skill)
78
- // position-poll SYNTHETIC fill, and any agent attach_brackets — each of
79
- // which can re-enter registerEntry. The original code then upsert'd
80
- // state:'pending_entry' with a FRESH bracketId unconditionally, wiping
81
- // the active bracket's identity from the ledger. The ledger row no
82
- // longer matched the live exchange orders, so the orphan sweep saw them
83
- // as unmatched (→ cancel), classify saw stale cids (→ reattach loop),
84
- // and audit went unverifiable — the shared root of every bracket spiral
85
- // this session. Making a duplicate registerEntry a no-op keeps the
86
- // ledger row matching the live orders. attach_brackets terminalises the
87
- // row (markState 'cancelled') BEFORE its registerEntry, so its legitimate
88
- // re-attach is unaffected (existing is terminal → removed below). A new
89
- // entry on a symbol that still has a non-terminal row is a scale-in/
90
- // error whose bracket must be adjusted via modify_*, never by silently
91
- // resetting + re-attaching (that IS the double-bracket spiral).
92
- if (existing && !isTerminalState(existing.state)) {
93
- logger.warn(TAG, `registerEntry(${req.symbol}): a non-terminal bracket row already ` +
94
- `exists (state=${existing.state}, bracketId=${existing.bracketId}, ` +
95
- `slCid=${existing.slCid ?? '-'}, tpCid=${existing.tpCid ?? '-'}). ` +
96
- `Treating as a duplicate fill signal — NOT clobbering the live ` +
97
- `bracket's ledger identity (anti-clobber root fix). Use modify_* ` +
98
- `to change levels.`);
99
- return;
100
- }
101
- if (existing && isTerminalState(existing.state)) {
102
- this.ledger.remove(req.symbol);
103
- }
104
- this.ledger.upsert({
105
- bracketId,
106
- symbol: req.symbol,
107
- entrySide: req.side,
108
- entryCid,
109
- stopPrice: req.stopPrice,
110
- targetPrice: req.targetPrice,
111
- state: 'pending_entry',
112
- });
113
- this.emitEvent({
114
- type: 'bracket.entry_submitted',
115
- bracketId,
116
- symbol: req.symbol,
117
- ts: new Date(this.now()).toISOString(),
118
- });
119
- }
120
- /** Called by LiveAdapter when the entry fills. Attaches SL + TP to the
121
- * exchange with retries. Idempotent — safe to call exactly once per fill.
122
- *
123
- * Intentionally NOT gated by `assertNotShuttingDown`: by the time this
124
- * runs, the entry has already filled and the position is open on Binance.
125
- * Refusing here would leave a naked position — the drain budget is sized
126
- * to cover the 3-attempt retry loop instead. New ENTRIES are gated at
127
- * `LiveAdapter.createOrder`, so once we get here the entry was authorised
128
- * before the shutdown flag was set. */
129
- async attachBrackets(symbol, entryAmount) {
130
- const entry = this.ledger.getBySymbol(symbol);
131
- if (!entry)
132
- throw new Error(`attachBrackets: no ledger entry for ${symbol}`);
133
- if (entry.state !== 'pending_entry') {
134
- // Idempotency: if already attaching/active, return current status.
135
- return {
136
- ok: entry.state === 'active' || entry.state === 'partial',
137
- latencyMs: entry.attachLatencyMs ?? 0,
138
- slCid: entry.slCid,
139
- tpCid: entry.tpCid,
140
- attempts: 0,
141
- };
142
- }
143
- return trackOp(`attachBrackets(${symbol})`, async () => {
144
- const startTs = this.now();
145
- const startedAtIso = new Date(startTs).toISOString();
146
- this.ledger.markState(symbol, 'attaching', { attachStartedAt: startedAtIso });
147
- this.emitEvent({
148
- type: 'bracket.entry_filled',
149
- bracketId: entry.bracketId,
150
- symbol,
151
- ts: startedAtIso,
152
- });
153
- const req = {
154
- symbol,
155
- side: entry.entrySide,
156
- stopPrice: entry.stopPrice,
157
- targetPrice: entry.targetPrice,
158
- };
159
- let lastError;
160
- for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
161
- const result = await this.attemptAttach(req, entry.bracketId, entryAmount);
162
- if (result.ok) {
163
- const latencyMs = this.now() - startTs;
164
- const targetState = (result.slCid && result.tpCid)
165
- ? 'active'
166
- : 'partial';
167
- this.ledger.markState(symbol, targetState, {
168
- attachCompletedAt: new Date(this.now()).toISOString(),
169
- attachLatencyMs: latencyMs,
170
- slCid: result.slCid,
171
- tpCid: result.tpCid,
172
- // Freeze the size the legs were submitted with so a later
173
- // modifyStop/modifyTarget rebuilds the leg at the SAME size
174
- // instead of a placeholder (the 1-contract under-protect bug).
175
- qty: entryAmount,
176
- });
177
- this.emitEvent({
178
- type: 'bracket.attached',
179
- bracketId: entry.bracketId,
180
- symbol,
181
- latencyMs,
182
- ts: new Date(this.now()).toISOString(),
183
- });
184
- if (latencyMs > this.slaMs) {
185
- this.emitEvent({
186
- type: 'bracket.sla_breach',
187
- bracketId: entry.bracketId,
188
- symbol,
189
- latencyMs,
190
- ts: new Date(this.now()).toISOString(),
191
- });
192
- }
193
- return { ok: true, latencyMs, slCid: result.slCid, tpCid: result.tpCid, attempts: attempt };
194
- }
195
- lastError = result.error;
196
- this.emitEvent({
197
- type: 'bracket.attach_failed',
198
- bracketId: entry.bracketId,
199
- symbol,
200
- error: lastError ?? 'unknown',
201
- retryCount: attempt,
202
- ts: new Date(this.now()).toISOString(),
203
- });
204
- // Clean up any partial attach (one leg succeeded, the other didn't)
205
- await this.cancelPartial(symbol, result.slCid, result.tpCid);
206
- if (attempt < this.maxAttempts) {
207
- await this.sleep(this.backoff(attempt));
208
- }
209
- }
210
- const latencyMs = this.now() - startTs;
211
- this.ledger.markState(symbol, 'failed', {
212
- closeReason: 'attach_failed',
213
- lastError,
214
- });
215
- return { ok: false, latencyMs, attempts: this.maxAttempts, error: lastError };
216
- });
217
- }
218
- /** Move the stop. Cancel-then-resubmit; rolls back to the old stop if the
219
- * new submission fails, so the position is never left unprotected. */
220
- async modifyStop(symbol, newStopPrice) {
221
- // Refuse during shutdown — cancel-then-resubmit is the worst race window
222
- // (brief naked position between cancel ack and new SL submission).
223
- assertNotShuttingDown(`modifyStop(${symbol})`);
224
- if (!Number.isFinite(newStopPrice) || newStopPrice <= 0) {
225
- throw new Error(`modifyStop: newStopPrice must be positive finite, got ${newStopPrice}`);
226
- }
227
- const entry = this.ledger.getBySymbol(symbol);
228
- if (!entry)
229
- throw new Error(`modifyStop: no ledger entry for ${symbol}`);
230
- if (entry.state !== 'active' && entry.state !== 'partial') {
231
- throw new Error(`modifyStop: cannot modify stop in state ${entry.state}`);
232
- }
233
- // Resolve the size the bracket was attached with. This MUST happen before
234
- // the old SL is cancelled below: if we cancelled first and then couldn't
235
- // size the replacement, the position would be left naked. Throwing here
236
- // (old bracket still live) is strictly safer than rebuilding the leg at a
237
- // placeholder size, which would silently under-protect the position.
238
- const qty = entry.qty;
239
- if (qty === undefined || !Number.isFinite(qty) || qty <= 0) {
240
- throw new Error(`modifyStop: ledger has no valid bracket qty for ${symbol} (qty=${qty}); ` +
241
- `refusing to resize the stop to a placeholder size — re-attach the bracket first`);
242
- }
243
- return trackOp(`modifyStop(${symbol})`, async () => {
244
- const oldStopPrice = entry.stopPrice;
245
- const oldSlCid = entry.slCid;
246
- // Cancel old stop (if present)
247
- if (oldSlCid) {
248
- try {
249
- await this.api.cancelOrderByClientId(oldSlCid, symbol);
250
- }
251
- catch (err) {
252
- throw new Error(`modifyStop: could not cancel old SL: ${formatError(err)}`);
253
- }
254
- }
255
- // Submit new stop
256
- const leg = buildStopLossParams({ symbol, side: entry.entrySide, stopPrice: newStopPrice }, entry.bracketId, qty);
257
- try {
258
- await this.api.submitBracketLeg(leg);
259
- }
260
- catch (err) {
261
- // Rollback: put the old stop back
262
- if (oldStopPrice !== undefined && oldSlCid) {
263
- const rollbackLeg = buildStopLossParams({ symbol, side: entry.entrySide, stopPrice: oldStopPrice }, entry.bracketId, qty);
264
- try {
265
- await this.api.submitBracketLeg(rollbackLeg);
266
- }
267
- catch (rbErr) {
268
- logger.error(TAG, `modifyStop rollback ALSO failed for ${symbol}: ${formatError(rbErr)}`);
269
- // Position is now unprotected on the stop side — emit critical event
270
- this.emitEvent({
271
- type: 'bracket.attach_failed',
272
- bracketId: entry.bracketId,
273
- symbol,
274
- error: `rollback failed: ${formatError(rbErr)}`,
275
- retryCount: 0,
276
- ts: new Date(this.now()).toISOString(),
277
- });
278
- }
279
- }
280
- throw new Error(`modifyStop: new SL submission failed: ${formatError(err)}`);
281
- }
282
- // Success — persist new stop. Same reasoning as attemptAttach: store the
283
- // client id we chose, not the exchange-assigned id.
284
- this.ledger.upsert({
285
- ...entry,
286
- stopPrice: newStopPrice,
287
- slCid: leg.params.newClientOrderId,
288
- });
289
- this.emitEvent({
290
- type: 'bracket.modified',
291
- bracketId: entry.bracketId,
292
- symbol,
293
- field: 'stop',
294
- oldValue: oldStopPrice ?? NaN,
295
- newValue: newStopPrice,
296
- ts: new Date(this.now()).toISOString(),
297
- });
298
- });
299
- }
300
- /** Move the take-profit. Same semantics as modifyStop. */
301
- async modifyTarget(symbol, newTargetPrice) {
302
- assertNotShuttingDown(`modifyTarget(${symbol})`);
303
- if (!Number.isFinite(newTargetPrice) || newTargetPrice <= 0) {
304
- throw new Error(`modifyTarget: newTargetPrice must be positive finite, got ${newTargetPrice}`);
305
- }
306
- const entry = this.ledger.getBySymbol(symbol);
307
- if (!entry)
308
- throw new Error(`modifyTarget: no ledger entry for ${symbol}`);
309
- if (entry.state !== 'active' && entry.state !== 'partial') {
310
- throw new Error(`modifyTarget: cannot modify target in state ${entry.state}`);
311
- }
312
- // See modifyStop: resolve size before cancelling the old TP so we never
313
- // rebuild the leg at a placeholder size (the 1-contract under-protect bug).
314
- const qty = entry.qty;
315
- if (qty === undefined || !Number.isFinite(qty) || qty <= 0) {
316
- throw new Error(`modifyTarget: ledger has no valid bracket qty for ${symbol} (qty=${qty}); ` +
317
- `refusing to resize the target to a placeholder size — re-attach the bracket first`);
318
- }
319
- return trackOp(`modifyTarget(${symbol})`, async () => {
320
- const oldTargetPrice = entry.targetPrice;
321
- const oldTpCid = entry.tpCid;
322
- if (oldTpCid) {
323
- try {
324
- await this.api.cancelOrderByClientId(oldTpCid, symbol);
325
- }
326
- catch (err) {
327
- throw new Error(`modifyTarget: could not cancel old TP: ${formatError(err)}`);
328
- }
329
- }
330
- const leg = buildTakeProfitParams({ symbol, side: entry.entrySide, targetPrice: newTargetPrice }, entry.bracketId, qty);
331
- try {
332
- await this.api.submitBracketLeg(leg);
333
- }
334
- catch (err) {
335
- if (oldTargetPrice !== undefined && oldTpCid) {
336
- const rollbackLeg = buildTakeProfitParams({ symbol, side: entry.entrySide, targetPrice: oldTargetPrice }, entry.bracketId, qty);
337
- try {
338
- await this.api.submitBracketLeg(rollbackLeg);
339
- }
340
- catch (rbErr) {
341
- logger.error(TAG, `modifyTarget rollback ALSO failed for ${symbol}: ${formatError(rbErr)}`);
342
- }
343
- }
344
- throw new Error(`modifyTarget: new TP submission failed: ${formatError(err)}`);
345
- }
346
- this.ledger.upsert({
347
- ...entry,
348
- targetPrice: newTargetPrice,
349
- tpCid: leg.params.newClientOrderId,
350
- });
351
- this.emitEvent({
352
- type: 'bracket.modified',
353
- bracketId: entry.bracketId,
354
- symbol,
355
- field: 'target',
356
- oldValue: oldTargetPrice ?? NaN,
357
- newValue: newTargetPrice,
358
- ts: new Date(this.now()).toISOString(),
359
- });
360
- });
361
- }
362
- /** Cancel both bracket legs and mark the ledger cancelled. Called when
363
- * LiveAdapter closes the position via `close_position` or flatten. Risk-
364
- * reducing — allowed during shutdown, but tracked so the drain awaits it. */
365
- async cancelBrackets(symbol, reason) {
366
- const entry = this.ledger.getBySymbol(symbol);
367
- if (!entry)
368
- return; // nothing to cancel
369
- if (entry.slCid) {
370
- try {
371
- await this.api.cancelOrderByClientId(entry.slCid, symbol);
372
- }
373
- catch (err) {
374
- logger.warn(TAG, `cancelBrackets SL ${symbol}: ${formatError(err)}`);
375
- }
376
- }
377
- if (entry.tpCid) {
378
- try {
379
- await this.api.cancelOrderByClientId(entry.tpCid, symbol);
380
- }
381
- catch (err) {
382
- logger.warn(TAG, `cancelBrackets TP ${symbol}: ${formatError(err)}`);
383
- }
384
- }
385
- this.ledger.markState(symbol, 'cancelled', { closeReason: 'cancelled_manual' });
386
- this.emitEvent({
387
- type: 'bracket.cancelled',
388
- bracketId: entry.bracketId,
389
- symbol,
390
- reason,
391
- ts: new Date(this.now()).toISOString(),
392
- });
393
- }
394
- /** Called by the reconciler / fill poller when one of the bracket legs
395
- * fires on the exchange. Transitions the ledger to the matching triggered
396
- * state and emits. Binance's closePosition:true auto-cancels the sibling. */
397
- handleBracketTriggered(symbol, triggeredRole) {
398
- const entry = this.ledger.getBySymbol(symbol);
399
- if (!entry)
400
- return;
401
- const nextState = triggeredRole === 'sl' ? 'triggered_sl' : 'triggered_tp';
402
- this.ledger.markState(symbol, nextState, {
403
- closeReason: triggeredRole === 'sl' ? 'triggered_sl' : 'triggered_tp',
404
- });
405
- this.emitEvent({
406
- type: 'bracket.triggered',
407
- bracketId: entry.bracketId,
408
- symbol,
409
- side: triggeredRole,
410
- ts: new Date(this.now()).toISOString(),
411
- });
412
- }
413
- // ---- Internals ----
414
- async attemptAttach(req, bracketId, entryAmount) {
415
- let slCid;
416
- let tpCid;
417
- // ROOT-CAUSE FIX 2026-05-16: neutralise any externally-armed
418
- // countdownCancelAll dead-man's-switch for this symbol BEFORE placing
419
- // protection, so Binance can't purge the legs ~tens of seconds later
420
- // (the proven cause of the months-long naked-position spiral). Purely
421
- // protective + best-effort: the method swallows its own errors and never
422
- // throws here — a failed disable must never block bracket placement.
423
- if (this.api.disableCountdownCancelAll) {
424
- try {
425
- await this.api.disableCountdownCancelAll(req.symbol);
426
- }
427
- catch (err) {
428
- logger.warn(TAG, `disableCountdownCancelAll(${req.symbol}) threw (ignored): ${formatError(err)}`);
429
- }
430
- }
431
- if (req.stopPrice !== undefined) {
432
- const leg = buildStopLossParams(req, bracketId, entryAmount);
433
- try {
434
- await this.api.submitBracketLeg(leg);
435
- // Store the CLIENT order id (what we sent), not the exchange-assigned
436
- // id. The exchange id lives in a different namespace for algo orders
437
- // (algoId) vs regular orders; cancelOrderByClientId expects the cid
438
- // we chose, which is deterministic and survives an adapter restart.
439
- slCid = leg.params.newClientOrderId;
440
- }
441
- catch (err) {
442
- return { ok: false, error: `SL: ${formatError(err)}` };
443
- }
444
- }
445
- if (req.targetPrice !== undefined) {
446
- const leg = buildTakeProfitParams(req, bracketId, entryAmount);
447
- try {
448
- await this.api.submitBracketLeg(leg);
449
- tpCid = leg.params.newClientOrderId;
450
- }
451
- catch (err) {
452
- return { ok: false, slCid, error: `TP: ${formatError(err)}` };
453
- }
454
- }
455
- return { ok: true, slCid, tpCid };
456
- }
457
- async cancelPartial(symbol, slCid, tpCid) {
458
- if (slCid) {
459
- try {
460
- await this.api.cancelOrderByClientId(slCid, symbol);
461
- }
462
- catch (err) {
463
- logger.warn(TAG, `cancelPartial SL ${symbol}: ${formatError(err)}`);
464
- }
465
- }
466
- if (tpCid) {
467
- try {
468
- await this.api.cancelOrderByClientId(tpCid, symbol);
469
- }
470
- catch (err) {
471
- logger.warn(TAG, `cancelPartial TP ${symbol}: ${formatError(err)}`);
472
- }
473
- }
474
- }
475
- emitEvent(event) {
476
- this.emit('event', event);
477
- }
478
- }
@@ -1,22 +0,0 @@
1
- import type { BracketId, BracketRequest } from './bracket-types.js';
2
- /** One CCXT-shaped leg ready to hand to `exchange.createOrder(...)`. */
3
- export interface BracketLegParams {
4
- symbol: string;
5
- type: 'STOP_MARKET' | 'TAKE_PROFIT_MARKET';
6
- side: 'buy' | 'sell';
7
- amount: number;
8
- price: undefined;
9
- params: Record<string, any>;
10
- }
11
- /** Return the side that CLOSES a position opened with `entrySide`. */
12
- export declare function closingSide(entrySide: 'buy' | 'sell'): 'buy' | 'sell';
13
- /** Build the stop-loss leg. Throws if stopPrice is missing. */
14
- export declare function buildStopLossParams(req: BracketRequest, bracketId: BracketId, entryAmount: number): BracketLegParams;
15
- /** Build the take-profit leg. Throws if targetPrice is missing. */
16
- export declare function buildTakeProfitParams(req: BracketRequest, bracketId: BracketId, entryAmount: number): BracketLegParams;
17
- /** Sanity check that a stopPrice is on the correct side of entry — catches
18
- * off-by-flipped-sign errors before Binance rejects with -2021 "would
19
- * immediately trigger." Returns null if OK, error message otherwise. */
20
- export declare function validateStopDirection(entrySide: 'buy' | 'sell', entryPrice: number, stopPrice: number): string | null;
21
- /** Same sanity check for take-profit: must be on the winning side of entry. */
22
- export declare function validateTargetDirection(entrySide: 'buy' | 'sell', entryPrice: number, targetPrice: number): string | null;
@@ -1,124 +0,0 @@
1
- // CCXT parameter builder for bracket legs (STOP_MARKET + TAKE_PROFIT_MARKET).
2
- //
3
- // One-way mode only (per locked design decision #1). Hedge-mode support can
4
- // be added later via positionSide — but see §2 of BRACKET_ORDERS_DESIGN.md.
5
- //
6
- // Order-flag semantics — `closePosition: true` (position-bound), 2026-05-16.
7
- //
8
- // ROOT-CAUSE FIX. We previously used `reduceOnly: true` + explicit `amount`.
9
- // On 2025-12-09 Binance migrated ALL USD-M conditional orders to the new
10
- // "Algo Service" (changelog 2025-11-06 / 2025-12-09; classic /fapi/v1/order
11
- // now rejects them with -4120 → forced onto POST /fapi/v1/algoOrder). The
12
- // new Algo Service AUTO-CANCELS standalone `reduceOnly`+`quantity`
13
- // conditional algo orders ~17-53s after placement WHILE THE POSITION IS
14
- // STILL OPEN (prod-proven 2026-05-15/16 SOL+APT: every prior fix targeted
15
- // ReefClaw bracket logic — the wrong layer; an airtight-verified
16
- // `logAlgoCancelChokepoint` tracer recorded ZERO of our cancel calls while
17
- // Binance reported the leg CANCELED). Binance does NOT document this; it is
18
- // a silent post-migration behaviour change.
19
- //
20
- // `closePosition: true` is the POSITION-BOUND form: Binance ties the order's
21
- // lifecycle to the position and does NOT auto-cancel it while the position
22
- // is open. Independently proven: the operator's manually-set Binance-app
23
- // position TP/SL is exactly this form and it sticks when our reduceOnly one
24
- // vanishes. Doc (New-Algo-Order): closePosition "close all current
25
- // long/short position if triggered"; MUST NOT be sent with `quantity`
26
- // (-4137) or `reduceOnly` (-4138) → `amount` is 0 and neither flag is set.
27
- //
28
- // -4130 reassessed: the old comment said a second closePosition order is
29
- // rejected -4130 ("stop/TP with GTE and closePosition in the direction
30
- // exists"). That finding "after testnet validation" PREDATES the 2025-12-09
31
- // algo migration; -4130 is no longer in the current USD-M error-code doc;
32
- // and the Binance app itself runs a coexisting closePosition SL+TP on a
33
- // position (opposite trigger types, the standard exchange-native bracket).
34
- // The deployed cancel/attribution tracers + the bracket reconciler surface
35
- // any -4130 immediately and loudly, so a recurrence is an observable fast
36
- // follow-up (asymmetric SL-closePosition / TP-reduceOnly fallback) rather
37
- // than a silent naked position.
38
- //
39
- // closePosition also SIMPLIFIES the model: first trigger closes the whole
40
- // position; the sibling is auto-cancelled by Binance on position close
41
- // (EXPIRED, benign); no quantity/partial-fill bracket-resize logic needed.
42
- //
43
- // workingType:
44
- // - CONTRACT_PRICE (Binance default): triggers on last traded price of the
45
- // pair. Matches what users typically mean by "stop price."
46
- // - MARK_PRICE: triggers on the mark price (index-derived). More robust to
47
- // single-pair manipulation but can lag fast moves. Not used by default.
48
- import { buildBracketCid } from './bracket-id.js';
49
- /** Return the side that CLOSES a position opened with `entrySide`. */
50
- export function closingSide(entrySide) {
51
- return entrySide === 'buy' ? 'sell' : 'buy';
52
- }
53
- /** Build the stop-loss leg. Throws if stopPrice is missing. */
54
- export function buildStopLossParams(req, bracketId, entryAmount) {
55
- if (req.stopPrice === undefined || !Number.isFinite(req.stopPrice) || req.stopPrice <= 0) {
56
- throw new Error('buildStopLossParams: stopPrice must be a positive finite number');
57
- }
58
- if (!Number.isFinite(entryAmount) || entryAmount <= 0) {
59
- throw new Error('buildStopLossParams: entryAmount must be a positive finite number');
60
- }
61
- return {
62
- symbol: req.symbol,
63
- type: 'STOP_MARKET',
64
- side: closingSide(req.side),
65
- // closePosition is "close-all" — Binance ignores/forbids a quantity
66
- // (-4137). amount 0; entryAmount is still validated above so a caller
67
- // with a bogus size is rejected, and the ledger keeps qty for telemetry.
68
- amount: 0,
69
- price: undefined,
70
- params: {
71
- stopPrice: req.stopPrice,
72
- // Position-bound form: Binance keeps it with the position and does NOT
73
- // auto-cancel it while open (unlike reduceOnly+qty — see file header).
74
- closePosition: true,
75
- workingType: 'CONTRACT_PRICE',
76
- newClientOrderId: buildBracketCid(bracketId, 'stop'),
77
- },
78
- };
79
- }
80
- /** Build the take-profit leg. Throws if targetPrice is missing. */
81
- export function buildTakeProfitParams(req, bracketId, entryAmount) {
82
- if (req.targetPrice === undefined || !Number.isFinite(req.targetPrice) || req.targetPrice <= 0) {
83
- throw new Error('buildTakeProfitParams: targetPrice must be a positive finite number');
84
- }
85
- if (!Number.isFinite(entryAmount) || entryAmount <= 0) {
86
- throw new Error('buildTakeProfitParams: entryAmount must be a positive finite number');
87
- }
88
- return {
89
- symbol: req.symbol,
90
- type: 'TAKE_PROFIT_MARKET',
91
- side: closingSide(req.side),
92
- amount: 0, // closePosition = close-all; no quantity (-4137)
93
- price: undefined,
94
- params: {
95
- stopPrice: req.targetPrice, // Binance calls the trigger "stopPrice" on TP_MARKET too
96
- // Position-bound form — see file header (root-cause fix 2026-05-16).
97
- closePosition: true,
98
- workingType: 'CONTRACT_PRICE',
99
- newClientOrderId: buildBracketCid(bracketId, 'target'),
100
- },
101
- };
102
- }
103
- /** Sanity check that a stopPrice is on the correct side of entry — catches
104
- * off-by-flipped-sign errors before Binance rejects with -2021 "would
105
- * immediately trigger." Returns null if OK, error message otherwise. */
106
- export function validateStopDirection(entrySide, entryPrice, stopPrice) {
107
- if (entrySide === 'buy' && stopPrice >= entryPrice) {
108
- return `Stop price ${stopPrice} must be BELOW entry ${entryPrice} for a long position`;
109
- }
110
- if (entrySide === 'sell' && stopPrice <= entryPrice) {
111
- return `Stop price ${stopPrice} must be ABOVE entry ${entryPrice} for a short position`;
112
- }
113
- return null;
114
- }
115
- /** Same sanity check for take-profit: must be on the winning side of entry. */
116
- export function validateTargetDirection(entrySide, entryPrice, targetPrice) {
117
- if (entrySide === 'buy' && targetPrice <= entryPrice) {
118
- return `Target price ${targetPrice} must be ABOVE entry ${entryPrice} for a long position`;
119
- }
120
- if (entrySide === 'sell' && targetPrice >= entryPrice) {
121
- return `Target price ${targetPrice} must be BELOW entry ${entryPrice} for a short position`;
122
- }
123
- return null;
124
- }