@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,345 +0,0 @@
1
- // Pre-trade risk gate — pure function.
2
- // Validates a proposed order against portfolio limits, drawdown zones, and volatility.
3
- // Lives in the plugin (synchronous access to simulator state).
4
- import { getCachedTradingParams } from '../trading-params-cache.js';
5
- // ---- Default pre-trade limits (now read from trading params cache) ----
6
- export function getDefaultPreTradeLimits() {
7
- const tp = getCachedTradingParams();
8
- return {
9
- maxPositionSize: tp.maxPositionSize,
10
- maxOpenPositions: tp.maxOpenPositions,
11
- maxGrossExposure: tp.maxGrossExposure,
12
- maxPerTradeLoss: tp.maxPerTradeLoss,
13
- };
14
- }
15
- /** @deprecated Use getDefaultPreTradeLimits() for dynamic values */
16
- export const DEFAULT_PRE_TRADE_LIMITS = {
17
- maxPositionSize: 10_000,
18
- maxOpenPositions: 5,
19
- maxGrossExposure: 1.5,
20
- maxPerTradeLoss: 500,
21
- };
22
- // ---- Drawdown zone thresholds (now read from trading params cache) ----
23
- export function getDrawdownThresholds() {
24
- const tp = getCachedTradingParams();
25
- return {
26
- YELLOW: tp.drawdownYellow,
27
- ORANGE: tp.drawdownOrange,
28
- RED: tp.drawdownRed,
29
- };
30
- }
31
- export const DRAWDOWN_ZONE_THRESHOLDS = {
32
- YELLOW: -0.01, // -1%
33
- ORANGE: -0.02, // -2%
34
- RED: -0.025, // -2.5%
35
- };
36
- // ---- Pure helpers ----
37
- /** Determine drawdown zone from drawdown ratio (e.g. -0.015 = -1.5%). */
38
- export function getDrawdownZone(drawdownRatio) {
39
- const thresholds = getDrawdownThresholds();
40
- if (drawdownRatio <= thresholds.RED)
41
- return 'RED';
42
- if (drawdownRatio <= thresholds.ORANGE)
43
- return 'ORANGE';
44
- if (drawdownRatio <= thresholds.YELLOW)
45
- return 'YELLOW';
46
- return 'GREEN';
47
- }
48
- /** Compute volatility factor from current ATR vs baseline. Clamped [0.5, 3.0]. */
49
- export function computeVolFactor(currentAtr, baselineAtr) {
50
- if (baselineAtr <= 0 || currentAtr <= 0)
51
- return 1.0;
52
- return Math.max(0.5, Math.min(3.0, currentAtr / baselineAtr));
53
- }
54
- /** Adjust a limit value by volatility factor. Higher vol = tighter limit. */
55
- export function adjustLimitByVol(defaultLimit, volFactor) {
56
- if (volFactor <= 1.0)
57
- return defaultLimit;
58
- return defaultLimit / volFactor;
59
- }
60
- /** Check if an order is closing an existing position (partial or full). */
61
- export function isClosingOrder(order, positions) {
62
- const pos = positions.find(p => p.symbol === order.symbol);
63
- if (!pos)
64
- return false;
65
- // Sell against a long = closing; buy against a short = closing
66
- return (pos.side === 'long' && order.side === 'sell') ||
67
- (pos.side === 'short' && order.side === 'buy');
68
- }
69
- // ---- Main pre-trade gate ----
70
- // ---- Equity-proportional floors (safety net for tiny accounts) ----
71
- // These are independent of the configurable trading params and exist so that
72
- // a $10,000 static `maxPositionSize` default can't allow a $289 account to
73
- // open an $8,000 position. They shrink the effective caps relative to current
74
- // equity; the tighter of (absolute limit, equity-proportional floor) wins.
75
- export const EQUITY_FLOOR = {
76
- /** Max single-position notional as a fraction of equity.
77
- * Raised 0.25 → 0.40 on 2026-04-20 so small live accounts ($186) can fit
78
- * BTC's ~$75 min-lot. Still protects against all-in entries. Tracked for
79
- * promotion to operator-configurable trading param in the next session. */
80
- MAX_POSITION_PCT: 0.40,
81
- /** Max per-trade risk (expected loss) as a fraction of equity. */
82
- MAX_PER_TRADE_LOSS_PCT: 0.02,
83
- /** Presumed adverse move when an order has no explicit stopPrice. */
84
- NO_STOP_ASSUMED_ADVERSE: 0.05,
85
- };
86
- export function preTradeRiskCheck(order, portfolio, limits = DEFAULT_PRE_TRADE_LIMITS, options = {}) {
87
- const violations = [];
88
- const volFactor = options.volFactor ?? 1.0;
89
- // Caller-provided equity is authoritative; fall back to local compute for
90
- // legacy test callers that don't supply it.
91
- const currentEquity = portfolio.equity ?? computePortfolioEquity(portfolio);
92
- // Drawdown anchor: prefer sessionStartNav, fall back to current equity.
93
- const nav = portfolio.sessionStartNav > 0 ? portfolio.sessionStartNav : currentEquity;
94
- const drawdownRatio = nav > 0 ? (currentEquity - nav) / nav : 0;
95
- const zone = getDrawdownZone(drawdownRatio);
96
- // Classify the order against any same-symbol position BEFORE the zone gates:
97
- // - pure reduce / full close → "closing": exempt from entry gates (exits
98
- // must always work, even in RED/ORANGE).
99
- // - flip (over-close) → closes the old leg AND opens a NEW opposite
100
- // leg; the NEW leg must clear every entry gate (drawdown zone, size,
101
- // gross, per-trade-loss, bracket requirement). Previously a flip took the
102
- // exit exemption and opened unchecked, possibly oversized, stop-less
103
- // exposure — even in the RED zone (M6).
104
- // - same-direction add (scale-in) / fresh entry → full entry checks (M5).
105
- // Emergency flatten bypasses this function entirely (EmergencyControls → adapter.createOrder).
106
- const closingPos = portfolio.positions.find(p => p.symbol === order.symbol &&
107
- ((p.side === 'long' && order.side === 'sell') || (p.side === 'short' && order.side === 'buy')));
108
- const flipAmount = closingPos ? order.amount - closingPos.quantity : 0;
109
- const isFlip = closingPos != null && flipAmount > 1e-9 * Math.max(closingPos.quantity, 1);
110
- const closing = closingPos != null && !isFlip; // reduce/close, opens no new exposure
111
- // The leg that opens new exposure and must clear the entry gates. For a flip
112
- // it's ONLY the excess beyond the closed position; otherwise the whole order.
113
- // stopPrice/targetPrice carry over so the per-trade-loss and live
114
- // bracket-requirement gates evaluate against the new leg's real stop.
115
- const entryOrder = isFlip ? { ...order, amount: flipAmount } : order;
116
- // Bracket requirement gates — only apply to entries (not closes) when the
117
- // caller explicitly passes `bracketEnforcement`. Closes are exempt so
118
- // operators can always exit, even if the entry broke the policy.
119
- if (!closing && options.bracketEnforcement) {
120
- const { requireStopLoss, requireTakeProfit } = options.bracketEnforcement;
121
- if (requireStopLoss && (order.stopPrice === undefined || !(order.stopPrice > 0))) {
122
- violations.push({
123
- rule: 'requireStopLoss',
124
- message: 'Live trades require a stopPrice. Disable requireStopLoss in Trading Parameters to override (not recommended).',
125
- current: 0,
126
- limit: 1,
127
- });
128
- }
129
- if (requireTakeProfit && (order.targetPrice === undefined || !(order.targetPrice > 0))) {
130
- violations.push({
131
- rule: 'requireTakeProfit',
132
- message: 'Live trades require a target_price. Disable requireTakeProfit in Trading Parameters to override.',
133
- current: 0,
134
- limit: 1,
135
- });
136
- }
137
- if (violations.length > 0) {
138
- return {
139
- allowed: false,
140
- violations,
141
- drawdownZone: zone,
142
- effectiveMaxPositionSize: 0,
143
- };
144
- }
145
- }
146
- // Exits are always allowed regardless of drawdown zone
147
- if (closing) {
148
- const effectiveMax = computeEffectivePositionSize(limits.maxPositionSize, volFactor, zone);
149
- return {
150
- allowed: true,
151
- violations: [],
152
- drawdownZone: zone,
153
- effectiveMaxPositionSize: effectiveMax,
154
- };
155
- }
156
- // RED zone: reject new entries (exits already handled above)
157
- if (zone === 'RED') {
158
- violations.push({
159
- rule: 'drawdownZone',
160
- message: `RED zone (${(drawdownRatio * 100).toFixed(2)}% drawdown) — new entries rejected`,
161
- current: drawdownRatio,
162
- limit: DRAWDOWN_ZONE_THRESHOLDS.RED,
163
- });
164
- return {
165
- allowed: false,
166
- violations,
167
- drawdownZone: zone,
168
- effectiveMaxPositionSize: 0,
169
- };
170
- }
171
- // ORANGE zone: only exits allowed (already handled above)
172
- if (zone === 'ORANGE') {
173
- violations.push({
174
- rule: 'drawdownZone',
175
- message: `ORANGE zone (${(drawdownRatio * 100).toFixed(2)}% drawdown) — new entries blocked, exits only`,
176
- current: drawdownRatio,
177
- limit: DRAWDOWN_ZONE_THRESHOLDS.ORANGE,
178
- });
179
- return {
180
- allowed: false,
181
- violations,
182
- drawdownZone: zone,
183
- effectiveMaxPositionSize: 0,
184
- };
185
- }
186
- // ---- Entry checks (GREEN/YELLOW) ----
187
- const streak = options.consecutiveLosses ?? 0;
188
- const tp = getCachedTradingParams();
189
- // Equity-proportional floor — shrinks the static cap on small accounts.
190
- // A $10k default `maxPositionSize` is useless on a $289 account; cap to
191
- // `EQUITY_FLOOR.MAX_POSITION_PCT` of current equity. The tighter of the two wins.
192
- const equityPositionCap = currentEquity > 0
193
- ? currentEquity * EQUITY_FLOOR.MAX_POSITION_PCT
194
- : limits.maxPositionSize;
195
- const scaledMaxPositionSize = Math.min(limits.maxPositionSize, equityPositionCap);
196
- let effectiveMaxPositionSize = computeEffectivePositionSize(scaledMaxPositionSize, volFactor, zone);
197
- // Graduated size reduction on loss streaks (never a hard block — that creates deadlocks)
198
- // Ensure correct ordering: the harsher reduction (0.25x) needs the higher threshold
199
- const quarterThreshold = Math.max(tp.lossStreakQuarterSize, tp.lossStreakHalfSize);
200
- const halfThreshold = Math.min(tp.lossStreakQuarterSize, tp.lossStreakHalfSize);
201
- if (streak >= quarterThreshold) {
202
- effectiveMaxPositionSize *= 0.25;
203
- }
204
- else if (streak >= halfThreshold) {
205
- effectiveMaxPositionSize *= 0.5;
206
- }
207
- // 1. Position size check — against the RESULTING position notional, not just
208
- // this order's increment. A same-direction scale-in must include the
209
- // existing leg, or repeated small adds each pass individually yet build a
210
- // position far beyond the per-symbol cap (M5). A flip's resulting position
211
- // is only the new opposite leg (the old leg is closed), so the existing
212
- // notional is NOT added there.
213
- const entryNotional = entryOrder.amount * order.price;
214
- const sameSymbolPos = portfolio.positions.find(p => p.symbol === order.symbol);
215
- const isScaleIn = sameSymbolPos != null &&
216
- ((sameSymbolPos.side === 'long' && order.side === 'buy') ||
217
- (sameSymbolPos.side === 'short' && order.side === 'sell'));
218
- const existingNotional = isScaleIn && sameSymbolPos
219
- ? sameSymbolPos.quantity * (sameSymbolPos.markPrice ?? sameSymbolPos.entryPrice)
220
- : 0;
221
- const resultingNotional = existingNotional + entryNotional;
222
- if (resultingNotional > effectiveMaxPositionSize) {
223
- violations.push({
224
- rule: 'positionSize',
225
- message: `Resulting position notional $${resultingNotional.toFixed(2)} (existing $${existingNotional.toFixed(2)} + order $${entryNotional.toFixed(2)}) exceeds effective max $${effectiveMaxPositionSize.toFixed(2)} (equity $${currentEquity.toFixed(2)}, cap ${(EQUITY_FLOOR.MAX_POSITION_PCT * 100).toFixed(0)}% of equity)`,
226
- current: resultingNotional,
227
- limit: effectiveMaxPositionSize,
228
- });
229
- }
230
- // 2. Open positions count (would a new symbol exceed limit?)
231
- const existingSymbols = new Set(portfolio.positions.map(p => p.symbol));
232
- if (!existingSymbols.has(order.symbol)) {
233
- const newCount = existingSymbols.size + 1;
234
- if (newCount > limits.maxOpenPositions) {
235
- violations.push({
236
- rule: 'openPositions',
237
- message: `New position would bring count to ${newCount}, max is ${limits.maxOpenPositions}`,
238
- current: newCount,
239
- limit: limits.maxOpenPositions,
240
- });
241
- }
242
- }
243
- // 3. Projected gross exposure. On a flip the closed leg leaves the book, so
244
- // net it out — otherwise the projection double-counts the position we close.
245
- if (nav > 0) {
246
- const currentGross = computeGrossExposure(portfolio);
247
- const closedLegNotional = isFlip && closingPos
248
- ? closingPos.quantity * (closingPos.markPrice ?? closingPos.entryPrice)
249
- : 0;
250
- const projectedGross = currentGross - closedLegNotional + entryNotional;
251
- const projectedRatio = projectedGross / nav;
252
- const effectiveMaxGross = adjustLimitByVol(limits.maxGrossExposure, volFactor);
253
- if (projectedRatio > effectiveMaxGross) {
254
- violations.push({
255
- rule: 'grossExposure',
256
- message: `Projected gross exposure ${projectedRatio.toFixed(2)}x exceeds limit ${effectiveMaxGross.toFixed(2)}x`,
257
- current: projectedRatio,
258
- limit: effectiveMaxGross,
259
- });
260
- }
261
- }
262
- // 4. Per-trade loss check — MANDATORY (was previously opt-in on stopPrice).
263
- // Without a stop, we presume a 5% adverse move as the worst-case loss. This
264
- // prevents the gate from waving through stopless entries on thin accounts.
265
- if (!closing) {
266
- // Use the opening leg's amount/notional (the flip's new leg, or the whole
267
- // order for a fresh entry/scale-in) so the flip's new exposure is gated.
268
- const expectedLoss = order.stopPrice != null
269
- ? Math.abs(order.price - order.stopPrice) * entryOrder.amount
270
- : entryNotional * EQUITY_FLOOR.NO_STOP_ASSUMED_ADVERSE;
271
- const equityLossCap = currentEquity > 0
272
- ? currentEquity * EQUITY_FLOOR.MAX_PER_TRADE_LOSS_PCT
273
- : limits.maxPerTradeLoss;
274
- const scaledPerTradeLoss = Math.min(limits.maxPerTradeLoss, equityLossCap);
275
- if (expectedLoss > scaledPerTradeLoss) {
276
- const stopNote = order.stopPrice != null
277
- ? `stop @ ${order.stopPrice}`
278
- : `no stop — assumed ${(EQUITY_FLOOR.NO_STOP_ASSUMED_ADVERSE * 100).toFixed(0)}% adverse move`;
279
- violations.push({
280
- rule: 'perTradeLoss',
281
- message: `Expected loss $${expectedLoss.toFixed(2)} (${stopNote}) exceeds per-trade limit $${scaledPerTradeLoss.toFixed(2)} (${(EQUITY_FLOOR.MAX_PER_TRADE_LOSS_PCT * 100).toFixed(0)}% of equity $${currentEquity.toFixed(2)})`,
282
- current: expectedLoss,
283
- limit: scaledPerTradeLoss,
284
- });
285
- }
286
- }
287
- return {
288
- allowed: violations.length === 0,
289
- violations,
290
- drawdownZone: zone,
291
- effectiveMaxPositionSize,
292
- };
293
- }
294
- // ---- Exported helpers ----
295
- /** Count consecutive losses from the end of a trade history array. */
296
- export function computeConsecutiveLosses(trades) {
297
- let streak = 0;
298
- for (let i = trades.length - 1; i >= 0; i--) {
299
- if (trades[i].realizedPnl < 0) {
300
- streak++;
301
- }
302
- else {
303
- break;
304
- }
305
- }
306
- return streak;
307
- }
308
- // ---- Internal helpers ----
309
- function computeEffectivePositionSize(baseMax, volFactor, zone) {
310
- let effective = adjustLimitByVol(baseMax, volFactor);
311
- if (zone === 'YELLOW') {
312
- effective *= 0.5; // YELLOW halves position sizes
313
- }
314
- return effective;
315
- }
316
- function computePortfolioEquity(portfolio) {
317
- let equity = portfolio.walletTotal;
318
- for (const pos of portfolio.positions) {
319
- const mark = pos.markPrice ?? pos.entryPrice;
320
- const pnl = pos.side === 'long'
321
- ? (mark - pos.entryPrice) * pos.quantity
322
- : (pos.entryPrice - mark) * pos.quantity;
323
- if (portfolio.isLive) {
324
- // Live Binance: wallet already includes margin — add only unrealized P&L.
325
- equity += pnl;
326
- }
327
- else {
328
- // Paper simulator (SPOT-collateral model): the full entry notional was
329
- // deducted from wallet at open and is released on close, so we must add
330
- // it back here. Same formula for longs and shorts — the previous
331
- // `-qty*mark` short branch was arithmetically wrong and underrepresented
332
- // equity by 2*entry*qty whenever the account held a short.
333
- equity += pos.entryPrice * pos.quantity + pnl;
334
- }
335
- }
336
- return equity;
337
- }
338
- function computeGrossExposure(portfolio) {
339
- let gross = 0;
340
- for (const pos of portfolio.positions) {
341
- const price = pos.markPrice ?? pos.entryPrice;
342
- gross += Math.abs(pos.quantity * price);
343
- }
344
- return gross;
345
- }
@@ -1,60 +0,0 @@
1
- export type DrawdownZone = 'GREEN' | 'YELLOW' | 'ORANGE' | 'RED';
2
- export interface PreTradeRiskLimits {
3
- maxPositionSize: number;
4
- maxOpenPositions: number;
5
- maxGrossExposure: number;
6
- maxPerTradeLoss: number;
7
- }
8
- export interface ProposedOrder {
9
- symbol: string;
10
- side: 'buy' | 'sell';
11
- type: 'market' | 'limit';
12
- amount: number;
13
- price: number;
14
- stopPrice?: number;
15
- targetPrice?: number;
16
- }
17
- export interface PortfolioSnapshot {
18
- positions: Array<{
19
- symbol: string;
20
- side: 'long' | 'short';
21
- quantity: number;
22
- entryPrice: number;
23
- markPrice?: number;
24
- }>;
25
- walletTotal: number;
26
- walletAvailable: number;
27
- sessionStartNav: number;
28
- /** Mark-to-market total account value. If provided, takes precedence over
29
- * the gate's own equity computation — the caller's value is authoritative
30
- * because it has access to the real simulator/exchange state. When absent
31
- * (legacy test callers), the gate falls back to an internal computation. */
32
- equity?: number;
33
- /** Paper simulator deducts notional from wallet at entry — equity = wallet + position value.
34
- * Live Binance wallet already includes margin — equity = wallet + unrealized PnL only. */
35
- isLive?: boolean;
36
- }
37
- export interface PreTradeViolation {
38
- rule: string;
39
- message: string;
40
- current: number;
41
- limit: number;
42
- }
43
- export interface PreTradeResult {
44
- allowed: boolean;
45
- violations: PreTradeViolation[];
46
- drawdownZone: DrawdownZone;
47
- effectiveMaxPositionSize: number;
48
- }
49
- export interface PreTradeOptions {
50
- volFactor?: number;
51
- consecutiveLosses?: number;
52
- /** When true, the gate rejects entries without a stopPrice and/or targetPrice
53
- * based on the flags below. Only meaningful in live mode with bracket orders
54
- * enabled — in paper/off mode the stop-watcher handles protection and these
55
- * flags don't apply (gate ignores them). */
56
- bracketEnforcement?: {
57
- requireStopLoss: boolean;
58
- requireTakeProfit: boolean;
59
- };
60
- }
@@ -1,3 +0,0 @@
1
- // Pre-trade risk gate types.
2
- // Used by preTradeRiskCheck() to validate orders before they reach the simulator.
3
- export {};
@@ -1,36 +0,0 @@
1
- import { EventEmitter } from 'node:events';
2
- import type { BinancePrivateApi } from '../ccxt/binance-private.js';
3
- import type { ExchangeSimulator } from '../simulator/exchange-simulator.js';
4
- import type { ShadowComparison, ShadowMetrics, ShadowConfig } from './types.js';
5
- /**
6
- * ShadowTracker hooks into the ExchangeSimulator to compute
7
- * shadow estimates for every paper fill.
8
- *
9
- * Events emitted:
10
- * - 'shadowComparison': ShadowComparison — after each fill comparison
11
- */
12
- export declare class ShadowTracker extends EventEmitter {
13
- private privateApi;
14
- private simulator;
15
- private metrics;
16
- private config;
17
- private recentComparisons;
18
- private active;
19
- constructor(privateApi: BinancePrivateApi, simulator: ExchangeSimulator, config?: ShadowConfig, existingMetrics?: ShadowMetrics);
20
- /** Start listening for simulator fill events. */
21
- start(): void;
22
- /** Stop listening. */
23
- stop(): void;
24
- /** Get current shadow metrics. */
25
- getMetrics(): ShadowMetrics;
26
- /** Get recent comparisons. */
27
- getRecentComparisons(): ShadowComparison[];
28
- /** Check if shadow mode criteria are met for mode upgrade. */
29
- isReadyForUpgrade(): {
30
- ready: boolean;
31
- reasons: string[];
32
- };
33
- private onFill;
34
- private computeShadowComparison;
35
- private updateMetrics;
36
- }
@@ -1,151 +0,0 @@
1
- // Shadow Tracker — compares paper fills against live exchange estimates.
2
- // Listens for fill events from the simulator, fetches real order book,
3
- // computes what the live fill would have been, logs the comparison.
4
- import { EventEmitter } from 'node:events';
5
- import { logger } from '../logger.js';
6
- import { priceToBps } from '../simulator/types.js';
7
- import { computeBookAwareFillPrice } from '../simulator/realistic-fills.js';
8
- import { createEmptyShadowMetrics, DEFAULT_SHADOW_CONFIG } from './types.js';
9
- const TAG = 'shadow-tracker';
10
- /** Maximum recent comparisons to keep in memory. */
11
- const MAX_RECENT_COMPARISONS = 100;
12
- /**
13
- * ShadowTracker hooks into the ExchangeSimulator to compute
14
- * shadow estimates for every paper fill.
15
- *
16
- * Events emitted:
17
- * - 'shadowComparison': ShadowComparison — after each fill comparison
18
- */
19
- export class ShadowTracker extends EventEmitter {
20
- privateApi;
21
- simulator;
22
- metrics;
23
- config;
24
- recentComparisons = [];
25
- active = false;
26
- constructor(privateApi, simulator, config, existingMetrics) {
27
- super();
28
- this.privateApi = privateApi;
29
- this.simulator = simulator;
30
- this.config = config ?? DEFAULT_SHADOW_CONFIG;
31
- this.metrics = existingMetrics ?? createEmptyShadowMetrics();
32
- }
33
- /** Start listening for simulator fill events. */
34
- start() {
35
- if (this.active)
36
- return;
37
- this.active = true;
38
- this.simulator.on('fill', this.onFill);
39
- logger.info(TAG, `Shadow tracker started (${this.metrics.totalShadowTrades} prior comparisons)`);
40
- }
41
- /** Stop listening. */
42
- stop() {
43
- if (!this.active)
44
- return;
45
- this.active = false;
46
- this.simulator.off('fill', this.onFill);
47
- logger.info(TAG, 'Shadow tracker stopped');
48
- }
49
- /** Get current shadow metrics. */
50
- getMetrics() {
51
- return { ...this.metrics };
52
- }
53
- /** Get recent comparisons. */
54
- getRecentComparisons() {
55
- return [...this.recentComparisons];
56
- }
57
- /** Check if shadow mode criteria are met for mode upgrade. */
58
- isReadyForUpgrade() {
59
- const reasons = [];
60
- if (this.metrics.totalShadowTrades < this.config.minTrades) {
61
- reasons.push(`Need ${this.config.minTrades} shadow trades, have ${this.metrics.totalShadowTrades}`);
62
- }
63
- if (this.metrics.tradingDays < this.config.minDays) {
64
- reasons.push(`Need ${this.config.minDays} trading days, have ${this.metrics.tradingDays}`);
65
- }
66
- if (this.metrics.avgDeltaBps > this.config.maxAvgDeltaBps) {
67
- reasons.push(`Avg delta ${this.metrics.avgDeltaBps.toFixed(2)}bps exceeds max ${this.config.maxAvgDeltaBps}bps`);
68
- }
69
- return { ready: reasons.length === 0, reasons };
70
- }
71
- // Arrow function to preserve `this` binding when used as event listener
72
- onFill = (fillData) => {
73
- // Only compare market order fills (limit orders fill at limit price, no comparison needed)
74
- if (fillData.type !== 'market')
75
- return;
76
- // Fire and forget — shadow comparison is async but doesn't block the fill
77
- this.computeShadowComparison(fillData).catch(err => {
78
- logger.warn(TAG, `Shadow comparison failed: ${err instanceof Error ? err.message : String(err)}`);
79
- });
80
- };
81
- async computeShadowComparison(fillData) {
82
- // Fetch fresh order book from the exchange (authenticated path)
83
- const liveBook = await this.privateApi.fetchOrderBook(fillData.symbol, 20);
84
- let shadowPrice;
85
- let bookDepthUsed = 0;
86
- let bookDepthAvailable = false;
87
- if (liveBook && liveBook.asks.length > 0 && liveBook.bids.length > 0) {
88
- // Walk the live book to compute shadow VWAP
89
- const { vwap, levelsConsumed } = computeBookAwareFillPrice(fillData.side, fillData.amount, liveBook);
90
- shadowPrice = vwap;
91
- bookDepthUsed = levelsConsumed;
92
- bookDepthAvailable = true;
93
- }
94
- else {
95
- // No live book available — use paper fill as shadow estimate
96
- shadowPrice = fillData.fillPrice;
97
- logger.warn(TAG, `No live order book for ${fillData.symbol} — shadow estimate equals paper`);
98
- }
99
- // Compute shadow fee (same taker rate as paper for fair comparison)
100
- const simConfig = this.simulator.getSimulationConfig();
101
- const shadowFee = fillData.amount * shadowPrice * simConfig.fees.takerRate;
102
- // Delta: positive = live would be worse (pay more for buy, receive less for sell)
103
- const deltaBps = priceToBps(shadowPrice, fillData.fillPrice);
104
- const comparison = {
105
- orderId: fillData.orderId,
106
- symbol: fillData.symbol,
107
- side: fillData.side,
108
- type: fillData.type,
109
- amount: fillData.amount,
110
- paperFillPrice: fillData.fillPrice,
111
- shadowEstimatePrice: shadowPrice,
112
- deltaBps,
113
- paperFee: fillData.fee,
114
- shadowEstimateFee: shadowFee,
115
- bookDepthUsed,
116
- bookDepthAvailable,
117
- timestamp: new Date().toISOString(),
118
- };
119
- // Update metrics
120
- this.updateMetrics(comparison);
121
- // Store recent comparison (match webapp slice pattern — slice instead of shift)
122
- this.recentComparisons = [
123
- ...this.recentComparisons.slice(-(MAX_RECENT_COMPARISONS - 1)),
124
- comparison,
125
- ];
126
- // Emit event for skill/bridge pipeline
127
- this.emit('shadowComparison', comparison);
128
- logger.info(TAG, `Shadow comparison: ${fillData.side} ${fillData.amount} ${fillData.symbol}` +
129
- ` | Paper: ${fillData.fillPrice.toFixed(2)} | Shadow: ${shadowPrice.toFixed(2)}` +
130
- ` | Delta: ${deltaBps.toFixed(2)}bps` +
131
- ` | Book: ${bookDepthAvailable ? `${bookDepthUsed} levels` : 'unavailable'}`);
132
- }
133
- updateMetrics(comparison) {
134
- const m = this.metrics;
135
- m.totalShadowTrades++;
136
- const absDelta = Math.abs(comparison.deltaBps);
137
- m.totalDeltaBpsSum += absDelta;
138
- m.avgDeltaBps = m.totalDeltaBpsSum / m.totalShadowTrades;
139
- if (absDelta > m.worstDeltaBps) {
140
- m.worstDeltaBps = absDelta;
141
- }
142
- m.paperTotalFees += comparison.paperFee;
143
- m.shadowTotalFees += comparison.shadowEstimateFee;
144
- // Track trading days
145
- const today = comparison.timestamp.slice(0, 10);
146
- if (today !== m.lastTradeDate) {
147
- m.tradingDays++;
148
- m.lastTradeDate = today;
149
- }
150
- }
151
- }
@@ -1,42 +0,0 @@
1
- import type { TradingMode } from '../types.js';
2
- export type { TradingMode };
3
- /** A single shadow comparison record: paper fill vs live estimate. */
4
- export interface ShadowComparison {
5
- orderId: string;
6
- symbol: string;
7
- side: 'buy' | 'sell';
8
- type: 'market' | 'limit';
9
- amount: number;
10
- paperFillPrice: number;
11
- shadowEstimatePrice: number;
12
- deltaBps: number;
13
- paperFee: number;
14
- shadowEstimateFee: number;
15
- bookDepthUsed: number;
16
- bookDepthAvailable: boolean;
17
- timestamp: string;
18
- }
19
- /** Aggregate shadow metrics across all shadow comparisons. */
20
- export interface ShadowMetrics {
21
- totalShadowTrades: number;
22
- avgDeltaBps: number;
23
- worstDeltaBps: number;
24
- totalDeltaBpsSum: number;
25
- paperTotalFees: number;
26
- shadowTotalFees: number;
27
- startedAt: string;
28
- tradingDays: number;
29
- lastTradeDate: string;
30
- }
31
- /** Shadow mode configuration thresholds. */
32
- export interface ShadowConfig {
33
- /** Minimum shadow trades before allowing mode upgrade (default: 50) */
34
- minTrades: number;
35
- /** Minimum days in shadow mode (default: 7) */
36
- minDays: number;
37
- /** Max acceptable average delta in bps (default: 5) */
38
- maxAvgDeltaBps: number;
39
- }
40
- export declare const DEFAULT_SHADOW_CONFIG: ShadowConfig;
41
- /** Create empty shadow metrics. */
42
- export declare function createEmptyShadowMetrics(): ShadowMetrics;
@@ -1,20 +0,0 @@
1
- // Shadow mode types — tracking paper vs live fill comparison.
2
- export const DEFAULT_SHADOW_CONFIG = {
3
- minTrades: 50,
4
- minDays: 7,
5
- maxAvgDeltaBps: 5,
6
- };
7
- /** Create empty shadow metrics. */
8
- export function createEmptyShadowMetrics() {
9
- return {
10
- totalShadowTrades: 0,
11
- avgDeltaBps: 0,
12
- worstDeltaBps: 0,
13
- totalDeltaBpsSum: 0,
14
- paperTotalFees: 0,
15
- shadowTotalFees: 0,
16
- startedAt: new Date().toISOString(),
17
- tradingDays: 0,
18
- lastTradeDate: '',
19
- };
20
- }