@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,527 +0,0 @@
1
- // Tool: audit_bracket_protection — returns every open live position with a
2
- // verdict on whether exchange-side SL / TP protection is currently attached.
3
- // Agent runs this at SESSION START and every heartbeat; any position with
4
- // `has_stop=false` or `has_target=false` must be resolved (attach_brackets
5
- // with new levels, or close_position).
6
- //
7
- // Cross-references three sources of truth to catch every failure mode:
8
- // 1. Live positions (adapter.getPositions)
9
- // 2. Open orders on the exchange (adapter.getOpenOrders) — ground truth
10
- // for SL/TP orders currently live
11
- // 3. Bracket ledger (for state + stored price levels)
12
- //
13
- // Order checks are by clientOrderId prefix AND by symbol + type, so we catch
14
- // both (a) bracket orders with reefclaw-managed cids and (b) manually-placed
15
- // STOP_MARKET / TAKE_PROFIT_MARKET orders from the Binance UI that happen to
16
- // protect the position. Either is good enough for "position is protected".
17
- import { parseBracketCid } from '../live/bracket-id.js';
18
- import { normalizeBracketSymbol } from '../live/bracket-ledger.js';
19
- import { formatError, logger } from '../logger.js';
20
- const TAG = 'audit-bracket-protection';
21
- // Per-symbol verdict history for flicker detection. When audit verdicts
22
- // transition protected→unprotected→protected repeatedly inside a short
23
- // window, the bracket subsystem itself is unreliable — protection on the
24
- // exchange isn't changing, our reading of it is. That's the signature of
25
- // the 2026-05-15 spiral (ATOM/LINK/NEAR all flushed via bracket_integrity
26
- // while their brackets were really still live). Emitting a structured warn
27
- // when we see it surfaces the bug to the operator BEFORE the agent
28
- // escalates to close_position.
29
- const FLICKER_WINDOW_MS = 5 * 60 * 1000;
30
- const FLICKER_THRESHOLD = 3; // 3 verdict flips in the window → warn
31
- // Retention bumped to 60 min so close_position can copy the last hour of
32
- // audit verdicts into position_closes.close_assessment.metadata.bracket_health_history
33
- // for post-mortem analysis on the dashboard's Position Timeline drawer.
34
- // 120 samples × ~120 bytes = ~15KB worst-case per symbol; trivial.
35
- const HISTORY_RETENTION_MS = 60 * 60 * 1000;
36
- const HISTORY_MAX_PER_SYMBOL = 120;
37
- const verdictHistory = new Map();
38
- let lastFlickerWarnedAt = new Map();
39
- const FLICKER_WARN_COOLDOWN_MS = 60 * 1000; // don't repeat the warn more than once a minute per symbol
40
- export async function auditBracketProtectionTool(_args, deps) {
41
- try {
42
- const isLive = deps.adapter.isLive;
43
- // Paper mode: stop protection lives in position metadata + stop-watcher,
44
- // not exchange orders. Report positions with their metadata for
45
- // completeness, but mark them all protected (the stop-watcher model is
46
- // the contract in paper).
47
- if (!isLive) {
48
- const positions = await deps.adapter.getPositions();
49
- const entries = positions
50
- .filter(p => p.contracts > 0)
51
- .map(p => ({
52
- symbol: p.symbol,
53
- side: p.side,
54
- contracts: p.contracts,
55
- entry_price: p.entryPrice,
56
- mark_price: p.markPrice,
57
- has_stop: p.stopPrice !== undefined,
58
- has_target: p.targetPrice !== undefined,
59
- stop_price: p.stopPrice,
60
- target_price: p.targetPrice,
61
- ledger_state: 'no_ledger_row',
62
- reason: p.stopPrice !== undefined ? 'manual_order_protecting' : 'no_protective_order',
63
- recommended_action: p.stopPrice !== undefined ? 'none' : 'close_position',
64
- }));
65
- const unprotected = entries.filter(e => !e.has_stop).length;
66
- return {
67
- ok: true,
68
- mode: 'paper',
69
- brackets_enabled: false,
70
- total_positions: entries.length,
71
- protected_count: entries.length - unprotected,
72
- unprotected_count: unprotected,
73
- positions: entries,
74
- };
75
- }
76
- // Live mode.
77
- const live = deps.adapter;
78
- const ledger = live.getBracketLedger?.() ?? null;
79
- const bracketsEnabled = ledger !== null;
80
- // Fetch positions + open orders. If `getOpenOrders` throws (it does so
81
- // on null = fetch failure / 429 — see live-adapter.ts), we return a
82
- // clear error instead of falling through with an empty list. The old
83
- // behaviour was: null collapsed to []; audit said has_stop=false;
84
- // agent ran attach_brackets; cancelSymbolBracketOrders no-op'd; new
85
- // brackets piled up on top of orders Binance hadn't surfaced through
86
- // the 429'd fetch. 2026-05-14 ATOM ran ~17 spurious re-attach cycles
87
- // before the operator noticed. With this gate, a single 429 just
88
- // delays the audit one heartbeat — far safer than fabricating
89
- // "unprotected" verdicts.
90
- // Weight discipline (2026-05-15, measured): the unscoped getOpenOrders
91
- // sweep is 80 weight (40 regular + 40 algo). Pre-fix this ran on EVERY
92
- // audit invocation — including when flat — and the agent's SKILL.md
93
- // recovery loop (audit→attach) re-runs it every ~3s, so prod measured
94
- // ~560-640 weight/min from this ONE call, ~40% of the pacer ceiling,
95
- // which starved every other read and blinded the agent. Two cuts that
96
- // do NOT change the audit verdict:
97
- // 1. `openOrders` is consumed ONLY inside `activePositions.map(...)`,
98
- // so when there are no active positions it is provably unused —
99
- // skip the call entirely (return the trivial 0-position verdict).
100
- // 2. When positions exist, fetch open orders SCOPED to those symbols
101
- // (1 regular + 1 algo = 2 weight each) instead of one 80-weight
102
- // unscoped sweep. Audit only ever inspects orders for symbols that
103
- // have a position; cross-symbol orphan detection is the bracket
104
- // reconciler's job (it keeps its 60s unscoped sweep — the
105
- // authoritative orphan/naked backstop, unchanged).
106
- // The null-vs-empty {error} contract is preserved for the calls that
107
- // matter (verifying real open positions have stops). When flat, the
108
- // reconciler + user-data WS + ALGO_UPDATE remain the safety net.
109
- let positions, openOrders;
110
- try {
111
- // null = positions fetch FAILED (429 / weight-paced / transient).
112
- // getPositions() would collapse that to [] → activeSymbols=[] → this
113
- // audit returns a trivial "0 positions, all protected" verdict during
114
- // a rate-limit storm, masking a real naked position for a heartbeat.
115
- // Treat it identically to the getOpenOrders-null case below: surface
116
- // {error} so the agent skips this cycle and MUST NOT run attach_brackets
117
- // (see CLAUDE.md audit-vs-action contract).
118
- const positionsOrNull = await deps.adapter.getPositionsOrNull();
119
- if (positionsOrNull === null) {
120
- throw new Error('positions fetch returned null (exchange data unavailable)');
121
- }
122
- positions = positionsOrNull;
123
- const activeSymbols = [
124
- ...new Set(positions.filter(p => p.contracts > 0).map(p => p.symbol)),
125
- ];
126
- if (activeSymbols.length === 0) {
127
- openOrders = [];
128
- }
129
- else {
130
- const perSymbol = await Promise.all(activeSymbols.map(s => deps.adapter.getOpenOrders(s)));
131
- openOrders = perSymbol.flat();
132
- }
133
- }
134
- catch (err) {
135
- const msg = formatError(err);
136
- logger.warn(TAG, `audit skipped — exchange data unavailable: ${msg}`);
137
- return {
138
- error: `Exchange data unavailable (likely Binance 429 or transient network). ` +
139
- `Skipping audit this cycle — current bracket state on Binance is unchanged. ` +
140
- `Retry on next heartbeat. Underlying: ${msg}`,
141
- };
142
- }
143
- const activePositions = positions.filter(p => p.contracts > 0);
144
- // Group open orders by NORMALIZED symbol so position.symbol (may be
145
- // `:USDT`-suffixed from CCXT fetchPositions) and order.symbol (same
146
- // source but historically inconsistent across CCXT versions) always
147
- // collide on the same key. Without this, a suffixed position would miss
148
- // an un-suffixed order's brackets and audit would return has_stop=false
149
- // despite the exchange-side stop being live.
150
- const ordersBySymbol = new Map();
151
- for (const o of openOrders) {
152
- if (!o.symbol)
153
- continue;
154
- const key = normalizeBracketSymbol(o.symbol);
155
- const list = ordersBySymbol.get(key) ?? [];
156
- list.push(o);
157
- ordersBySymbol.set(key, list);
158
- }
159
- // Untrusted-empty contradiction guard (2026-05-15 SOL/INJ spiral).
160
- // A position whose ledger row is non-terminal WITH stored cids but whose
161
- // scoped open-orders fetch came back EMPTY is NOT positive evidence the
162
- // brackets are gone: under weight pressure Binance's algo-orders REST
163
- // endpoint returns a *successful* [] while ALGO_UPDATE (the authoritative
164
- // bracket-lifecycle signal) shows the legs still live and never
165
- // terminated. Emitting a confident has_stop=false / attach_brackets
166
- // verdict here is what drove the audit → attach → cancel-live-brackets
167
- // loop AND the bracket_integrity escalation that flushed ATOM/LINK/NEAR.
168
- // Same null≠empty / require-positive-disconfirmation contract as
169
- // classifyLedgerVsExchange and the reconciler: surface {error} so the
170
- // agent skips this cycle and MUST NOT run attach_brackets /
171
- // close_position(reason='bracket_integrity') (CLAUDE.md audit-vs-action
172
- // contract). The reconciler + ALGO_UPDATE remain the backstop for any
173
- // genuinely-naked position on another symbol within one cycle — the
174
- // file's own stated philosophy ("a single transient gap just delays the
175
- // audit one heartbeat — far safer than fabricating verdicts").
176
- const unverifiable = activePositions.filter(p => {
177
- const normSym = normalizeBracketSymbol(p.symbol);
178
- if ((ordersBySymbol.get(normSym) ?? []).length > 0)
179
- return false;
180
- const lr = ledger?.getBySymbol(p.symbol) ?? null;
181
- return !!lr
182
- && (lr.state === 'active' || lr.state === 'partial' || lr.state === 'attaching')
183
- && (!!lr.slCid || !!lr.tpCid);
184
- });
185
- // Before declaring the audit blind, ask the ZERO-WEIGHT authoritative
186
- // source we already built (Phase 1/2, deployed): the per-cid bracket-leg
187
- // liveness resolver. `getOpenOrders` came back empty ONLY because the
188
- // proactive weight pacer shed it (steady-state IP weight pins the soft
189
- // ceiling 24/7 — the real disease). But ALGO_UPDATE has already pushed
190
- // every leg's NEW/CANCELED/EXPIRED/TRIGGERED status into the in-memory
191
- // per-cid map at zero Binance weight. `resolveBracketLegLiveness` reads
192
- // that (Tier-1, only when the WS store is trusted), falling back to a
193
- // weight-1 REST query, then to 'unknown'. Pre-fix this branch returned
194
- // {error} unconditionally → the agent went blind on a live position for
195
- // HOURS (prod 2026-05-16: INJ/USDT unverifiable every heartbeat 04:29→
196
- // 05:54 straight) even though the WS knew the brackets were live the
197
- // whole time. The Phase-2 resolver was dead code in the audit path.
198
- //
199
- // stop leg 'live' → position IS protected (positive verdict, w=0)
200
- // stop leg 'terminal' → positively confirmed naked → attach_brackets
201
- // 'unknown' → keep the d59e51b safe {error} floor for that
202
- // symbol only (NEVER infer from absence)
203
- const wsResolvedProtected = new Set(); // normSym → stop leg confirmed live
204
- const stillBlind = [];
205
- if (unverifiable.length > 0) {
206
- await Promise.all(unverifiable.map(async (p) => {
207
- const normSym = normalizeBracketSymbol(p.symbol);
208
- const lr = ledger?.getBySymbol(p.symbol) ?? null;
209
- // The stop leg is the protective one; resolve it. (A live SL is the
210
- // bar for "protected"; TP-only is still has_stop=false downstream.)
211
- let slState = 'unknown';
212
- if (lr?.slCid) {
213
- try {
214
- slState = await live.resolveBracketLegLiveness(lr.slCid);
215
- }
216
- catch {
217
- slState = 'unknown';
218
- }
219
- }
220
- if (slState === 'live') {
221
- wsResolvedProtected.add(normSym);
222
- }
223
- else {
224
- // #1 (supporting) — the ledger's slCid may be positively terminal
225
- // while a PRIOR reattach's FRESH stop leg is live on the exchange
226
- // under a NEW cid the ledger never caught up to (the 2026-05-16 INJ
227
- // spiral). Declaring the position naked here drives the agent to
228
- // attach_brackets → clear+reattach → cancels the live leg → spiral.
229
- // Before that, ask whether ANY trusted-WS rc-*-s stop leg for this
230
- // symbol is live, not just the ledger's cid. (Authoritative break
231
- // is #2 in classifyLedgerVsExchange; this keeps the audit verdict
232
- // consistent so the agent isn't told to attach in the first place.)
233
- const sweep = live.findTrustedLiveBracketCidsForSymbol(p.symbol);
234
- const hasLiveStopLeg = sweep.trusted &&
235
- sweep.liveCids.some(c => parseBracketCid(c)?.role === 'stop');
236
- if (hasLiveStopLeg) {
237
- wsResolvedProtected.add(normSym);
238
- }
239
- else if (slState === 'terminal') {
240
- // Positively confirmed gone AND no other live stop leg — let the
241
- // normal entry builder produce has_stop=false → attach_brackets
242
- // (licensed: POSITIVE disconfirmation, not inference from absence).
243
- }
244
- else {
245
- stillBlind.push(p);
246
- }
247
- }
248
- }));
249
- }
250
- if (stillBlind.length > 0) {
251
- const blindSyms = stillBlind.map(p => p.symbol).join(', ');
252
- const seenLive = [...wsResolvedProtected].join(', ') || 'none';
253
- logger.warn(TAG, `audit unverifiable for [${blindSyms}]: scoped getOpenOrders returned EMPTY ` +
254
- `(weight-paced) AND the per-cid liveness resolver could not positively confirm ` +
255
- `(WS untrusted/silent + weight-1 REST unavailable). Empty ≠ "brackets gone". ` +
256
- `Returning {error} — agent must NOT run attach_brackets or ` +
257
- `close_position(reason='bracket_integrity') this cycle. ` +
258
- `(WS positively confirmed LIVE for: [${seenLive}].)`);
259
- return {
260
- error: `Cannot confirm bracket protection for [${blindSyms}] — the exchange returned ` +
261
- `an empty open-orders set (weight-paced) and the zero-weight per-leg liveness ` +
262
- `resolver could not positively confirm the bracket legs (WS store untrusted ` +
263
- `or silent on these cids, and the weight-1 REST query was unavailable). An ` +
264
- `empty result is NOT proof the brackets are gone. Skipping audit this cycle — ` +
265
- `bracket state on Binance is unchanged. Do NOT run attach_brackets or ` +
266
- `close_position(reason='bracket_integrity') on the basis of this call. ` +
267
- `Retry next heartbeat.`,
268
- };
269
- }
270
- if (wsResolvedProtected.size > 0) {
271
- logger.info(TAG, `per-leg liveness resolver: scoped getOpenOrders was weight-paced-empty but ` +
272
- `the WS POSITIVELY confirmed the stop leg LIVE for ` +
273
- `[${[...wsResolvedProtected].join(', ')}] at ZERO Binance weight — ` +
274
- `reporting protected instead of going blind.`);
275
- }
276
- const entries = activePositions.map(p => {
277
- const normSym = normalizeBracketSymbol(p.symbol);
278
- const symbolOrders = ordersBySymbol.get(normSym) ?? [];
279
- // BracketLedger applies normalization internally; pass p.symbol through.
280
- const ledgerRow = ledger?.getBySymbol(p.symbol) ?? null;
281
- // WS-confirmed-protected overlay: scoped getOpenOrders was weight-paced
282
- // to empty for this symbol, so the order-based classification below
283
- // would falsely report has_stop=false. But the zero-weight per-cid
284
- // resolver POSITIVELY confirmed the stop leg is live on the exchange.
285
- // Trust that (it's the authoritative ALGO_UPDATE signal, not inference
286
- // from an absent REST result). stop_price from the ledger (our intent).
287
- if (wsResolvedProtected.has(normSym)) {
288
- return {
289
- symbol: p.symbol,
290
- side: p.side,
291
- contracts: p.contracts,
292
- entry_price: p.entryPrice,
293
- mark_price: p.markPrice,
294
- has_stop: true,
295
- has_target: ledgerRow?.targetPrice !== undefined,
296
- stop_price: ledgerRow?.stopPrice,
297
- target_price: ledgerRow?.targetPrice,
298
- ledger_state: ledgerRow?.state ?? 'no_ledger_row',
299
- reason: 'bracket_active',
300
- recommended_action: 'none',
301
- };
302
- }
303
- // Classify each open order on the symbol: bracket SL, bracket TP,
304
- // manual SL (non-bracket STOP_MARKET), manual TP (non-bracket TAKE_PROFIT_MARKET).
305
- let hasBracketStop = false;
306
- let hasBracketTarget = false;
307
- let hasManualStop = false;
308
- let hasManualTarget = false;
309
- let stopPrice;
310
- let targetPrice;
311
- for (const o of symbolOrders) {
312
- const parsed = o.clientOrderId ? parseBracketCid(o.clientOrderId) : null;
313
- const triggerPrice = extractTriggerPrice(o);
314
- if (parsed && parsed.role === 'stop') {
315
- hasBracketStop = true;
316
- stopPrice = triggerPrice ?? stopPrice;
317
- }
318
- else if (parsed && parsed.role === 'target') {
319
- hasBracketTarget = true;
320
- targetPrice = triggerPrice ?? targetPrice;
321
- }
322
- else {
323
- // Prefer Binance's authoritative `orderType` field on the algo
324
- // response (preserved in `info` by binance-private.ts). This
325
- // catches externally-placed stops — manual SL via Binance UI —
326
- // which parseBracketCid can't recognize since they have no
327
- // `rc-*-s/t` CID. The string heuristic on top-level `type`
328
- // remains as a secondary signal for legacy / non-algo paths
329
- // where `info` may be absent.
330
- // Spec: https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Current-All-Algo-Open-Orders
331
- const infoOrderType = String(o.info?.orderType ?? '').toUpperCase();
332
- const type = (o.type ?? '').toLowerCase();
333
- const isStopType = infoOrderType === 'STOP_MARKET' || infoOrderType === 'STOP' || infoOrderType === 'TRAILING_STOP_MARKET' ||
334
- (type.includes('stop') && !type.includes('take'));
335
- const isTargetType = infoOrderType === 'TAKE_PROFIT_MARKET' || infoOrderType === 'TAKE_PROFIT' ||
336
- type.includes('take_profit') || type.includes('take-profit') || type === 'take_profit_market';
337
- if (isStopType) {
338
- hasManualStop = true;
339
- stopPrice = triggerPrice ?? stopPrice;
340
- }
341
- else if (isTargetType) {
342
- hasManualTarget = true;
343
- targetPrice = triggerPrice ?? targetPrice;
344
- }
345
- }
346
- }
347
- const hasStop = hasBracketStop || hasManualStop;
348
- const hasTarget = hasBracketTarget || hasManualTarget;
349
- // Prefer ledger price when available — it's our intent, not a re-derived
350
- // exchange trigger value (which Binance may round).
351
- if (ledgerRow?.stopPrice !== undefined)
352
- stopPrice = ledgerRow.stopPrice;
353
- if (ledgerRow?.targetPrice !== undefined)
354
- targetPrice = ledgerRow.targetPrice;
355
- const ledgerState = ledgerRow?.state ?? 'no_ledger_row';
356
- let reason;
357
- if (!bracketsEnabled) {
358
- reason = 'brackets_disabled';
359
- }
360
- else if (hasStop || hasTarget) {
361
- reason = hasBracketStop || hasBracketTarget ? 'bracket_active' : 'manual_order_protecting';
362
- }
363
- else if (ledgerRow && (ledgerRow.state === 'active' || ledgerRow.state === 'partial' || ledgerRow.state === 'attaching')) {
364
- reason = 'stale_ledger_row';
365
- }
366
- else if (ledgerRow && isTerminalState(ledgerRow.state)) {
367
- reason = 'ledger_terminal_no_order';
368
- }
369
- else {
370
- reason = 'no_protective_order';
371
- }
372
- let recommended_action = 'none';
373
- if (!bracketsEnabled)
374
- recommended_action = 'enable_brackets_mode';
375
- else if (!hasStop)
376
- recommended_action = 'attach_brackets';
377
- return {
378
- symbol: p.symbol,
379
- side: p.side,
380
- contracts: p.contracts,
381
- entry_price: p.entryPrice,
382
- mark_price: p.markPrice,
383
- has_stop: hasStop,
384
- has_target: hasTarget,
385
- stop_price: stopPrice,
386
- target_price: targetPrice,
387
- ledger_state: ledgerState,
388
- reason,
389
- recommended_action,
390
- };
391
- });
392
- const unprotected = entries.filter(e => !e.has_stop).length;
393
- // Flicker detection — runs after every audit pass. Cheap (a few map ops
394
- // per open position) and only emits log when the threshold trips.
395
- const nowTs = Date.now();
396
- for (const e of entries) {
397
- recordVerdictAndCheckFlicker(normalizeBracketSymbol(e.symbol), e.has_stop, nowTs);
398
- }
399
- // Diagnostic: when we conclude a live position is unprotected, dump the
400
- // raw openOrders shape for that symbol so post-mortems can tell whether
401
- // (a) exchange genuinely had no stop/TP, (b) CCXT returned them but the
402
- // cid/type didn't parse, or (c) the orders came back under a different
403
- // symbol key than the position. This is the other half of the bug the
404
- // 2026-04-21 close_position safeguard catches — we want to see WHY the
405
- // audit said false, not just catch the symptom.
406
- for (const e of entries) {
407
- if (e.has_stop)
408
- continue;
409
- const normSym = normalizeBracketSymbol(e.symbol);
410
- const raw = ordersBySymbol.get(normSym) ?? [];
411
- const orderSnapshot = raw.map(o => ({
412
- id: o.id,
413
- cid: o.clientOrderId ?? null,
414
- type: o.type ?? null,
415
- side: o.side ?? null,
416
- reduceOnly: o.reduceOnly ?? null,
417
- stopPrice: extractTriggerPrice(o) ?? null,
418
- infoType: o.info
419
- ? (o.info.type ?? null)
420
- : null,
421
- symbol: o.symbol ?? null,
422
- }));
423
- const allSymbols = Array.from(ordersBySymbol.keys());
424
- logger.warn(TAG, `unprotected verdict for ${e.symbol} (norm=${normSym}): has_stop=${e.has_stop} ` +
425
- `has_target=${e.has_target} reason=${e.reason} ledger=${e.ledger_state}. ` +
426
- `openOrders keyed under ${normSym}: ${orderSnapshot.length} ` +
427
- `(all symbol keys in map: ${JSON.stringify(allSymbols)}). ` +
428
- `orders=${JSON.stringify(orderSnapshot)}`);
429
- }
430
- return {
431
- ok: true,
432
- mode: 'live',
433
- brackets_enabled: bracketsEnabled,
434
- total_positions: entries.length,
435
- protected_count: entries.length - unprotected,
436
- unprotected_count: unprotected,
437
- positions: entries,
438
- };
439
- }
440
- catch (err) {
441
- logger.error(TAG, `audit failed: ${formatError(err)}`);
442
- return { error: `audit_bracket_protection failed: ${formatError(err)}` };
443
- }
444
- }
445
- function isTerminalState(s) {
446
- return s === 'cancelled' || s === 'failed' || s === 'triggered_sl' || s === 'triggered_tp';
447
- }
448
- /** Append a verdict sample for the symbol and emit a flicker warn when the
449
- * recent history shows ≥ FLICKER_THRESHOLD verdict transitions (true↔false)
450
- * inside FLICKER_WINDOW_MS. Trims the history to retention bounds. */
451
- function recordVerdictAndCheckFlicker(symbol, isProtected, nowTs) {
452
- const history = verdictHistory.get(symbol) ?? [];
453
- history.push({ ts: nowTs, protected: isProtected });
454
- // Trim by both age and length.
455
- const cutoff = nowTs - HISTORY_RETENTION_MS;
456
- while (history.length > 0 && history[0].ts < cutoff)
457
- history.shift();
458
- while (history.length > HISTORY_MAX_PER_SYMBOL)
459
- history.shift();
460
- verdictHistory.set(symbol, history);
461
- // Count verdict transitions inside the flicker window.
462
- const windowStart = nowTs - FLICKER_WINDOW_MS;
463
- let transitions = 0;
464
- let prev;
465
- for (const sample of history) {
466
- if (sample.ts < windowStart)
467
- continue;
468
- if (prev !== undefined && prev !== sample.protected)
469
- transitions++;
470
- prev = sample.protected;
471
- }
472
- if (transitions < FLICKER_THRESHOLD)
473
- return;
474
- const lastWarned = lastFlickerWarnedAt.get(symbol) ?? 0;
475
- if (nowTs - lastWarned < FLICKER_WARN_COOLDOWN_MS)
476
- return;
477
- lastFlickerWarnedAt.set(symbol, nowTs);
478
- logger.warn(TAG, `AUDIT FLICKER on ${symbol}: ${transitions} protected↔unprotected transitions ` +
479
- `in the last ${FLICKER_WINDOW_MS / 60_000} min. ` +
480
- `Bracket subsystem is reading exchange state inconsistently. ` +
481
- `Suspect transient fetchOpenOrders gaps, attach_brackets re-entry races, or ` +
482
- `CCXT symbol-form drift. Operator should investigate BEFORE the agent escalates ` +
483
- `to close_position(reason='bracket_integrity'). ` +
484
- `Recent samples: ${history.slice(-6).map(s => `${new Date(s.ts).toISOString().slice(11, 19)}:${s.protected ? 'P' : 'U'}`).join(' ')}`);
485
- }
486
- /** Public getter — returns the recent audit verdict samples for a symbol so
487
- * close_position can copy them into the position's close record for the
488
- * dashboard Position Timeline drawer. Read-only snapshot; mutating the
489
- * return value does not affect internal state. */
490
- export function getRecentAuditVerdictHistory(symbol) {
491
- const history = verdictHistory.get(normalizeBracketSymbol(symbol)) ?? [];
492
- // Defensive copy so callers can't mutate the live buffer.
493
- return history.map(s => ({ ts: s.ts, protected: s.protected }));
494
- }
495
- /** Test seam — clears the in-memory flicker history between unit tests. */
496
- export const __testing__ = {
497
- resetFlickerHistory() {
498
- verdictHistory.clear();
499
- lastFlickerWarnedAt = new Map();
500
- },
501
- /** Inspect current history for a symbol — used by tests to assert state. */
502
- getHistory(symbol) {
503
- return verdictHistory.get(normalizeBracketSymbol(symbol)) ?? [];
504
- },
505
- };
506
- // CCXT returns STOP_MARKET / TAKE_PROFIT_MARKET trigger prices in one of a
507
- // few spots depending on version + exchange. Check the most common ones.
508
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
509
- function extractTriggerPrice(o) {
510
- const candidates = [
511
- o?.stopPrice,
512
- o?.triggerPrice,
513
- o?.info?.stopPrice,
514
- o?.info?.triggerPrice,
515
- o?.params?.stopPrice,
516
- ];
517
- for (const c of candidates) {
518
- if (typeof c === 'number' && Number.isFinite(c) && c > 0)
519
- return c;
520
- if (typeof c === 'string') {
521
- const n = Number(c);
522
- if (Number.isFinite(n) && n > 0)
523
- return n;
524
- }
525
- }
526
- return undefined;
527
- }
@@ -1,9 +0,0 @@
1
- import type { IExchangeAdapter } from '../exchange-adapter.js';
2
- import type { TradingOperationLock } from '../lifecycle/trading-operation-lock.js';
3
- import type { CcxtOrder } from '../types.js';
4
- export declare function cancelAllOrdersTool(args: {
5
- symbol?: string;
6
- }, deps: {
7
- adapter: IExchangeAdapter;
8
- operationLock?: TradingOperationLock;
9
- }): Promise<CcxtOrder[]>;
@@ -1,8 +0,0 @@
1
- // Tool: cancel_all_orders — cancel all open orders (paper or live)
2
- // NO readiness gate — emergency control (kill switch), must always work.
3
- export async function cancelAllOrdersTool(args, deps) {
4
- const cancel = () => deps.adapter.cancelAllOrders(args.symbol);
5
- return deps.adapter.isLive && deps.operationLock
6
- ? deps.operationLock.withAccountLock(`generic-cancel-all-orders-final:${args.symbol ?? 'all'}`, cancel)
7
- : cancel();
8
- }
@@ -1,14 +0,0 @@
1
- import type { IExchangeAdapter } from '../exchange-adapter.js';
2
- import type { TradingOperationLock } from '../lifecycle/trading-operation-lock.js';
3
- import type { CcxtOrder } from '../types.js';
4
- import type { Wave9LiveSymbolOwnershipCheck } from '../wave9/live-symbol-ownership.js';
5
- export declare function cancelOrderTool(args: {
6
- id: string;
7
- symbol?: string;
8
- }, deps: {
9
- adapter: IExchangeAdapter;
10
- operationLock?: TradingOperationLock;
11
- checkWave9LiveSymbolOwnership?: Wave9LiveSymbolOwnershipCheck;
12
- }): Promise<CcxtOrder | {
13
- error: string;
14
- }>;
@@ -1,60 +0,0 @@
1
- // Tool: cancel_order — cancel a single order (paper or live).
2
- // There is no readiness gate, but LIVE cancellation cannot individually strip
3
- // candidate-bound Wave 9 protection. The emergency escape is an explicit
4
- // operator close, which reduces exposure instead of leaving it naked.
5
- import { formatError } from '../logger.js';
6
- export async function cancelOrderTool(args, deps) {
7
- if (!args.id) {
8
- return { error: 'Order ID is required.' };
9
- }
10
- if (!deps.adapter.isLive) {
11
- try {
12
- return await deps.adapter.cancelOrder(args.id, args.symbol);
13
- }
14
- catch (err) {
15
- return { error: formatError(err) };
16
- }
17
- }
18
- if (deps.checkWave9LiveSymbolOwnership && !deps.operationLock) {
19
- return {
20
- error: 'Live cancel_order refused: the shared trading operation lock is required ' +
21
- 'while Wave 9 LIVE ownership checks are enabled.',
22
- };
23
- }
24
- const cancelLive = async () => {
25
- let symbol = args.symbol?.trim();
26
- if (!symbol) {
27
- const matches = (await deps.adapter.getOpenOrders())
28
- .filter((order) => order.id === args.id);
29
- if (matches.length !== 1 || !matches[0].symbol) {
30
- throw new Error(`cancel_order refused: order ${args.id} could not be resolved to exactly one ` +
31
- `trusted open-order symbol (matches=${matches.length}).`);
32
- }
33
- symbol = matches[0].symbol;
34
- }
35
- if (deps.checkWave9LiveSymbolOwnership) {
36
- let ownership;
37
- try {
38
- ownership = await deps.checkWave9LiveSymbolOwnership(symbol);
39
- }
40
- catch (err) {
41
- throw new Error(`cancel_order refused at mutation boundary: Wave 9 LIVE ownership check failed ` +
42
- `for ${symbol} (${formatError(err)}).`);
43
- }
44
- if (ownership.status === 'owned' || ownership.status === 'ambiguous') {
45
- throw new Error(`cancel_order refused at mutation boundary: ${symbol} has ` +
46
- `${ownership.status} Wave 9 LIVE ownership (${ownership.reason}). ` +
47
- 'Use operator_command to close the position instead of stripping candidate-bound protection.');
48
- }
49
- }
50
- return deps.adapter.cancelOrder(args.id, symbol);
51
- };
52
- try {
53
- return deps.operationLock
54
- ? await deps.operationLock.withAccountLock(`generic-cancel-order-final:${args.id}`, cancelLive)
55
- : await cancelLive();
56
- }
57
- catch (err) {
58
- return { error: formatError(err) };
59
- }
60
- }
@@ -1,46 +0,0 @@
1
- interface PositionInput {
2
- symbol: string;
3
- side: 'LONG' | 'SHORT';
4
- entry_price: number;
5
- current_price: number;
6
- stop_price: number;
7
- target_price?: number;
8
- quantity: number;
9
- entry_time: string;
10
- }
11
- interface CheckHealthArgs {
12
- positions: PositionInput[];
13
- account_balance: number;
14
- }
15
- interface PositionHealth {
16
- symbol: string;
17
- side: string;
18
- pnl: number;
19
- pnlPercent: number;
20
- pnlR: number;
21
- distanceToStopPercent: number;
22
- distanceToStopR: number;
23
- stopStatus: 'SAFE' | 'CLOSE' | 'CRITICAL' | 'BREACHED';
24
- distanceToTargetPercent: number | null;
25
- distanceToTargetR: number | null;
26
- targetReached: boolean;
27
- heatPercent: number;
28
- notionalPercent: number;
29
- timeInTradeMinutes: number;
30
- timeInTradeFormatted: string;
31
- timeStatus: 'FRESH' | 'NORMAL' | 'EXTENDED' | 'STALE';
32
- alerts: string[];
33
- }
34
- interface HealthSummary {
35
- positions: PositionHealth[];
36
- portfolio: {
37
- totalHeat: number;
38
- totalNotional: number;
39
- totalPnl: number;
40
- positionCount: number;
41
- heatStatus: 'LOW' | 'MODERATE' | 'ELEVATED' | 'HIGH' | 'CRITICAL';
42
- alerts: string[];
43
- };
44
- }
45
- export declare function checkPositionHealthTool(args: CheckHealthArgs): HealthSummary;
46
- export {};