dexbot 1.6.7 → 1.6.9

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 (626) hide show
  1. package/CHANGELOG.md +73 -1
  2. package/README.md +3 -3
  3. package/analysis/README.md +2 -3
  4. package/analysis/tradingview/README.md +78 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
  6. package/claw/package.json +1 -1
  7. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  8. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  9. package/dist/analysis/tradingview/analyze_tradingview.d.ts +4 -0
  10. package/dist/analysis/tradingview/analyze_tradingview.js +55 -0
  11. package/dist/analysis/tradingview/grid_reset_config.d.ts +61 -0
  12. package/dist/analysis/tradingview/grid_reset_config.js +235 -0
  13. package/dist/analysis/tradingview/grid_reset_sim.d.ts +67 -0
  14. package/dist/analysis/tradingview/grid_reset_sim.js +307 -0
  15. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +419 -3
  16. package/dist/dexbot.js +55 -16
  17. package/dist/market_adapter/core/market_adapter_service.d.ts +81 -1
  18. package/dist/market_adapter/core/market_adapter_service.js +239 -20
  19. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
  20. package/dist/market_adapter/core/signals/hurst_analyzer.js +40 -18
  21. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +26 -2
  22. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +132 -29
  23. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +8 -1
  24. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +5 -1
  25. package/dist/market_adapter/core/strategies/regime_gate.d.ts +61 -3
  26. package/dist/market_adapter/core/strategies/regime_gate.js +207 -7
  27. package/dist/market_adapter/inputs/window_cache.d.ts +97 -19
  28. package/dist/market_adapter/inputs/window_cache.js +302 -48
  29. package/dist/market_adapter/interval_utils.d.ts +18 -1
  30. package/dist/market_adapter/interval_utils.js +31 -1
  31. package/dist/market_adapter/market_adapter.d.ts +158 -2
  32. package/dist/market_adapter/market_adapter.js +399 -65
  33. package/dist/market_adapter/test_helpers.d.ts +2 -2
  34. package/dist/market_adapter/test_helpers.js +2 -2
  35. package/dist/market_adapter/utils/file_json_cache.d.ts +29 -0
  36. package/dist/market_adapter/utils/file_json_cache.js +106 -0
  37. package/dist/modules/account_bots.js +10 -0
  38. package/dist/modules/account_orders.d.ts +24 -2
  39. package/dist/modules/account_orders.js +41 -4
  40. package/dist/modules/bot_settings.js +10 -1
  41. package/dist/modules/config.d.ts +7 -0
  42. package/dist/modules/config.js +2 -0
  43. package/dist/modules/constants.d.ts +16 -4
  44. package/dist/modules/constants.js +144 -38
  45. package/dist/modules/dexbot_class.d.ts +6 -76
  46. package/dist/modules/dexbot_class.js +0 -32
  47. package/dist/modules/dexbot_cow_runtime.d.ts +3 -58
  48. package/dist/modules/dexbot_cow_runtime.js +4 -87
  49. package/dist/modules/dexbot_maintenance_runtime.d.ts +15 -1
  50. package/dist/modules/dexbot_maintenance_runtime.js +59 -11
  51. package/dist/modules/dexbot_startup_runtime.js +73 -20
  52. package/dist/modules/dexbot_state_recovery.d.ts +6 -0
  53. package/dist/modules/dexbot_state_recovery.js +21 -0
  54. package/dist/modules/order/async_lock.d.ts +8 -0
  55. package/dist/modules/order/async_lock.js +15 -0
  56. package/dist/modules/order/genesis_policy.d.ts +162 -0
  57. package/dist/modules/order/genesis_policy.js +267 -0
  58. package/dist/modules/order/grid.js +172 -160
  59. package/dist/modules/order/grid_reconcile.d.ts +9 -0
  60. package/dist/modules/order/grid_reconcile.js +13 -4
  61. package/dist/modules/order/grid_reconcile_internal.js +2 -2
  62. package/dist/modules/order/manager.d.ts +4 -0
  63. package/dist/modules/order/manager.js +14 -1
  64. package/dist/modules/order/sync_engine.d.ts +19 -0
  65. package/dist/modules/order/sync_engine.js +284 -344
  66. package/dist/modules/order/utils/math.d.ts +22 -1
  67. package/dist/modules/order/utils/math.js +64 -1
  68. package/dist/modules/order/utils/order.d.ts +43 -58
  69. package/dist/modules/order/utils/order.js +220 -197
  70. package/dist/modules/order/utils/system.js +8 -1
  71. package/dist/modules/paths.d.ts +1 -0
  72. package/dist/modules/paths.js +1 -0
  73. package/dist/modules/version_notice.d.ts +311 -0
  74. package/dist/modules/version_notice.js +709 -0
  75. package/dist/pm2.js +16 -0
  76. package/dist/unlock.js +28 -0
  77. package/docs/BITSHARES_ONBOARDING.md +8 -1
  78. package/docs/COW_INVARIANTS.md +3 -2
  79. package/docs/DEXBOT_COMPARISON.md +4 -4
  80. package/docs/EVOLUTION.md +22 -20
  81. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
  82. package/docs/GRID_PRICE_INVARIANT.md +149 -31
  83. package/docs/GRID_RECALCULATION.md +18 -2
  84. package/docs/README.md +3 -1
  85. package/docs/WORKFLOW.md +16 -5
  86. package/market_adapter/README.md +29 -1
  87. package/modules/README.md +18 -1
  88. package/package.json +13 -5
  89. package/scripts/README.md +28 -2
  90. package/scripts/clear-all.sh +13 -4
  91. package/scripts/clear-logs.sh +13 -4
  92. package/scripts/clear-market-adapter.sh +6 -0
  93. package/scripts/clear-orders.sh +5 -0
  94. package/scripts/lib/dexbot-paths.sh +108 -0
  95. package/tests/README.md +11 -3
  96. package/analysis/account_resolver.ts +0 -161
  97. package/analysis/ama_fitting/analyze_ama_price_changes.ts +0 -155
  98. package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +0 -404
  99. package/analysis/ama_fitting/calibrate_convergence_er.ts +0 -201
  100. package/analysis/ama_fitting/fetch_lp_candles.ts +0 -184
  101. package/analysis/ama_fitting/generate_unified_comparison_chart.ts +0 -232
  102. package/analysis/ama_fitting/optimizer_high_resolution.ts +0 -802
  103. package/analysis/analyze_dynamic_weight.ts +0 -243
  104. package/analysis/analyze_kalman.ts +0 -157
  105. package/analysis/analyze_regime.ts +0 -158
  106. package/analysis/analyze_regime_windows.ts +0 -470
  107. package/analysis/analyze_risk_profile.ts +0 -199
  108. package/analysis/analyze_trade_heatmap.ts +0 -362
  109. package/analysis/analyze_volatility.ts +0 -182
  110. package/analysis/bot_fitting/backtest_ama_sweep.ts +0 -934
  111. package/analysis/bot_fitting/backtest_bot_fitting.ts +0 -861
  112. package/analysis/bot_fitting/shared_utils.ts +0 -52
  113. package/analysis/bot_key_utils.ts +0 -426
  114. package/analysis/bot_usage/discover_bot_accounts.ts +0 -635
  115. package/analysis/bot_usage/kibana_bot_queries.ts +0 -211
  116. package/analysis/chain_pool.ts +0 -47
  117. package/analysis/chart_css.ts +0 -62
  118. package/analysis/chart_ui.ts +0 -105
  119. package/analysis/chart_utils.ts +0 -210
  120. package/analysis/fills_source.ts +0 -228
  121. package/analysis/grid_correction_check.ts +0 -786
  122. package/analysis/math_utils.ts +0 -53
  123. package/analysis/price_sources.ts +0 -136
  124. package/analysis/resolve_bot_accounts.ts +0 -199
  125. package/analysis/resolve_source.ts +0 -99
  126. package/analysis/results/ama_sweep_results_lp_pool_133_1h.json +0 -2455
  127. package/analysis/results/bot_fitting_results_lp_pool_133_1h.json +0 -218
  128. package/analysis/trade_profitability.ts +0 -1335
  129. package/analysis/tradingview/analyze_tradingview.ts +0 -280
  130. package/analysis/tradingview/h-bts_tradingview.html +0 -1570
  131. package/analysis/tradingview/t-bts_tradingview.html +0 -1570
  132. package/analysis/tradingview/tradingview_uplot_chart_generator.ts +0 -3268
  133. package/analysis/trend_detection/dynamic_weight_chart_generator.ts +0 -1481
  134. package/analysis/trend_detection/hurst_analyzer.ts +0 -7
  135. package/analysis/trend_detection/kalman_chart_generator.ts +0 -398
  136. package/analysis/trend_detection/kalman_trend_analyzer.ts +0 -9
  137. package/analysis/trend_detection/kalman_velocity_smoothing.ts +0 -7
  138. package/analysis/trend_detection/package.json +0 -23
  139. package/analysis/trend_detection/permutation_entropy_analyzer.ts +0 -7
  140. package/analysis/trend_detection/regime_chart_generator.ts +0 -338
  141. package/analysis/trend_detection/tests/test_kalman_trend.ts +0 -153
  142. package/analysis/trend_detection/tests/test_kalman_velocity_smoothing.ts +0 -64
  143. package/analysis/trend_detection/volatility_chart_generator.ts +0 -654
  144. package/analysis/tsconfig.json +0 -29
  145. package/claw/tests/package.json +0 -3
  146. package/claw/tests/test_claw_bridge.ts +0 -570
  147. package/claw/tests/test_claw_catalog_and_credentials.ts +0 -156
  148. package/claw/tests/test_claw_chain_layer.ts +0 -739
  149. package/claw/tests/test_claw_data_flow.ts +0 -525
  150. package/claw/tests/test_claw_domain_logic.ts +0 -471
  151. package/claw/tests/test_claw_manifest_and_matrix.ts +0 -222
  152. package/claw/tests/test_claw_mcp_transport.ts +0 -243
  153. package/claw/tests/test_claw_regressions.ts +0 -711
  154. package/claw/tests/test_claw_skill_generation.ts +0 -103
  155. package/claw/tests/test_claw_state_store.ts +0 -44
  156. package/claw/tests/test_dexbot_profiles.ts +0 -654
  157. package/claw/tests/test_memu_bridge.ts +0 -189
  158. package/claw/tests/test_nullclaw_tmp_integration.ts +0 -57
  159. package/claw/tests/test_position_health.ts +0 -343
  160. package/claw/tests/test_position_manager.ts +0 -429
  161. package/claw/tests/test_position_manager_watch_health.ts +0 -100
  162. package/claw/tests/test_short_mpa_strategy.ts +0 -232
  163. package/dist/analysis/account_resolver.d.ts.map +0 -1
  164. package/dist/analysis/account_resolver.js.map +0 -1
  165. package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +0 -1
  166. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +0 -1
  167. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +0 -1
  168. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +0 -1
  169. package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +0 -1
  170. package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +0 -1
  171. package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +0 -1
  172. package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +0 -1
  173. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +0 -1
  174. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +0 -1
  175. package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +0 -1
  176. package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +0 -1
  177. package/dist/analysis/analyze_dynamic_weight.d.ts.map +0 -1
  178. package/dist/analysis/analyze_dynamic_weight.js.map +0 -1
  179. package/dist/analysis/analyze_kalman.d.ts.map +0 -1
  180. package/dist/analysis/analyze_kalman.js.map +0 -1
  181. package/dist/analysis/analyze_regime.d.ts.map +0 -1
  182. package/dist/analysis/analyze_regime.js.map +0 -1
  183. package/dist/analysis/analyze_regime_windows.d.ts.map +0 -1
  184. package/dist/analysis/analyze_regime_windows.js.map +0 -1
  185. package/dist/analysis/analyze_risk_profile.d.ts.map +0 -1
  186. package/dist/analysis/analyze_risk_profile.js.map +0 -1
  187. package/dist/analysis/analyze_trade_heatmap.d.ts.map +0 -1
  188. package/dist/analysis/analyze_trade_heatmap.js.map +0 -1
  189. package/dist/analysis/analyze_volatility.d.ts.map +0 -1
  190. package/dist/analysis/analyze_volatility.js.map +0 -1
  191. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +0 -1
  192. package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +0 -1
  193. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +0 -1
  194. package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +0 -1
  195. package/dist/analysis/bot_fitting/shared_utils.d.ts.map +0 -1
  196. package/dist/analysis/bot_fitting/shared_utils.js.map +0 -1
  197. package/dist/analysis/bot_key_utils.d.ts.map +0 -1
  198. package/dist/analysis/bot_key_utils.js.map +0 -1
  199. package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +0 -1
  200. package/dist/analysis/bot_usage/discover_bot_accounts.js.map +0 -1
  201. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +0 -1
  202. package/dist/analysis/bot_usage/kibana_bot_queries.js.map +0 -1
  203. package/dist/analysis/chain_pool.d.ts.map +0 -1
  204. package/dist/analysis/chain_pool.js.map +0 -1
  205. package/dist/analysis/chart_css.d.ts.map +0 -1
  206. package/dist/analysis/chart_css.js.map +0 -1
  207. package/dist/analysis/chart_ui.d.ts.map +0 -1
  208. package/dist/analysis/chart_ui.js.map +0 -1
  209. package/dist/analysis/chart_utils.d.ts.map +0 -1
  210. package/dist/analysis/chart_utils.js.map +0 -1
  211. package/dist/analysis/fills_source.d.ts.map +0 -1
  212. package/dist/analysis/fills_source.js.map +0 -1
  213. package/dist/analysis/grid_correction_check.d.ts.map +0 -1
  214. package/dist/analysis/grid_correction_check.js.map +0 -1
  215. package/dist/analysis/math_utils.d.ts.map +0 -1
  216. package/dist/analysis/math_utils.js.map +0 -1
  217. package/dist/analysis/price_sources.d.ts.map +0 -1
  218. package/dist/analysis/price_sources.js.map +0 -1
  219. package/dist/analysis/resolve_bot_accounts.d.ts.map +0 -1
  220. package/dist/analysis/resolve_bot_accounts.js.map +0 -1
  221. package/dist/analysis/resolve_source.d.ts.map +0 -1
  222. package/dist/analysis/resolve_source.js.map +0 -1
  223. package/dist/analysis/trade_profitability.d.ts.map +0 -1
  224. package/dist/analysis/trade_profitability.js.map +0 -1
  225. package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +0 -1
  226. package/dist/analysis/tradingview/analyze_tradingview.js.map +0 -1
  227. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +0 -1
  228. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +0 -1
  229. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +0 -1
  230. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +0 -1
  231. package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +0 -1
  232. package/dist/analysis/trend_detection/hurst_analyzer.js.map +0 -1
  233. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +0 -1
  234. package/dist/analysis/trend_detection/kalman_chart_generator.js.map +0 -1
  235. package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +0 -1
  236. package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +0 -1
  237. package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +0 -1
  238. package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +0 -1
  239. package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +0 -1
  240. package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +0 -1
  241. package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +0 -1
  242. package/dist/analysis/trend_detection/regime_chart_generator.js.map +0 -1
  243. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +0 -2
  244. package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +0 -1
  245. package/dist/analysis/trend_detection/tests/test_kalman_trend.js +0 -128
  246. package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +0 -1
  247. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +0 -2
  248. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +0 -1
  249. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +0 -37
  250. package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +0 -1
  251. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +0 -1
  252. package/dist/analysis/trend_detection/volatility_chart_generator.js.map +0 -1
  253. package/dist/bot.d.ts.map +0 -1
  254. package/dist/bot.js.map +0 -1
  255. package/dist/credential-daemon.d.ts.map +0 -1
  256. package/dist/credential-daemon.js.map +0 -1
  257. package/dist/dexbot.d.ts.map +0 -1
  258. package/dist/dexbot.js.map +0 -1
  259. package/dist/market_adapter/ama_signal_runner.d.ts.map +0 -1
  260. package/dist/market_adapter/ama_signal_runner.js.map +0 -1
  261. package/dist/market_adapter/candle_utils.d.ts.map +0 -1
  262. package/dist/market_adapter/candle_utils.js.map +0 -1
  263. package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +0 -1
  264. package/dist/market_adapter/core/asymmetric_bounds.js.map +0 -1
  265. package/dist/market_adapter/core/config_normalizers.d.ts.map +0 -1
  266. package/dist/market_adapter/core/config_normalizers.js.map +0 -1
  267. package/dist/market_adapter/core/kibana_candles.d.ts.map +0 -1
  268. package/dist/market_adapter/core/kibana_candles.js.map +0 -1
  269. package/dist/market_adapter/core/kibana_client.d.ts.map +0 -1
  270. package/dist/market_adapter/core/kibana_client.js.map +0 -1
  271. package/dist/market_adapter/core/kibana_market_candles.d.ts.map +0 -1
  272. package/dist/market_adapter/core/kibana_market_candles.js.map +0 -1
  273. package/dist/market_adapter/core/market_adapter_service.d.ts.map +0 -1
  274. package/dist/market_adapter/core/market_adapter_service.js.map +0 -1
  275. package/dist/market_adapter/core/signals/hurst_analyzer.d.ts.map +0 -1
  276. package/dist/market_adapter/core/signals/hurst_analyzer.js.map +0 -1
  277. package/dist/market_adapter/core/signals/kalman_trend_analyzer.d.ts.map +0 -1
  278. package/dist/market_adapter/core/signals/kalman_trend_analyzer.js.map +0 -1
  279. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.d.ts.map +0 -1
  280. package/dist/market_adapter/core/signals/kalman_velocity_smoothing.js.map +0 -1
  281. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts.map +0 -1
  282. package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js.map +0 -1
  283. package/dist/market_adapter/core/strategies/ama.d.ts.map +0 -1
  284. package/dist/market_adapter/core/strategies/ama.js.map +0 -1
  285. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +0 -1
  286. package/dist/market_adapter/core/strategies/ama_slope_model.js.map +0 -1
  287. package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +0 -1
  288. package/dist/market_adapter/core/strategies/atr/calculator.js.map +0 -1
  289. package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +0 -1
  290. package/dist/market_adapter/core/strategies/collateral_manager.js.map +0 -1
  291. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts.map +0 -1
  292. package/dist/market_adapter/core/strategies/dynamic_weight_series.js.map +0 -1
  293. package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +0 -1
  294. package/dist/market_adapter/core/strategies/regime_gate.js.map +0 -1
  295. package/dist/market_adapter/core/strategies/regime_interp.d.ts.map +0 -1
  296. package/dist/market_adapter/core/strategies/regime_interp.js.map +0 -1
  297. package/dist/market_adapter/core/strategies/volatility_shift.d.ts.map +0 -1
  298. package/dist/market_adapter/core/strategies/volatility_shift.js.map +0 -1
  299. package/dist/market_adapter/inputs/fetch_book_data.d.ts.map +0 -1
  300. package/dist/market_adapter/inputs/fetch_book_data.js.map +0 -1
  301. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +0 -1
  302. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +0 -1
  303. package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +0 -1
  304. package/dist/market_adapter/inputs/fetch_lp_data.js.map +0 -1
  305. package/dist/market_adapter/inputs/kibana_feed_source.d.ts.map +0 -1
  306. package/dist/market_adapter/inputs/kibana_feed_source.js.map +0 -1
  307. package/dist/market_adapter/inputs/kibana_source.d.ts.map +0 -1
  308. package/dist/market_adapter/inputs/kibana_source.js.map +0 -1
  309. package/dist/market_adapter/inputs/window_cache.d.ts.map +0 -1
  310. package/dist/market_adapter/inputs/window_cache.js.map +0 -1
  311. package/dist/market_adapter/interval_utils.d.ts.map +0 -1
  312. package/dist/market_adapter/interval_utils.js.map +0 -1
  313. package/dist/market_adapter/log_format.d.ts.map +0 -1
  314. package/dist/market_adapter/log_format.js.map +0 -1
  315. package/dist/market_adapter/lp_chart_core.d.ts.map +0 -1
  316. package/dist/market_adapter/lp_chart_core.js.map +0 -1
  317. package/dist/market_adapter/lp_chart_runner.d.ts.map +0 -1
  318. package/dist/market_adapter/lp_chart_runner.js.map +0 -1
  319. package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +0 -1
  320. package/dist/market_adapter/lp_chart_strategy_loader.js.map +0 -1
  321. package/dist/market_adapter/market_adapter.d.ts.map +0 -1
  322. package/dist/market_adapter/market_adapter.js.map +0 -1
  323. package/dist/market_adapter/test_helpers.d.ts.map +0 -1
  324. package/dist/market_adapter/test_helpers.js.map +0 -1
  325. package/dist/market_adapter/utils/adapter_client.d.ts.map +0 -1
  326. package/dist/market_adapter/utils/adapter_client.js.map +0 -1
  327. package/dist/market_adapter/utils/atomic_write.d.ts.map +0 -1
  328. package/dist/market_adapter/utils/atomic_write.js.map +0 -1
  329. package/dist/market_adapter/utils/chain.d.ts.map +0 -1
  330. package/dist/market_adapter/utils/chain.js.map +0 -1
  331. package/dist/market_adapter/utils/data_discovery.d.ts.map +0 -1
  332. package/dist/market_adapter/utils/data_discovery.js.map +0 -1
  333. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +0 -1
  334. package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +0 -1
  335. package/dist/market_adapter/utils/file_lock.d.ts.map +0 -1
  336. package/dist/market_adapter/utils/file_lock.js.map +0 -1
  337. package/dist/market_adapter/utils/native_history.d.ts.map +0 -1
  338. package/dist/market_adapter/utils/native_history.js.map +0 -1
  339. package/dist/modules/account_bots.d.ts.map +0 -1
  340. package/dist/modules/account_bots.js.map +0 -1
  341. package/dist/modules/account_orders.d.ts.map +0 -1
  342. package/dist/modules/account_orders.js.map +0 -1
  343. package/dist/modules/authority_resolver.d.ts.map +0 -1
  344. package/dist/modules/authority_resolver.js.map +0 -1
  345. package/dist/modules/bitshares-native/chain_client.d.ts.map +0 -1
  346. package/dist/modules/bitshares-native/chain_client.js.map +0 -1
  347. package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +0 -1
  348. package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +0 -1
  349. package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +0 -1
  350. package/dist/modules/bitshares-native/crypto/ecc.js.map +0 -1
  351. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +0 -1
  352. package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +0 -1
  353. package/dist/modules/bitshares-native/index.d.ts.map +0 -1
  354. package/dist/modules/bitshares-native/index.js.map +0 -1
  355. package/dist/modules/bitshares-native/lru_cache.d.ts.map +0 -1
  356. package/dist/modules/bitshares-native/lru_cache.js.map +0 -1
  357. package/dist/modules/bitshares-native/resolvers.d.ts.map +0 -1
  358. package/dist/modules/bitshares-native/resolvers.js.map +0 -1
  359. package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +0 -1
  360. package/dist/modules/bitshares-native/serial/chain_constants.js.map +0 -1
  361. package/dist/modules/bitshares-native/serial/index.d.ts.map +0 -1
  362. package/dist/modules/bitshares-native/serial/index.js.map +0 -1
  363. package/dist/modules/bitshares-native/serial/operations.d.ts.map +0 -1
  364. package/dist/modules/bitshares-native/serial/operations.js.map +0 -1
  365. package/dist/modules/bitshares-native/serial/serializer.d.ts.map +0 -1
  366. package/dist/modules/bitshares-native/serial/serializer.js.map +0 -1
  367. package/dist/modules/bitshares-native/serial/types.d.ts.map +0 -1
  368. package/dist/modules/bitshares-native/serial/types.js.map +0 -1
  369. package/dist/modules/bitshares-native/signing_client.d.ts.map +0 -1
  370. package/dist/modules/bitshares-native/signing_client.js.map +0 -1
  371. package/dist/modules/bitshares-native/subscriptions.d.ts.map +0 -1
  372. package/dist/modules/bitshares-native/subscriptions.js.map +0 -1
  373. package/dist/modules/bitshares-native/transport.d.ts.map +0 -1
  374. package/dist/modules/bitshares-native/transport.js.map +0 -1
  375. package/dist/modules/bitshares-native/tx/builder.d.ts.map +0 -1
  376. package/dist/modules/bitshares-native/tx/builder.js.map +0 -1
  377. package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +0 -1
  378. package/dist/modules/bitshares-native/tx/tx_cache.js.map +0 -1
  379. package/dist/modules/bitshares_client.d.ts.map +0 -1
  380. package/dist/modules/bitshares_client.js.map +0 -1
  381. package/dist/modules/bot_defaults.d.ts.map +0 -1
  382. package/dist/modules/bot_defaults.js.map +0 -1
  383. package/dist/modules/bot_settings.d.ts.map +0 -1
  384. package/dist/modules/bot_settings.js.map +0 -1
  385. package/dist/modules/bots_file_lock.d.ts.map +0 -1
  386. package/dist/modules/bots_file_lock.js.map +0 -1
  387. package/dist/modules/broadcast_failure.d.ts.map +0 -1
  388. package/dist/modules/broadcast_failure.js.map +0 -1
  389. package/dist/modules/chain_keys.d.ts.map +0 -1
  390. package/dist/modules/chain_keys.js.map +0 -1
  391. package/dist/modules/chain_orders.d.ts.map +0 -1
  392. package/dist/modules/chain_orders.js.map +0 -1
  393. package/dist/modules/cli_colors.d.ts.map +0 -1
  394. package/dist/modules/cli_colors.js.map +0 -1
  395. package/dist/modules/cli_start_onboarding.d.ts.map +0 -1
  396. package/dist/modules/cli_start_onboarding.js.map +0 -1
  397. package/dist/modules/cli_start_output.d.ts.map +0 -1
  398. package/dist/modules/cli_start_output.js.map +0 -1
  399. package/dist/modules/config.d.ts.map +0 -1
  400. package/dist/modules/config.js.map +0 -1
  401. package/dist/modules/constants.d.ts.map +0 -1
  402. package/dist/modules/constants.js.map +0 -1
  403. package/dist/modules/cr_planner.d.ts.map +0 -1
  404. package/dist/modules/cr_planner.js.map +0 -1
  405. package/dist/modules/credential_policy.d.ts.map +0 -1
  406. package/dist/modules/credential_policy.js.map +0 -1
  407. package/dist/modules/credential_runtime.d.ts.map +0 -1
  408. package/dist/modules/credential_runtime.js.map +0 -1
  409. package/dist/modules/credential_session_cache.d.ts.map +0 -1
  410. package/dist/modules/credential_session_cache.js.map +0 -1
  411. package/dist/modules/credit_pricing.d.ts.map +0 -1
  412. package/dist/modules/credit_pricing.js.map +0 -1
  413. package/dist/modules/credit_runtime.d.ts.map +0 -1
  414. package/dist/modules/credit_runtime.js.map +0 -1
  415. package/dist/modules/crypto/browser_provider.d.ts.map +0 -1
  416. package/dist/modules/crypto/browser_provider.js.map +0 -1
  417. package/dist/modules/crypto/index.d.ts.map +0 -1
  418. package/dist/modules/crypto/index.js.map +0 -1
  419. package/dist/modules/crypto/node_provider.d.ts.map +0 -1
  420. package/dist/modules/crypto/node_provider.js.map +0 -1
  421. package/dist/modules/crypto/provider.d.ts.map +0 -1
  422. package/dist/modules/crypto/provider.js.map +0 -1
  423. package/dist/modules/crypto/pure_ripemd160.d.ts.map +0 -1
  424. package/dist/modules/crypto/pure_ripemd160.js.map +0 -1
  425. package/dist/modules/crypto/pure_scrypt.d.ts.map +0 -1
  426. package/dist/modules/crypto/pure_scrypt.js.map +0 -1
  427. package/dist/modules/crypto/pure_secp256k1.d.ts.map +0 -1
  428. package/dist/modules/crypto/pure_secp256k1.js.map +0 -1
  429. package/dist/modules/crypto/sync.d.ts.map +0 -1
  430. package/dist/modules/crypto/sync.js.map +0 -1
  431. package/dist/modules/daemon_node_health.d.ts.map +0 -1
  432. package/dist/modules/daemon_node_health.js.map +0 -1
  433. package/dist/modules/dexbot_class.d.ts.map +0 -1
  434. package/dist/modules/dexbot_class.js.map +0 -1
  435. package/dist/modules/dexbot_cow_runtime.d.ts.map +0 -1
  436. package/dist/modules/dexbot_cow_runtime.js.map +0 -1
  437. package/dist/modules/dexbot_credential_client.d.ts.map +0 -1
  438. package/dist/modules/dexbot_credential_client.js.map +0 -1
  439. package/dist/modules/dexbot_fill_runtime.d.ts.map +0 -1
  440. package/dist/modules/dexbot_fill_runtime.js.map +0 -1
  441. package/dist/modules/dexbot_maintenance_runtime.d.ts.map +0 -1
  442. package/dist/modules/dexbot_maintenance_runtime.js.map +0 -1
  443. package/dist/modules/dexbot_startup_runtime.d.ts.map +0 -1
  444. package/dist/modules/dexbot_startup_runtime.js.map +0 -1
  445. package/dist/modules/dexbot_state_recovery.d.ts.map +0 -1
  446. package/dist/modules/dexbot_state_recovery.js.map +0 -1
  447. package/dist/modules/env.d.ts.map +0 -1
  448. package/dist/modules/env.js.map +0 -1
  449. package/dist/modules/fund_registry.d.ts.map +0 -1
  450. package/dist/modules/fund_registry.js.map +0 -1
  451. package/dist/modules/general_settings.d.ts.map +0 -1
  452. package/dist/modules/general_settings.js.map +0 -1
  453. package/dist/modules/graceful_shutdown.d.ts.map +0 -1
  454. package/dist/modules/graceful_shutdown.js.map +0 -1
  455. package/dist/modules/grid_price_source.d.ts.map +0 -1
  456. package/dist/modules/grid_price_source.js.map +0 -1
  457. package/dist/modules/key_store.d.ts.map +0 -1
  458. package/dist/modules/key_store.js.map +0 -1
  459. package/dist/modules/launcher/adapter_requirement.d.ts.map +0 -1
  460. package/dist/modules/launcher/adapter_requirement.js.map +0 -1
  461. package/dist/modules/launcher/bot_supervisor.d.ts.map +0 -1
  462. package/dist/modules/launcher/bot_supervisor.js.map +0 -1
  463. package/dist/modules/launcher/child_env.d.ts.map +0 -1
  464. package/dist/modules/launcher/child_env.js.map +0 -1
  465. package/dist/modules/launcher/credential_bootstrap.d.ts.map +0 -1
  466. package/dist/modules/launcher/credential_bootstrap.js.map +0 -1
  467. package/dist/modules/launcher/credential_daemon.d.ts.map +0 -1
  468. package/dist/modules/launcher/credential_daemon.js.map +0 -1
  469. package/dist/modules/launcher/credential_secret.d.ts.map +0 -1
  470. package/dist/modules/launcher/credential_secret.js.map +0 -1
  471. package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +0 -1
  472. package/dist/modules/launcher/foreign_cred_daemon.js.map +0 -1
  473. package/dist/modules/launcher/headless_password.d.ts.map +0 -1
  474. package/dist/modules/launcher/headless_password.js.map +0 -1
  475. package/dist/modules/launcher/launch_modes.d.ts.map +0 -1
  476. package/dist/modules/launcher/launch_modes.js.map +0 -1
  477. package/dist/modules/launcher/market_adapter_runtime.d.ts.map +0 -1
  478. package/dist/modules/launcher/market_adapter_runtime.js.map +0 -1
  479. package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +0 -1
  480. package/dist/modules/launcher/market_adapter_watchdog.js.map +0 -1
  481. package/dist/modules/launcher/monolithic_runtime.d.ts.map +0 -1
  482. package/dist/modules/launcher/monolithic_runtime.js.map +0 -1
  483. package/dist/modules/launcher/runtime_entry.d.ts.map +0 -1
  484. package/dist/modules/launcher/runtime_entry.js.map +0 -1
  485. package/dist/modules/launcher/status_reporting.d.ts.map +0 -1
  486. package/dist/modules/launcher/status_reporting.js.map +0 -1
  487. package/dist/modules/launcher/supervisor_control.d.ts.map +0 -1
  488. package/dist/modules/launcher/supervisor_control.js.map +0 -1
  489. package/dist/modules/market_adapter_whitelist.d.ts.map +0 -1
  490. package/dist/modules/market_adapter_whitelist.js.map +0 -1
  491. package/dist/modules/node_connect_policy.d.ts.map +0 -1
  492. package/dist/modules/node_connect_policy.js.map +0 -1
  493. package/dist/modules/node_failure_ledger.d.ts.map +0 -1
  494. package/dist/modules/node_failure_ledger.js.map +0 -1
  495. package/dist/modules/node_health_cache.d.ts.map +0 -1
  496. package/dist/modules/node_health_cache.js.map +0 -1
  497. package/dist/modules/node_manager.d.ts.map +0 -1
  498. package/dist/modules/node_manager.js.map +0 -1
  499. package/dist/modules/order/accounting.d.ts.map +0 -1
  500. package/dist/modules/order/accounting.js.map +0 -1
  501. package/dist/modules/order/async_lock.d.ts.map +0 -1
  502. package/dist/modules/order/async_lock.js.map +0 -1
  503. package/dist/modules/order/export.d.ts.map +0 -1
  504. package/dist/modules/order/export.js.map +0 -1
  505. package/dist/modules/order/format.d.ts.map +0 -1
  506. package/dist/modules/order/format.js.map +0 -1
  507. package/dist/modules/order/grid.d.ts.map +0 -1
  508. package/dist/modules/order/grid.js.map +0 -1
  509. package/dist/modules/order/grid_reconcile.d.ts.map +0 -1
  510. package/dist/modules/order/grid_reconcile.js.map +0 -1
  511. package/dist/modules/order/grid_reconcile_internal.d.ts.map +0 -1
  512. package/dist/modules/order/grid_reconcile_internal.js.map +0 -1
  513. package/dist/modules/order/index.d.ts.map +0 -1
  514. package/dist/modules/order/index.js.map +0 -1
  515. package/dist/modules/order/logger.d.ts.map +0 -1
  516. package/dist/modules/order/logger.js.map +0 -1
  517. package/dist/modules/order/logger_state.d.ts.map +0 -1
  518. package/dist/modules/order/logger_state.js.map +0 -1
  519. package/dist/modules/order/manager.d.ts.map +0 -1
  520. package/dist/modules/order/manager.js.map +0 -1
  521. package/dist/modules/order/processed_fill_store.d.ts.map +0 -1
  522. package/dist/modules/order/processed_fill_store.js.map +0 -1
  523. package/dist/modules/order/strategy.d.ts.map +0 -1
  524. package/dist/modules/order/strategy.js.map +0 -1
  525. package/dist/modules/order/sync_engine.d.ts.map +0 -1
  526. package/dist/modules/order/sync_engine.js.map +0 -1
  527. package/dist/modules/order/utils/math.d.ts.map +0 -1
  528. package/dist/modules/order/utils/math.js.map +0 -1
  529. package/dist/modules/order/utils/order.d.ts.map +0 -1
  530. package/dist/modules/order/utils/order.js.map +0 -1
  531. package/dist/modules/order/utils/slot.d.ts.map +0 -1
  532. package/dist/modules/order/utils/slot.js.map +0 -1
  533. package/dist/modules/order/utils/system.d.ts.map +0 -1
  534. package/dist/modules/order/utils/system.js.map +0 -1
  535. package/dist/modules/order/utils/timeout.d.ts.map +0 -1
  536. package/dist/modules/order/utils/timeout.js.map +0 -1
  537. package/dist/modules/order/utils/validate.d.ts.map +0 -1
  538. package/dist/modules/order/utils/validate.js.map +0 -1
  539. package/dist/modules/order/utils/withPoolRef.d.ts.map +0 -1
  540. package/dist/modules/order/utils/withPoolRef.js.map +0 -1
  541. package/dist/modules/order/working_grid.d.ts.map +0 -1
  542. package/dist/modules/order/working_grid.js.map +0 -1
  543. package/dist/modules/path_api.d.ts.map +0 -1
  544. package/dist/modules/path_api.js.map +0 -1
  545. package/dist/modules/paths.d.ts.map +0 -1
  546. package/dist/modules/paths.js.map +0 -1
  547. package/dist/modules/process_discovery.d.ts.map +0 -1
  548. package/dist/modules/process_discovery.js.map +0 -1
  549. package/dist/modules/runtime.d.ts.map +0 -1
  550. package/dist/modules/runtime.js.map +0 -1
  551. package/dist/modules/runtime_settings.d.ts.map +0 -1
  552. package/dist/modules/runtime_settings.js.map +0 -1
  553. package/dist/modules/settings_merge.d.ts.map +0 -1
  554. package/dist/modules/settings_merge.js.map +0 -1
  555. package/dist/modules/socket_json_client.d.ts.map +0 -1
  556. package/dist/modules/socket_json_client.js.map +0 -1
  557. package/dist/modules/storage/browser_adapter.d.ts.map +0 -1
  558. package/dist/modules/storage/browser_adapter.js.map +0 -1
  559. package/dist/modules/storage/index.d.ts.map +0 -1
  560. package/dist/modules/storage/index.js.map +0 -1
  561. package/dist/modules/storage/node_adapter.d.ts.map +0 -1
  562. package/dist/modules/storage/node_adapter.js.map +0 -1
  563. package/dist/modules/storage/types.d.ts.map +0 -1
  564. package/dist/modules/storage/types.js.map +0 -1
  565. package/dist/modules/types.d.ts.map +0 -1
  566. package/dist/modules/types.js.map +0 -1
  567. package/dist/modules/utils/base58check.d.ts.map +0 -1
  568. package/dist/modules/utils/base58check.js.map +0 -1
  569. package/dist/modules/utils/build_dir.d.ts.map +0 -1
  570. package/dist/modules/utils/build_dir.js.map +0 -1
  571. package/dist/modules/utils/chain_logs.d.ts.map +0 -1
  572. package/dist/modules/utils/chain_logs.js.map +0 -1
  573. package/dist/modules/utils/errors.d.ts.map +0 -1
  574. package/dist/modules/utils/errors.js.map +0 -1
  575. package/dist/modules/utils/sanitize_key.d.ts.map +0 -1
  576. package/dist/modules/utils/sanitize_key.js.map +0 -1
  577. package/dist/modules/utils/text_width.d.ts.map +0 -1
  578. package/dist/modules/utils/text_width.js.map +0 -1
  579. package/dist/modules/validate_profiles.d.ts.map +0 -1
  580. package/dist/modules/validate_profiles.js.map +0 -1
  581. package/dist/pm2.d.ts.map +0 -1
  582. package/dist/pm2.js.map +0 -1
  583. package/dist/scripts/analyze-credit.d.ts.map +0 -1
  584. package/dist/scripts/analyze-credit.js.map +0 -1
  585. package/dist/scripts/analyze-git.d.ts.map +0 -1
  586. package/dist/scripts/analyze-git.js.map +0 -1
  587. package/dist/scripts/analyze-orders.d.ts.map +0 -1
  588. package/dist/scripts/analyze-orders.js.map +0 -1
  589. package/dist/scripts/chart_command.d.ts.map +0 -1
  590. package/dist/scripts/chart_command.js.map +0 -1
  591. package/dist/scripts/diagnose-kibana-candles.d.ts.map +0 -1
  592. package/dist/scripts/diagnose-kibana-candles.js.map +0 -1
  593. package/dist/scripts/diagnose-pool-history.d.ts.map +0 -1
  594. package/dist/scripts/diagnose-pool-history.js.map +0 -1
  595. package/dist/scripts/divergence-calc.d.ts.map +0 -1
  596. package/dist/scripts/divergence-calc.js.map +0 -1
  597. package/dist/scripts/dw.d.ts.map +0 -1
  598. package/dist/scripts/dw.js.map +0 -1
  599. package/dist/scripts/generate_lp_chart.d.ts.map +0 -1
  600. package/dist/scripts/generate_lp_chart.js.map +0 -1
  601. package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +0 -1
  602. package/dist/scripts/generate_mainnet_corpus_report.js.map +0 -1
  603. package/dist/scripts/native_release_gates.d.ts.map +0 -1
  604. package/dist/scripts/native_release_gates.js.map +0 -1
  605. package/dist/scripts/print_grid.d.ts.map +0 -1
  606. package/dist/scripts/print_grid.js.map +0 -1
  607. package/dist/scripts/run-tests.d.ts.map +0 -1
  608. package/dist/scripts/run-tests.js.map +0 -1
  609. package/dist/scripts/runner.d.ts.map +0 -1
  610. package/dist/scripts/runner.js.map +0 -1
  611. package/dist/scripts/sync-version.d.ts.map +0 -1
  612. package/dist/scripts/sync-version.js.map +0 -1
  613. package/dist/scripts/test-credit-renewal.d.ts.map +0 -1
  614. package/dist/scripts/test-credit-renewal.js.map +0 -1
  615. package/dist/scripts/tv.d.ts.map +0 -1
  616. package/dist/scripts/tv.js.map +0 -1
  617. package/dist/scripts/update.d.ts.map +0 -1
  618. package/dist/scripts/update.js.map +0 -1
  619. package/dist/scripts/update_dist_freshness.d.ts.map +0 -1
  620. package/dist/scripts/update_dist_freshness.js.map +0 -1
  621. package/dist/scripts/validate_bots.d.ts.map +0 -1
  622. package/dist/scripts/validate_bots.js.map +0 -1
  623. package/dist/scripts/verify-browser-bundle.d.ts.map +0 -1
  624. package/dist/scripts/verify-browser-bundle.js.map +0 -1
  625. package/dist/unlock.d.ts.map +0 -1
  626. package/dist/unlock.js.map +0 -1
@@ -1,786 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- /**
5
- * LAST-FILL-GUARD CHECK
6
- *
7
- * Validates LAST-FILL-GUARD discipline: pivot ± halfIncrement
8
- * Last fill @x with increment i (half=i/2) gates BOTH sides regardless of
9
- * last side — BUY must be < x*(1-half/100), SELL > x*(1+half/100).
10
- * e.g. x=1000, i=0.5% => BUY < 997.5 / SELL > 1002.5.
11
- * Cold start (no previous fill) is disabled.
12
- * Intentional offline gaps (documented, acceptable):
13
- * - Runtime pivots on _lastFilledPrice/_lastFilledType at decision time; tool
14
- * checks consecutive fill pairs. For batch-placed orders (multiple orders
15
- * guarded against the same pivot in one COW batch) this diverges — inherent
16
- * offline approximation.
17
- * - Spread-correction bypass (cowResult.origin === 'spread-correction') is
18
- * not simulated — every consecutive pair is checked.
19
- *
20
- * Mirrors modules/dexbot_cow_runtime.ts:isLastFillGuardBlocked 1:1 and
21
- * modules/constants.ts:DEFAULT_CONFIG.incrementPercent fallback (0.5).
22
- *
23
- * Fetches fill_order operations from Kibana (same pipeline as
24
- * trade_profitability.ts) and checks for last-fill guard violations.
25
- *
26
- * Usage:
27
- * node dist/analysis/grid_correction_check.js --bot-key <bot-key> --hours 168
28
- * node dist/analysis/grid_correction_check.js --bot-key <bot-key> --start 2025-01-01 --end 2025-06-01
29
- * node dist/analysis/grid_correction_check.js --bot-key <bot-key> --hours 720 --account 1.2.123
30
- * node dist/analysis/grid_correction_check.js --bot-key <bot-key> --hours 720 --json results.json
31
- * node dist/analysis/grid_correction_check.js --bot-key <bot-key> --hours 720 --csv violations.csv
32
- * node dist/analysis/grid_correction_check.js --bot-key <bot-key> --hours 720 --increment 0.5
33
- * node dist/analysis/grid_correction_check.js --list-bots
34
- */
35
-
36
- import fs from 'node:fs';
37
- import { pathToFileURL } from 'node:url';
38
- import * as KC from '../market_adapter/core/kibana_client.js';
39
- import * as C from '../modules/constants.js';
40
- import { loadBotSettings, computeBotKey } from './bot_key_utils.js';
41
- import { resolveBotAccount } from './account_resolver.js';
42
- import {
43
- BTS_ID,
44
- FillRecord,
45
- assetPrec,
46
- assetSymbol,
47
- fetchAllFills,
48
- resolveAssetPrecisions,
49
- toReal,
50
- } from './fills_source.js';
51
-
52
- const { kibanaSearch, DEFAULT_CONFIG: BASE_CONFIG } = KC;
53
-
54
- const OP_LIMIT_ORDER_UPDATE = 77;
55
-
56
- // ─── Types ────────────────────────────────────────────────────────────────────
57
- interface OrderUpdate {
58
- orderId: string;
59
- sequence: number;
60
- }
61
- interface TradeFill {
62
- time: string;
63
- orderId: string;
64
- direction: 'buy' | 'sell';
65
- baseAsset: string;
66
- quoteAsset: string;
67
- baseAmount: number;
68
- quoteAmount: number;
69
- price: number;
70
- isMaker: boolean;
71
- sequence: number;
72
- }
73
- interface Violation {
74
- index: number;
75
- pair: string;
76
- direction: 'buy' | 'sell';
77
- expected: string;
78
- prev: TradeFill;
79
- curr: TradeFill;
80
- priceDelta: number;
81
- priceDeltaPct: number;
82
- pivot: number;
83
- halfInc: number;
84
- threshold: number;
85
- }
86
- interface AggregatedOrder {
87
- orderId: string;
88
- direction: 'buy' | 'sell';
89
- baseAsset: string;
90
- quoteAsset: string;
91
- baseAmount: number;
92
- quoteAmount: number;
93
- price: number;
94
- time: string;
95
- sequence: number;
96
- fillCount: number;
97
- isMaker: boolean;
98
- }
99
-
100
- // ─── LAST-FILL-GUARD helper (1:1 with dexbot_cow_runtime.ts) ─────────────────
101
-
102
- /**
103
- * LAST-FILL-GUARD helper — pivot ± halfIncrement (replaces price-tolerance).
104
- * last fill @x with increment i: BUY < x*(1 - i/2/100), SELL > x*(1 + i/2/100)
105
- * e.g. x=1000, i=0.5% => BUY < 997.5, SELL > 1002.5
106
- * Cold (pivot null or lastType null) => disabled.
107
- * @param {number} price - Target order price
108
- * @param {string} type - buy/sell
109
- * @param {number|null} lastPrice - Most recent fill price
110
- * @param {string|null} lastType - Most recent fill side (buy/sell)
111
- * @param {number|any} incrementPercent - Grid increment percent (e.g. 0.5). If not finite/<=0 falls back to DEFAULT_CONFIG.
112
- * @returns {{blocked: boolean, pivot: number|null, halfInc: number, threshold: number|null}}
113
- */
114
- function isLastFillGuardBlocked(
115
- price: any,
116
- type: any,
117
- lastPrice: any,
118
- lastType: any,
119
- incrementPercent: any,
120
- ): { blocked: boolean; pivot: number | null; halfInc?: number; threshold?: number | null } {
121
- const numPrice = Number(price);
122
- if (!Number.isFinite(numPrice)) return { blocked: false, pivot: null };
123
- if (lastPrice == null || !Number.isFinite(Number(lastPrice)) || lastType == null) return { blocked: false, pivot: null };
124
- const pivot = Number(lastPrice);
125
- let inc = Number(incrementPercent);
126
- if (!Number.isFinite(inc) || inc <= 0) {
127
- inc = Number((C as any)?.DEFAULT_CONFIG?.incrementPercent ?? 0.5);
128
- }
129
- if (!Number.isFinite(inc) || inc <= 0) return { blocked: false, pivot: null };
130
- const halfInc = inc / 2;
131
- const halfPct = halfInc / 100;
132
- const buyThreshold = pivot * (1 - halfPct);
133
- const sellThreshold = pivot * (1 + halfPct);
134
- if (type === 'buy' && numPrice > buyThreshold) return { blocked: true, pivot, halfInc, threshold: buyThreshold };
135
- if (type === 'sell' && numPrice < sellThreshold) return { blocked: true, pivot, halfInc, threshold: sellThreshold };
136
- return { blocked: false, pivot: null, halfInc, threshold: null };
137
- }
138
-
139
- function resolveIncrementPercent(botMeta: any, override: number | null): number {
140
- if (override != null && Number.isFinite(override) && override > 0) return override;
141
- const fromBot = Number(botMeta?.incrementPercent);
142
- if (Number.isFinite(fromBot) && fromBot > 0) return fromBot;
143
- const fromDefault = Number((C as any)?.DEFAULT_CONFIG?.incrementPercent ?? 0.5);
144
- if (Number.isFinite(fromDefault) && fromDefault > 0) return fromDefault;
145
- return 0.5;
146
- }
147
-
148
- // ─── CLI ──────────────────────────────────────────────────────────────────────
149
- function printHelp() {
150
- console.log(`\
151
- Usage: node dist/analysis/grid_correction_check.js --bot-key <key> [options]
152
-
153
- Validates LAST-FILL-GUARD discipline (pivot ± halfIncrement):
154
- last fill @x with increment i (half=i/2) gates both sides —
155
- BUY must be < x*(1-half/100), SELL > x*(1+half/100).
156
- e.g. x=1000, i=0.5% => BUY < 997.5 / SELL > 1002.5.
157
- Mirrors dexbot_cow_runtime:isLastFillGuardBlocked 1:1.
158
-
159
- Required:
160
- --bot-key <key> Bot key (e.g. my-grid-bot) or bot name (use --list-bots)
161
-
162
- Time range (one of):
163
- --hours <n> Lookback hours from now (default: 168)
164
- --start <iso> Start time (ISO 8601)
165
- --end <iso> End time (ISO 8601, default: now)
166
-
167
- Options:
168
- --account <id> Override account ID (default: from bot preferredAccount)
169
- --refresh-account Force re-resolution of preferredAccount and update the
170
- stored accountId when it changed (default: reuse the
171
- stored accountId with no chain lookup)
172
- --increment <pct> Grid increment percent (default: from bot config or ${Number((C as any)?.DEFAULT_CONFIG?.incrementPercent ?? 0.5)})
173
- --tolerance <pct> Deprecated alias for --increment (kept for compat, prefer --increment)
174
- --per-fill Check at fill granularity (default: per-order aggregated)
175
- --include-cross-pair Check consecutive fills across different pairs (default: same pair only)
176
- --json <file> Export violations as JSON
177
- --csv <file> Export violations as CSV
178
- --verbose Print the fetched trade sequence before checking
179
- --list-bots List available bot keys and exit
180
- --help, -h Show this help
181
-
182
- Examples:
183
- node dist/analysis/grid_correction_check.js --bot-key <bot-key> --hours 720
184
- node dist/analysis/grid_correction_check.js --bot-key "<bot-key>" --start 2025-01-01 --end 2025-06-01
185
- node dist/analysis/grid_correction_check.js --bot-key <bot-key> --hours 168 --increment 1.0
186
- `);
187
- }
188
-
189
- function parseArgs() {
190
- const args = process.argv.slice(2);
191
- if (args.includes('--help') || args.includes('-h')) { printHelp(); process.exit(0); }
192
- if (args.includes('--list-bots')) {
193
- const settings = loadBotSettings();
194
- const entries = settings?.bots ?? [];
195
- if (!entries.length) { console.log('No bots in profiles/bots.json'); process.exit(0); }
196
- console.log('Available bot keys:');
197
- for (let i = 0; i < entries.length; i++) {
198
- const k = computeBotKey(entries[i], i);
199
- console.log(` ${k} (name: ${entries[i].name ?? '-'}, ${entries[i].assetA}/${entries[i].assetB}, account: ${entries[i].preferredAccount ?? '-'})`);
200
- }
201
- process.exit(0);
202
- }
203
-
204
- const opts: any = {
205
- botKey: null,
206
- hours: null,
207
- start: null,
208
- end: null,
209
- account: null,
210
- refreshAccount: false,
211
- perFill: false,
212
- includeCrossPair: false,
213
- incrementPercent: null as number | null,
214
- json: null,
215
- csv: null,
216
- verbose: false,
217
- };
218
-
219
- for (let i = 0; i < args.length; i++) {
220
- switch (args[i]) {
221
- case '--bot-key': opts.botKey = args[++i]; break;
222
- case '--hours': opts.hours = parseInt(args[++i], 10); break;
223
- case '--start': opts.start = args[++i]; break;
224
- case '--end': opts.end = args[++i]; break;
225
- case '--account': opts.account = args[++i]; break;
226
- case '--refresh-account': opts.refreshAccount = true; break;
227
- case '--per-fill': opts.perFill = true; break;
228
- case '--include-cross-pair': opts.includeCrossPair = true; break;
229
- case '--increment': opts.incrementPercent = parseFloat(args[++i]); break;
230
- case '--tolerance': {
231
- const v = parseFloat(args[++i]);
232
- // Back-compat: old --tolerance was adverse pct before flagging; now map to increment if user still passes it
233
- // Prefer explicit --increment; don't overwrite if already set
234
- if (opts.incrementPercent == null) opts.incrementPercent = v > 0 ? v * 2 : null; // heuristic: old tolerance ~ halfInc, so inc ~ 2*tolerance
235
- console.warn(`[warn] --tolerance is deprecated, use --increment <pct> (e.g. --increment ${v > 0 ? (v*2) : 0.5})`);
236
- break;
237
- }
238
- case '--json': opts.json = args[++i]; break;
239
- case '--csv': opts.csv = args[++i]; break;
240
- case '--verbose': opts.verbose = true; break;
241
- default:
242
- console.error(`Unknown option: ${args[i]}`);
243
- printHelp();
244
- process.exit(1);
245
- }
246
- }
247
-
248
- if (!opts.botKey) {
249
- console.error('Error: --bot-key is required (use --list-bots to see available keys)');
250
- printHelp();
251
- process.exit(1);
252
- }
253
- if (!opts.hours && !opts.start) opts.hours = 168;
254
- if (opts.incrementPercent != null && (isNaN(opts.incrementPercent) || opts.incrementPercent < 0)) {
255
- console.error('Error: --increment must be a non-negative number');
256
- process.exit(1);
257
- }
258
- return opts;
259
- }
260
-
261
- // ─── Time helpers ─────────────────────────────────────────────────────────────
262
- function resolveTimeRange(opts: any): { gte: string; lte: string; label: string } {
263
- let gte: string, lte: string;
264
- if (opts.start) {
265
- const s = new Date(opts.start);
266
- if (isNaN(s.getTime())) { console.error(`Invalid --start: ${opts.start}`); process.exit(1); }
267
- gte = s.toISOString();
268
- } else {
269
- const h = opts.hours ?? 168;
270
- gte = new Date(Date.now() - h * 3600_000).toISOString();
271
- }
272
- if (opts.end) {
273
- const e = new Date(opts.end);
274
- if (isNaN(e.getTime())) { console.error(`Invalid --end: ${opts.end}`); process.exit(1); }
275
- lte = e.toISOString();
276
- } else {
277
- lte = new Date().toISOString();
278
- }
279
- const label = `${gte} → ${lte}`;
280
- return { gte, lte, label };
281
- }
282
-
283
- // ─── Account resolution errors ────────────────────────────────────────────────
284
- /** Map a shared account-resolver failure onto this tool's operator-facing hint. */
285
- function reportAccountFailure(resolved: any, opts: any): void {
286
- switch (resolved.reason) {
287
- case 'bot-not-found':
288
- console.error(`Error: bot key '${opts.botKey}' not found in profiles/bots.json and no --account provided.`);
289
- console.error('Use --list-bots to see available keys, or pass --account <1.2.x> explicitly.');
290
- break;
291
- case 'override-unresolved':
292
- console.error(`Error: failed to resolve --account '${opts.account}' to 1.2.x`);
293
- break;
294
- case 'no-preferred-account':
295
- console.error(`Error: bot '${opts.botKey}' has no preferredAccount and no --account provided.`);
296
- break;
297
- default:
298
- console.error(`Error: failed to resolve account name '${resolved?.botMeta?.preferredAccount ?? opts.botKey}' to 1.2.x`);
299
- }
300
- }
301
-
302
- // ─── Kibana fetch ─────────────────────────────────────────────────────────────
303
- async function fetchAllOrderUpdates(config: any, accountId: string, gte: string, lte: string): Promise<OrderUpdate[]> {
304
- const pageSize = 10000;
305
- const updates: OrderUpdate[] = [];
306
- let searchAfter: any[] | null = null;
307
- const cfg = { ...BASE_CONFIG, timeout: 60000, ...config };
308
- while (true) {
309
- const query: any = {
310
- size: pageSize,
311
- track_total_hits: false,
312
- _source: [
313
- 'block_data.block_num', 'operation_id_num',
314
- 'operation_history.op_object.order',
315
- 'operation_history.op_object.seller',
316
- ],
317
- query: { bool: { filter: [
318
- { term: { operation_type: OP_LIMIT_ORDER_UPDATE } },
319
- { term: { 'operation_history.op_object.seller.keyword': accountId } },
320
- { range: { 'block_data.block_time': { gte, lte } } },
321
- ] } },
322
- sort: [
323
- { 'block_data.block_num': { order: 'asc' } },
324
- { operation_id_num: { order: 'asc' } },
325
- ],
326
- };
327
- if (searchAfter) query.search_after = searchAfter;
328
- const result: any = await kibanaSearch(cfg, query);
329
- const hits = result?.hits?.hits ?? [];
330
- if (!hits.length) break;
331
- for (const hit of hits) {
332
- const source = hit?._source || {};
333
- const op = source.operation_history?.op_object || {};
334
- const orderId = op.order;
335
- if (!orderId) continue;
336
- const blockNum = Number(source.block_data?.block_num ?? 0);
337
- const opNum = Number(source.operation_id_num ?? 0);
338
- updates.push({ orderId, sequence: blockNum * 1e6 + opNum });
339
- }
340
- const last = hits[hits.length - 1];
341
- searchAfter = last?.sort;
342
- if (!searchAfter || hits.length < pageSize) break;
343
- }
344
- return updates;
345
- }
346
-
347
- // ─── Fill classification ─────────────────────────────────────────────────────
348
- function classifyFills(fills: FillRecord[]): { trades: TradeFill[]; skipped: number } {
349
- const trades: TradeFill[] = [];
350
- let skipped = 0;
351
- for (const f of fills) {
352
- const pAsset = f.pays.asset_id;
353
- const rAsset = f.receives.asset_id;
354
- let direction: 'buy' | 'sell';
355
- let baseAsset: string;
356
- let quoteAsset: string;
357
- let baseAmount: number;
358
- let quoteAmount: number;
359
- let price: number;
360
-
361
- if (pAsset === BTS_ID && rAsset !== BTS_ID) {
362
- direction = 'buy';
363
- baseAsset = rAsset; quoteAsset = BTS_ID;
364
- baseAmount = toReal(f.receives.amount, rAsset);
365
- quoteAmount = toReal(f.pays.amount, BTS_ID);
366
- if (!Number.isFinite(baseAmount) || !Number.isFinite(quoteAmount) || baseAmount <= 0 || quoteAmount <= 0) { skipped++; continue; }
367
- price = quoteAmount / baseAmount;
368
- } else if (rAsset === BTS_ID && pAsset !== BTS_ID) {
369
- direction = 'sell';
370
- baseAsset = pAsset; quoteAsset = BTS_ID;
371
- baseAmount = toReal(f.pays.amount, pAsset);
372
- quoteAmount = toReal(f.receives.amount, BTS_ID);
373
- if (!Number.isFinite(baseAmount) || !Number.isFinite(quoteAmount) || baseAmount <= 0 || quoteAmount <= 0) { skipped++; continue; }
374
- price = quoteAmount / baseAmount;
375
- } else {
376
- const baseForCheck = pAsset < rAsset ? pAsset : rAsset;
377
- const quoteForCheck = pAsset < rAsset ? rAsset : pAsset;
378
- if (assetPrec(baseForCheck) === undefined || assetPrec(quoteForCheck) === undefined) { skipped++; continue; }
379
- const isSell = pAsset < rAsset;
380
- direction = isSell ? 'sell' : 'buy';
381
- baseAsset = isSell ? pAsset : rAsset;
382
- quoteAsset = isSell ? rAsset : pAsset;
383
- baseAmount = toReal(isSell ? f.pays.amount : f.receives.amount, baseAsset);
384
- quoteAmount = toReal(isSell ? f.receives.amount : f.pays.amount, quoteAsset);
385
- if (!Number.isFinite(baseAmount) || !Number.isFinite(quoteAmount) || baseAmount <= 0 || quoteAmount <= 0) { skipped++; continue; }
386
- price = quoteAmount / baseAmount;
387
- }
388
-
389
- trades.push({
390
- time: f.time,
391
- orderId: f.orderId,
392
- direction,
393
- baseAsset,
394
- quoteAsset,
395
- baseAmount,
396
- quoteAmount,
397
- price,
398
- isMaker: f.isMaker,
399
- sequence: f.blockNum * 1e6 + f.opNum,
400
- });
401
- }
402
- return { trades, skipped };
403
- }
404
-
405
- // ─── Per-order/price-epoch aggregation ───────────────────────────────────────
406
- // Collapses partial fills at one order lifetime, but never mixes fills from
407
- // different native limit_order_update repricings of the same order ID.
408
- function aggregateByOrder(trades: TradeFill[], updates: OrderUpdate[] = []): AggregatedOrder[] {
409
- const updatesByOrder = new Map<string, number[]>();
410
- for (const update of updates) {
411
- const list = updatesByOrder.get(update.orderId) || [];
412
- list.push(update.sequence);
413
- updatesByOrder.set(update.orderId, list);
414
- }
415
- for (const list of updatesByOrder.values()) list.sort((a, b) => a - b);
416
-
417
- const map = new Map<string, { trades: TradeFill[] }>();
418
- for (const t of trades) {
419
- // An update is ordered before the fills it can affect. The epoch is
420
- // therefore the latest update sequence at or before this fill.
421
- const orderUpdates = updatesByOrder.get(t.orderId) || [];
422
- let epoch = 0;
423
- for (const sequence of orderUpdates) {
424
- if (sequence <= t.sequence) epoch = sequence;
425
- else break;
426
- }
427
- const k = t.orderId
428
- ? `${t.orderId}:${t.direction}:${t.baseAsset}:${t.quoteAsset}:${epoch}`
429
- : `__fill_${t.sequence}`;
430
- if (!map.has(k)) map.set(k, { trades: [] });
431
- map.get(k)!.trades.push(t);
432
- }
433
- const orders: AggregatedOrder[] = [];
434
- for (const [orderId, group] of map) {
435
- const first = group.trades[0];
436
- // All fills for same order should share direction/pair, but validate
437
- const directions = new Set(group.trades.map(t => t.direction));
438
- const pairs = new Set(group.trades.map(t => `${t.baseAsset}:${t.quoteAsset}`));
439
- if (directions.size > 1 || pairs.size > 1) {
440
- // Mixed direction/pair for same orderId should not happen; keep fills separate
441
- for (const t of group.trades) {
442
- orders.push({
443
- orderId: t.orderId, direction: t.direction, baseAsset: t.baseAsset, quoteAsset: t.quoteAsset,
444
- baseAmount: t.baseAmount, quoteAmount: t.quoteAmount, price: t.price,
445
- time: t.time, sequence: t.sequence, fillCount: 1, isMaker: t.isMaker,
446
- });
447
- }
448
- continue;
449
- }
450
- const baseAmount = group.trades.reduce((s, t) => s + t.baseAmount, 0);
451
- const quoteAmount = group.trades.reduce((s, t) => s + t.quoteAmount, 0);
452
- const price = baseAmount > 0 ? quoteAmount / baseAmount : first.price;
453
- // Use earliest time / smallest sequence for ordering; last time for display is earliest fill
454
- const sorted = [...group.trades].sort((a, b) => a.sequence - b.sequence);
455
- orders.push({
456
- orderId, direction: first.direction, baseAsset: first.baseAsset, quoteAsset: first.quoteAsset,
457
- baseAmount, quoteAmount, price,
458
- time: sorted[0].time,
459
- sequence: sorted[0].sequence,
460
- fillCount: group.trades.length,
461
- isMaker: group.trades.every(t => t.isMaker),
462
- });
463
- }
464
- return orders.sort((a, b) => a.sequence - b.sequence);
465
- }
466
-
467
- // ─── Violation detection (LAST-FILL-GUARD 1:1) ────────────────────────────────
468
- function detectViolations(
469
- items: (TradeFill | AggregatedOrder)[],
470
- includeCrossPair: boolean,
471
- incrementPercent: number,
472
- ): { violations: Violation[]; checkedTransitions: number } {
473
- const violations: Violation[] = [];
474
- let checkedTransitions = 0;
475
-
476
- // Helper for a single chronological sequence (already filtered to one pair or global)
477
- function checkSequence(seq: (TradeFill | AggregatedOrder)[]) {
478
- for (let i = 1; i < seq.length; i++) {
479
- const prev = seq[i - 1] as any;
480
- const curr = seq[i] as any;
481
- // Skip same orderId (multi-fill split of one order) — aggregated mode already collapsed, but per-fill may split
482
- if (prev.orderId && prev.orderId === curr.orderId) continue;
483
- checkedTransitions++;
484
-
485
- const check = isLastFillGuardBlocked(curr.price, curr.direction, prev.price, prev.direction, incrementPercent);
486
- if (check.blocked) {
487
- const delta = curr.price - prev.price;
488
- const deltaPct = prev.price !== 0 ? (delta / prev.price) * 100 : 0;
489
- const isSell = curr.direction === 'sell';
490
- violations.push({
491
- index: i,
492
- pair: `${curr.baseAsset}:${curr.quoteAsset}`,
493
- direction: curr.direction,
494
- expected: isSell ? `> ${check.threshold?.toFixed(6)} (pivot ${check.pivot} +${check.halfInc}%)` : `< ${check.threshold?.toFixed(6)} (pivot ${check.pivot} -${check.halfInc}%)`,
495
- prev: prev as TradeFill,
496
- curr: curr as TradeFill,
497
- priceDelta: delta,
498
- priceDeltaPct: deltaPct,
499
- pivot: check.pivot as number,
500
- halfInc: check.halfInc as number,
501
- threshold: check.threshold as number,
502
- });
503
- }
504
- }
505
- }
506
-
507
- if (includeCrossPair) {
508
- // Global consecutive check regardless of pair
509
- const sorted = [...items].sort((a, b) => (a as any).sequence - (b as any).sequence);
510
- checkSequence(sorted);
511
- } else {
512
- // Per-pair independent sequences (bot trades one pair; cross-pair interleaving is irrelevant)
513
- const byPair = new Map<string, (TradeFill | AggregatedOrder)[]>();
514
- for (const it of items) {
515
- const k = `${(it as any).baseAsset}:${(it as any).quoteAsset}`;
516
- if (!byPair.has(k)) byPair.set(k, []);
517
- byPair.get(k)!.push(it);
518
- }
519
- for (const [, seq] of byPair) {
520
- seq.sort((a: any, b: any) => a.sequence - b.sequence);
521
- checkSequence(seq);
522
- }
523
- }
524
- // Sort violations chronologically for reporting
525
- violations.sort((a, b) => new Date(a.curr.time).getTime() - new Date(b.curr.time).getTime());
526
- return { violations, checkedTransitions };
527
- }
528
-
529
- // ─── Reporting ────────────────────────────────────────────────────────────────
530
- function fmt(n: number, d = 4): string {
531
- if (!Number.isFinite(n)) return 'NaN';
532
- return n.toLocaleString('en-US', { minimumFractionDigits: d, maximumFractionDigits: d });
533
- }
534
-
535
- function printReport(
536
- trades: TradeFill[],
537
- orders: AggregatedOrder[] | null,
538
- violations: Violation[],
539
- checkedTransitions: number,
540
- skipped: number,
541
- rangeLabel: string,
542
- botKey: string,
543
- accountId: string,
544
- botMeta: any,
545
- perFill: boolean,
546
- includeCrossPair: boolean,
547
- incrementPercent: number,
548
- gte: string,
549
- _lte: string,
550
- ) {
551
- const pairGroups = new Map<string, TradeFill[]>();
552
- for (const t of trades) {
553
- const k = `${assetSymbol(t.baseAsset)}/${assetSymbol(t.quoteAsset)}`;
554
- if (!pairGroups.has(k)) pairGroups.set(k, []);
555
- pairGroups.get(k)!.push(t);
556
- }
557
-
558
- const halfInc = incrementPercent / 2;
559
-
560
- console.log('');
561
- console.log('═══════════════════════════════════════════════════════════════════');
562
- console.log(' LAST-FILL-GUARD CHECK (pivot ± halfIncrement)');
563
- console.log('═══════════════════════════════════════════════════════════════════');
564
- console.log(` Bot key: ${botKey}${botMeta?.name ? ` (name: ${botMeta.name})` : ''}`);
565
- if (botMeta) console.log(` Pair: ${botMeta.assetA ?? '?'} / ${botMeta.assetB ?? '?'}`);
566
- console.log(` Account: ${accountId}`);
567
- console.log(` Range: ${rangeLabel}`);
568
- console.log(` Mode: ${perFill ? 'per-fill' : 'per-order (aggregated)'}${includeCrossPair ? ', cross-pair enabled' : ', same-pair only'}`);
569
- console.log(` Increment: ${incrementPercent}% (halfInc ${halfInc}%)`);
570
- console.log(` Guard: BUY < pivot*(1-${halfInc}%) / SELL > pivot*(1+${halfInc}%) — both sides, global pivot`);
571
- console.log('');
572
-
573
- const buyCount = trades.filter(t => t.direction === 'buy').length;
574
- const sellCount = trades.filter(t => t.direction === 'sell').length;
575
- console.log(` Fills fetched: ${trades.length} (buy: ${buyCount}, sell: ${sellCount})`);
576
- if (orders) console.log(` Orders (aggregated): ${orders.length} (from ${trades.length} fills)`);
577
- console.log(` Pairs observed: ${[...pairGroups.keys()].join(', ') || '-'}`);
578
- if (skipped > 0) console.log(` Skipped (precision): ${skipped}`);
579
- console.log(` Transitions checked: ${checkedTransitions} consecutive fill/order transitions`);
580
- console.log(` Violations: ${violations.length}${checkedTransitions > 0 ? ` (${((violations.length / checkedTransitions) * 100).toFixed(2)}%)` : ''}`);
581
- console.log('');
582
-
583
- if (violations.length === 0) {
584
- console.log(' ✅ PASS — no LAST-FILL-GUARD violations detected (all BUY < pivot-half, SELL > pivot+half).');
585
- console.log('');
586
- if (checkedTransitions === 0) {
587
- console.log(' Note: no consecutive transitions in range to check.');
588
- console.log(' (Need at least two fills/orders to form a transition.)');
589
- }
590
- console.log('');
591
- return;
592
- }
593
-
594
- console.log(` ❌ FAIL — ${violations.length} violation(s) detected:`);
595
- console.log('');
596
-
597
- // Per-direction breakdown (blocked side = curr direction)
598
- const buyV = violations.filter(v => v.direction === 'buy').length;
599
- const sellV = violations.filter(v => v.direction === 'sell').length;
600
- console.log(` Breakdown: sell violations: ${sellV} (SELL < pivot+half), buy violations: ${buyV} (BUY > pivot-half)`);
601
- console.log('');
602
-
603
- // Timeline clustering by day
604
- const dayBuckets = new Map<string, number>();
605
- for (const v of violations) {
606
- const day = (v.curr.time || '').slice(0, 10) || 'unknown';
607
- dayBuckets.set(day, (dayBuckets.get(day) || 0) + 1);
608
- }
609
- const sortedDays = [...dayBuckets.entries()].sort((a, b) => a[0].localeCompare(b[0]));
610
- console.log(' Incidents by day:');
611
- for (const [day, count] of sortedDays) {
612
- const bar = '█'.repeat(Math.min(count, 40));
613
- console.log(` ${day} ${String(count).padStart(3)} ${bar}`);
614
- }
615
- // Overall incident time span
616
- const times = violations.map(v => v.curr.time).filter(Boolean).sort();
617
- if (times.length > 0) {
618
- console.log(`\n Incident range: ${times[0]} → ${times[times.length - 1]}`);
619
- // Also show in hours from start
620
- const gteMs = new Date(gte).getTime();
621
- const firstMs = new Date(times[0]).getTime();
622
- const lastMs = new Date(times[times.length - 1]).getTime();
623
- if (!isNaN(gteMs) && !isNaN(firstMs)) {
624
- const firstH = ((firstMs - gteMs) / 3600000).toFixed(1);
625
- const lastH = ((lastMs - gteMs) / 3600000).toFixed(1);
626
- console.log(` (hours into range: ${firstH}h → ${lastH}h)`);
627
- }
628
- }
629
- console.log('');
630
-
631
- // Detailed violation table
632
- console.log(' ── Violations (pivot ± halfIncrement) ──');
633
- console.log('');
634
- const hdr = ' # Pair Dir Prev Price Curr Price Thr Δ% Half% Prev Time Curr Time Prev Order Curr Order';
635
- console.log(hdr);
636
- console.log(' ' + '─'.repeat(hdr.length - 2));
637
- for (let i = 0; i < violations.length; i++) {
638
- const v = violations[i];
639
- const pairLabel = `${assetSymbol(v.prev.baseAsset)}/${assetSymbol(v.prev.quoteAsset)}`.padEnd(12);
640
- const dir = v.direction.padEnd(4);
641
- const pPrice = fmt(v.prev.price, 6).padStart(12);
642
- const cPrice = fmt(v.curr.price, 6).padStart(12);
643
- const thr = fmt(v.threshold, 6).padStart(12);
644
- const delta = (v.priceDeltaPct >= 0 ? '+' : '') + v.priceDeltaPct.toFixed(4) + '%';
645
- const deltaStr = delta.padStart(9);
646
- const halfStr = (v.halfInc.toFixed(3) + '%').padStart(6);
647
- const pTime = (v.prev.time || '').slice(0, 19).replace('T', ' ').padEnd(19);
648
- const cTime = (v.curr.time || '').slice(0, 19).replace('T', ' ').padEnd(19);
649
- const pOrd = (v.prev.orderId || '-').slice(0, 16).padEnd(16);
650
- const cOrd = (v.curr.orderId || '-').slice(0, 16).padEnd(16);
651
- const marker = v.direction === 'sell' ? `SELL < ${fmt(v.threshold,4)}` : `BUY > ${fmt(v.threshold,4)}`;
652
- console.log(` ${(String(i + 1)).padStart(2)} ${pairLabel} ${dir} ${pPrice} ${cPrice} ${thr} ${deltaStr} ${halfStr} ${pTime} ${cTime} ${pOrd} ${cOrd} ${marker}`);
653
- }
654
- console.log('');
655
- console.log(` Guard: BUY must be < pivot*(1-${halfInc}%), SELL > pivot*(1+${halfInc}%) — blocked if violated (mirrors bot).`);
656
- console.log(` Increment ${incrementPercent}% => halfInc ${halfInc}% — e.g. pivot 1000 => BUY thr ${(1000*(1-halfInc/100)).toFixed(4)}, SELL thr ${(1000*(1+halfInc/100)).toFixed(4)}`);
657
- console.log('');
658
- }
659
-
660
- function exportJson(filePath: string, violations: Violation[], trades: TradeFill[], rangeLabel: string, botKey: string, accountId: string, incrementPercent: number) {
661
- const payload = {
662
- botKey, accountId, range: rangeLabel,
663
- incrementPercent,
664
- halfIncrement: incrementPercent / 2,
665
- totalFills: trades.length,
666
- violations: violations.map(v => ({
667
- pair: `${assetSymbol(v.prev.baseAsset)}/${assetSymbol(v.prev.quoteAsset)}`,
668
- pairIds: { base: v.prev.baseAsset, quote: v.prev.quoteAsset },
669
- direction: v.direction,
670
- expected: v.expected,
671
- prev: { time: v.prev.time, orderId: v.prev.orderId, price: v.prev.price, baseAmount: v.prev.baseAmount, quoteAmount: v.prev.quoteAmount, isMaker: v.prev.isMaker },
672
- curr: { time: v.curr.time, orderId: v.curr.orderId, price: v.curr.price, baseAmount: v.curr.baseAmount, quoteAmount: v.curr.quoteAmount, isMaker: v.curr.isMaker },
673
- pivot: v.pivot,
674
- halfInc: v.halfInc,
675
- threshold: v.threshold,
676
- priceDelta: v.priceDelta,
677
- priceDeltaPct: v.priceDeltaPct,
678
- })),
679
- };
680
- fs.writeFileSync(filePath, JSON.stringify(payload, null, 2), 'utf-8');
681
- console.log(` JSON exported to ${filePath}`);
682
- }
683
-
684
- function exportCsv(filePath: string, violations: Violation[]) {
685
- const header = 'index,pair,direction,expected,prev_time,prev_order,prev_price,curr_time,curr_order,curr_price,threshold,halfInc,pivot,delta_pct';
686
- const rows = violations.map((v, i) =>
687
- [
688
- i + 1,
689
- `${assetSymbol(v.prev.baseAsset)}/${assetSymbol(v.prev.quoteAsset)}`,
690
- v.direction, v.expected,
691
- v.prev.time, v.prev.orderId, v.prev.price,
692
- v.curr.time, v.curr.orderId, v.curr.price,
693
- v.threshold, v.halfInc, v.pivot,
694
- v.priceDeltaPct.toFixed(6),
695
- ].map(x => `"${String(x).replace(/"/g, '""')}"`).join(',')
696
- );
697
- fs.writeFileSync(filePath, [header, ...rows].join('\n') + '\n', 'utf-8');
698
- console.log(` CSV exported to ${filePath}`);
699
- }
700
-
701
- // ─── Main ─────────────────────────────────────────────────────────────────────
702
- async function main() {
703
- const opts = parseArgs();
704
- const { gte, lte, label } = resolveTimeRange(opts);
705
-
706
- console.log(`\nLast-fill guard check — bot-key: ${opts.botKey}`);
707
- console.log(`Range: ${label}`);
708
-
709
- const resolvedAccount = await resolveBotAccount(opts.botKey, {
710
- overrideAccount: opts.account,
711
- refresh: opts.refreshAccount,
712
- });
713
- if (!resolvedAccount.accountId) {
714
- reportAccountFailure(resolvedAccount, opts);
715
- process.exit(1);
716
- }
717
- const accountId = resolvedAccount.accountId;
718
- const botMeta = resolvedAccount.botMeta;
719
- console.log(`Account: ${accountId}${botMeta ? ` (${botMeta.assetA}/${botMeta.assetB})` : ''}`);
720
- const incrementPercent = resolveIncrementPercent(botMeta, opts.incrementPercent);
721
- console.log(`Increment: ${incrementPercent}% (halfInc ${incrementPercent/2}%)${opts.incrementPercent == null && botMeta?.incrementPercent != null ? ' — from bot config' : opts.incrementPercent != null ? ' — from --increment' : ' — default'}`);
722
-
723
- console.log(`\nFetching fills and order updates from Kibana...`);
724
- const [fills, orderUpdates] = await Promise.all([
725
- fetchAllFills({}, accountId, gte, lte),
726
- fetchAllOrderUpdates({}, accountId, gte, lte),
727
- ]);
728
- console.log(` Fetched ${fills.length} fill_order operation(s)`);
729
- console.log(` Fetched ${orderUpdates.length} limit_order_update operation(s)`);
730
-
731
- if (fills.length === 0) {
732
- console.log('\nNo fills in range — nothing to check.');
733
- process.exit(0);
734
- }
735
-
736
- await resolveAssetPrecisions(fills);
737
-
738
- const { trades, skipped } = classifyFills(fills);
739
- console.log(` Classified ${trades.length} trade(s)${skipped > 0 ? `, ${skipped} skipped (unknown precision)` : ''}`);
740
- if (trades.length < 2) {
741
- console.log('\nFewer than 2 trade fills — no consecutive pairs to check.');
742
- process.exit(0);
743
- }
744
-
745
- // Sort chronologically
746
- trades.sort((a, b) => a.sequence - b.sequence);
747
-
748
- if (opts.verbose) {
749
- console.log('\n ── Trade sequence ──');
750
- for (let i = 0; i < trades.length; i++) {
751
- const t = trades[i];
752
- const pair = `${assetSymbol(t.baseAsset)}/${assetSymbol(t.quoteAsset)}`;
753
- console.log(` ${String(i + 1).padStart(3)} ${t.time.slice(0, 19)} ${t.direction.padEnd(4)} ${pair.padEnd(18)} price ${fmt(t.price, 6)} order ${t.orderId}`);
754
- }
755
- }
756
-
757
- // Choose per-fill or per-order mode
758
- let items: (TradeFill | AggregatedOrder)[];
759
- if (opts.perFill) {
760
- items = trades;
761
- } else {
762
- const orders = aggregateByOrder(trades, orderUpdates);
763
- console.log(` Aggregated into ${orders.length} order epoch(s) (partial fills collapsed; repriced orders kept separate)`);
764
- items = orders;
765
- }
766
-
767
- const { violations, checkedTransitions } = detectViolations(items, opts.includeCrossPair, incrementPercent);
768
-
769
- const ordersForReport = opts.perFill ? null : (items as AggregatedOrder[]);
770
- printReport(trades, ordersForReport, violations, checkedTransitions, skipped, label, opts.botKey, accountId, botMeta, opts.perFill, opts.includeCrossPair, incrementPercent, gte, lte);
771
-
772
- if (opts.json) exportJson(opts.json, violations, trades, label, opts.botKey, accountId, incrementPercent);
773
- if (opts.csv) exportCsv(opts.csv, violations);
774
-
775
- process.exit(violations.length > 0 ? 2 : 0);
776
- }
777
-
778
- export { isLastFillGuardBlocked, classifyFills, aggregateByOrder, detectViolations, TradeFill, Violation, AggregatedOrder };
779
-
780
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
781
- main().catch(e => {
782
- console.error('\n[fatal]', (e as any)?.message ?? e);
783
- if (process.env.DEBUG) console.error((e as any)?.stack);
784
- process.exit(1);
785
- });
786
- }