dexbot 1.6.11 → 1.6.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 (354) hide show
  1. package/CHANGELOG.md +35 -4
  2. package/README.md +2 -1
  3. package/analysis/README.md +2 -0
  4. package/analysis/tradingview/README.md +1 -1
  5. package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
  6. package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
  7. package/claw/modules/chain_broadcast.ts +7 -1
  8. package/claw/modules/claw_launcher.ts +1 -1
  9. package/claw/modules/launcher_mode_detector.ts +9 -2
  10. package/claw/package.json +1 -1
  11. package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
  12. package/claw/runtimes/openclaw-plugin/package.json +1 -1
  13. package/dist/analysis/account_resolver.d.ts +1 -1
  14. package/dist/analysis/account_resolver.js +2 -1
  15. package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
  16. package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
  17. package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
  18. package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
  19. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
  20. package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
  21. package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
  22. package/dist/analysis/analyze_args.d.ts +31 -0
  23. package/dist/analysis/analyze_args.js +41 -0
  24. package/dist/analysis/analyze_dynamic_weight.js +7 -17
  25. package/dist/analysis/analyze_kalman.js +7 -17
  26. package/dist/analysis/analyze_regime.js +7 -17
  27. package/dist/analysis/analyze_regime_windows.js +8 -18
  28. package/dist/analysis/analyze_risk_profile.js +8 -18
  29. package/dist/analysis/analyze_trade_heatmap.js +7 -17
  30. package/dist/analysis/analyze_volatility.js +7 -17
  31. package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
  32. package/dist/analysis/bot_fitting/backtest_ama_sweep.js +6 -5
  33. package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
  34. package/dist/analysis/bot_fitting/backtest_bot_fitting.js +11 -63
  35. package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
  36. package/dist/analysis/bot_fitting/shared_utils.js +2 -2
  37. package/dist/analysis/bot_key_utils.d.ts +18 -10
  38. package/dist/analysis/bot_key_utils.js +7 -4
  39. package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
  40. package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
  41. package/dist/analysis/chain_pool.d.ts +3 -1
  42. package/dist/analysis/chart_ui.d.ts +5 -2
  43. package/dist/analysis/chart_ui.js +6 -3
  44. package/dist/analysis/chart_utils.d.ts +5 -5
  45. package/dist/analysis/chart_utils.js +9 -0
  46. package/dist/analysis/fills_cache.d.ts +1 -1
  47. package/dist/analysis/fills_source.d.ts +2 -2
  48. package/dist/analysis/fills_source.js +14 -12
  49. package/dist/analysis/grid_correction_check.d.ts +1 -1
  50. package/dist/analysis/grid_correction_check.js +12 -11
  51. package/dist/analysis/math_utils.d.ts +7 -6
  52. package/dist/analysis/math_utils.js +5 -8
  53. package/dist/analysis/pnl_report.js +29 -29
  54. package/dist/analysis/price_sources.d.ts +8 -8
  55. package/dist/analysis/price_sources.js +5 -4
  56. package/dist/analysis/resolve_bot_accounts.js +2 -2
  57. package/dist/analysis/resolve_source.d.ts +1 -1
  58. package/dist/analysis/trade_profitability.d.ts +23 -2
  59. package/dist/analysis/trade_profitability.js +50 -50
  60. package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
  61. package/dist/analysis/tradingview/analyze_tradingview.js +6 -5
  62. package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
  63. package/dist/analysis/tradingview/grid_reset_config.js +23 -11
  64. package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
  65. package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
  66. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
  67. package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +18 -19
  68. package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -1
  69. package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +5 -5
  70. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
  71. package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +5 -4
  72. package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
  73. package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
  74. package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
  75. package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
  76. package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
  77. package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
  78. package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
  79. package/dist/credential-daemon.js +34 -20
  80. package/dist/dexbot.js +11 -11
  81. package/dist/market_adapter/candle_utils.d.ts +22 -18
  82. package/dist/market_adapter/candle_utils.js +24 -20
  83. package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
  84. package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
  85. package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
  86. package/dist/market_adapter/core/kibana_candles.js +9 -7
  87. package/dist/market_adapter/core/kibana_client.d.ts +9 -1
  88. package/dist/market_adapter/core/kibana_client.js +8 -7
  89. package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
  90. package/dist/market_adapter/core/market_adapter_service.d.ts +284 -117
  91. package/dist/market_adapter/core/market_adapter_service.js +137 -113
  92. package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
  93. package/dist/market_adapter/core/strategies/ama.js +2 -4
  94. package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
  95. package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
  96. package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
  97. package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
  98. package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
  99. package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
  100. package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +34 -6
  101. package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
  102. package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
  103. package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
  104. package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
  105. package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
  106. package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
  107. package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
  108. package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
  109. package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
  110. package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
  111. package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
  112. package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +96 -224
  113. package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
  114. package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
  115. package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
  116. package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
  117. package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
  118. package/dist/market_adapter/inputs/kibana_source.js +2 -2
  119. package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
  120. package/dist/market_adapter/inputs/window_cache.js +8 -8
  121. package/dist/market_adapter/interval_utils.d.ts +4 -4
  122. package/dist/market_adapter/log_format.d.ts +6 -6
  123. package/dist/market_adapter/log_format.js +28 -21
  124. package/dist/market_adapter/lp_chart_core.d.ts +22 -1
  125. package/dist/market_adapter/lp_chart_core.js +26 -192
  126. package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
  127. package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
  128. package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
  129. package/dist/market_adapter/market_adapter.d.ts +94 -32
  130. package/dist/market_adapter/market_adapter.js +67 -48
  131. package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
  132. package/dist/market_adapter/utils/adapter_client.js +2 -2
  133. package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
  134. package/dist/market_adapter/utils/chain.d.ts +50 -41
  135. package/dist/market_adapter/utils/chain.js +40 -46
  136. package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
  137. package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
  138. package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
  139. package/dist/market_adapter/utils/file_lock.d.ts +28 -14
  140. package/dist/market_adapter/utils/file_lock.js +36 -32
  141. package/dist/market_adapter/utils/native_history.d.ts +9 -2
  142. package/dist/market_adapter/utils/native_history.js +35 -28
  143. package/dist/modules/account_bots.d.ts +577 -21
  144. package/dist/modules/account_bots.js +182 -158
  145. package/dist/modules/account_orders.d.ts +66 -30
  146. package/dist/modules/account_orders.js +22 -20
  147. package/dist/modules/authority_resolver.d.ts +12 -2
  148. package/dist/modules/authority_resolver.js +15 -8
  149. package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
  150. package/dist/modules/bitshares-native/chain_client.js +45 -46
  151. package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
  152. package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
  153. package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
  154. package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
  155. package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
  156. package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
  157. package/dist/modules/bitshares-native/index.d.ts +1 -1
  158. package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
  159. package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
  160. package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
  161. package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
  162. package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
  163. package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
  164. package/dist/modules/bitshares-native/serial/serializer.js +7 -13
  165. package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
  166. package/dist/modules/bitshares-native/serial/types.js +55 -62
  167. package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
  168. package/dist/modules/bitshares-native/signing_client.js +19 -14
  169. package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
  170. package/dist/modules/bitshares-native/subscriptions.js +12 -12
  171. package/dist/modules/bitshares-native/transport.d.ts +5 -4
  172. package/dist/modules/bitshares-native/transport.js +5 -4
  173. package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
  174. package/dist/modules/bitshares-native/tx/builder.js +4 -3
  175. package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
  176. package/dist/modules/bitshares_client.d.ts +45 -13
  177. package/dist/modules/bitshares_client.js +28 -19
  178. package/dist/modules/bot_defaults.d.ts +6 -15
  179. package/dist/modules/bot_defaults.js +1 -5
  180. package/dist/modules/bot_settings.d.ts +44 -10
  181. package/dist/modules/bot_settings.js +11 -8
  182. package/dist/modules/bots_file_lock.d.ts +6 -6
  183. package/dist/modules/bots_file_lock.js +16 -12
  184. package/dist/modules/broadcast_failure.d.ts +2 -2
  185. package/dist/modules/broadcast_failure.js +5 -4
  186. package/dist/modules/chain_keys.d.ts +42 -40
  187. package/dist/modules/chain_keys.js +53 -45
  188. package/dist/modules/chain_orders.d.ts +93 -59
  189. package/dist/modules/chain_orders.js +31 -23
  190. package/dist/modules/constants.d.ts +527 -31
  191. package/dist/modules/constants.js +15 -47
  192. package/dist/modules/cr_planner.d.ts +40 -2
  193. package/dist/modules/credential_policy.d.ts +68 -8
  194. package/dist/modules/credential_policy.js +37 -31
  195. package/dist/modules/credential_session_cache.d.ts +2 -2
  196. package/dist/modules/credit_pricing.d.ts +42 -6
  197. package/dist/modules/credit_pricing.js +44 -30
  198. package/dist/modules/credit_runtime.d.ts +276 -118
  199. package/dist/modules/credit_runtime.js +462 -165
  200. package/dist/modules/crypto/browser_provider.js +6 -4
  201. package/dist/modules/crypto/node_provider.js +1 -1
  202. package/dist/modules/crypto/pure_scrypt.js +35 -4
  203. package/dist/modules/crypto/pure_secp256k1.js +72 -26
  204. package/dist/modules/crypto/sync.d.ts +9 -9
  205. package/dist/modules/crypto/sync.js +16 -9
  206. package/dist/modules/dexbot_class.d.ts +195 -139
  207. package/dist/modules/dexbot_class.js +78 -28
  208. package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
  209. package/dist/modules/dexbot_cow_runtime.js +248 -206
  210. package/dist/modules/dexbot_credential_client.d.ts +19 -11
  211. package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
  212. package/dist/modules/dexbot_fill_runtime.js +48 -41
  213. package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
  214. package/dist/modules/dexbot_maintenance_runtime.js +108 -83
  215. package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
  216. package/dist/modules/dexbot_startup_runtime.js +43 -43
  217. package/dist/modules/dexbot_state_recovery.d.ts +13 -12
  218. package/dist/modules/dexbot_state_recovery.js +18 -13
  219. package/dist/modules/fund_registry.d.ts +4 -2
  220. package/dist/modules/fund_registry.js +10 -10
  221. package/dist/modules/general_settings.d.ts +30 -4
  222. package/dist/modules/graceful_shutdown.d.ts +3 -3
  223. package/dist/modules/graceful_shutdown.js +2 -2
  224. package/dist/modules/grid_price_source.d.ts +1 -1
  225. package/dist/modules/key_store.d.ts +14 -8
  226. package/dist/modules/key_store.js +7 -6
  227. package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
  228. package/dist/modules/launcher/adapter_requirement.js +5 -5
  229. package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
  230. package/dist/modules/launcher/bot_supervisor.js +12 -11
  231. package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
  232. package/dist/modules/launcher/credential_bootstrap.js +1 -1
  233. package/dist/modules/launcher/credential_daemon.d.ts +4 -4
  234. package/dist/modules/launcher/credential_daemon.js +2 -2
  235. package/dist/modules/launcher/credential_secret.d.ts +1 -1
  236. package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
  237. package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
  238. package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
  239. package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
  240. package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
  241. package/dist/modules/launcher/status_reporting.d.ts +22 -14
  242. package/dist/modules/launcher/supervisor_control.d.ts +8 -1
  243. package/dist/modules/launcher/supervisor_control.js +4 -2
  244. package/dist/modules/market_adapter_whitelist.d.ts +9 -3
  245. package/dist/modules/market_adapter_whitelist.js +15 -3
  246. package/dist/modules/node_manager.d.ts +41 -11
  247. package/dist/modules/node_manager.js +5 -4
  248. package/dist/modules/order/accounting.d.ts +53 -24
  249. package/dist/modules/order/accounting.js +16 -15
  250. package/dist/modules/order/async_lock.d.ts +5 -2
  251. package/dist/modules/order/async_lock.js +1 -1
  252. package/dist/modules/order/export.d.ts +7 -6
  253. package/dist/modules/order/export.js +1 -7
  254. package/dist/modules/order/format.d.ts +4 -4
  255. package/dist/modules/order/genesis_policy.d.ts +21 -18
  256. package/dist/modules/order/genesis_policy.js +12 -8
  257. package/dist/modules/order/grid.d.ts +142 -36
  258. package/dist/modules/order/grid.js +148 -123
  259. package/dist/modules/order/grid_reconcile.d.ts +21 -20
  260. package/dist/modules/order/grid_reconcile.js +13 -12
  261. package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
  262. package/dist/modules/order/grid_reconcile_internal.js +28 -19
  263. package/dist/modules/order/index.d.ts +263 -1
  264. package/dist/modules/order/logger.d.ts +45 -11
  265. package/dist/modules/order/logger.js +38 -40
  266. package/dist/modules/order/logger_state.d.ts +4 -4
  267. package/dist/modules/order/manager.d.ts +225 -180
  268. package/dist/modules/order/manager.js +80 -83
  269. package/dist/modules/order/processed_fill_store.d.ts +18 -3
  270. package/dist/modules/order/processed_fill_store.js +16 -27
  271. package/dist/modules/order/strategy.d.ts +21 -13
  272. package/dist/modules/order/strategy.js +5 -6
  273. package/dist/modules/order/sync_engine.d.ts +91 -33
  274. package/dist/modules/order/sync_engine.js +84 -53
  275. package/dist/modules/order/utils/math.d.ts +157 -102
  276. package/dist/modules/order/utils/math.js +77 -38
  277. package/dist/modules/order/utils/order.d.ts +310 -110
  278. package/dist/modules/order/utils/order.js +122 -99
  279. package/dist/modules/order/utils/slot.d.ts +1 -1
  280. package/dist/modules/order/utils/system.d.ts +176 -26
  281. package/dist/modules/order/utils/system.js +86 -69
  282. package/dist/modules/order/utils/validate.d.ts +89 -41
  283. package/dist/modules/order/utils/validate.js +24 -22
  284. package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
  285. package/dist/modules/order/utils/withPoolRef.js +18 -12
  286. package/dist/modules/order/working_grid.d.ts +14 -13
  287. package/dist/modules/paths.d.ts +1 -4
  288. package/dist/modules/paths.js +1 -27
  289. package/dist/modules/process_discovery.d.ts +1 -1
  290. package/dist/modules/process_discovery.js +2 -1
  291. package/dist/modules/runtime.d.ts +7 -3
  292. package/dist/modules/runtime.js +4 -3
  293. package/dist/modules/runtime_settings.d.ts +15 -10
  294. package/dist/modules/runtime_settings.js +30 -24
  295. package/dist/modules/settings_merge.d.ts +29 -3
  296. package/dist/modules/settings_merge.js +56 -78
  297. package/dist/modules/socket_json_client.d.ts +7 -4
  298. package/dist/modules/storage/browser_adapter.d.ts +38 -53
  299. package/dist/modules/storage/browser_adapter.js +7 -30
  300. package/dist/modules/storage/index.d.ts +1 -1
  301. package/dist/modules/storage/node_adapter.d.ts +45 -27
  302. package/dist/modules/storage/node_adapter.js +9 -9
  303. package/dist/modules/storage/types.d.ts +5 -4
  304. package/dist/modules/types.d.ts +1071 -2
  305. package/dist/modules/types.js +4 -1
  306. package/dist/modules/utils/asset_symbols.d.ts +2 -1
  307. package/dist/modules/utils/asset_symbols.js +2 -1
  308. package/dist/modules/utils/errors.d.ts +9 -0
  309. package/dist/modules/utils/errors.js +23 -1
  310. package/dist/modules/utils/time_range.d.ts +1 -12
  311. package/dist/modules/utils/time_range.js +1 -1
  312. package/dist/modules/validate_profiles.js +53 -43
  313. package/dist/modules/version_notice.d.ts +14 -3
  314. package/dist/modules/version_notice.js +6 -4
  315. package/dist/pm2.d.ts +29 -27
  316. package/dist/pm2.js +5 -5
  317. package/dist/scripts/analyze-credit.d.ts +2 -1
  318. package/dist/scripts/analyze-credit.js +23 -24
  319. package/dist/scripts/analyze-orders.d.ts +77 -9
  320. package/dist/scripts/analyze-orders.js +65 -40
  321. package/dist/scripts/chart_command.d.ts +27 -18
  322. package/dist/scripts/chart_command.js +13 -11
  323. package/dist/scripts/check_any.d.ts +18 -0
  324. package/dist/scripts/check_any.js +126 -0
  325. package/dist/scripts/diagnose-pool-history.js +12 -7
  326. package/dist/scripts/print_grid.js +0 -1
  327. package/dist/scripts/run-tests.js +39 -7
  328. package/dist/scripts/runner.js +1 -1
  329. package/dist/scripts/test-credit-renewal.js +30 -21
  330. package/dist/scripts/update.d.ts +10 -5
  331. package/dist/scripts/update.js +168 -103
  332. package/dist/scripts/update_dist_freshness.js +1 -0
  333. package/dist/scripts/update_layout.d.ts +61 -0
  334. package/dist/scripts/update_layout.js +180 -0
  335. package/dist/scripts/validate_bots.js +2 -1
  336. package/dist/scripts/verify-browser-bundle.js +8 -0
  337. package/dist/unlock.d.ts +28 -3
  338. package/dist/unlock.js +63 -35
  339. package/docs/BITSHARES_ONBOARDING.md +2 -0
  340. package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
  341. package/docs/COW_INVARIANTS.md +13 -6
  342. package/docs/DEXBOT_COMPARISON.md +8 -8
  343. package/docs/EVOLUTION.md +10 -9
  344. package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
  345. package/docs/GRID_RECALCULATION.md +4 -2
  346. package/docs/GRID_RECONCILE.md +14 -3
  347. package/docs/LIFECYCLE.md +11 -11
  348. package/docs/MPA_CREDIT_USAGE.md +22 -3
  349. package/docs/README.md +14 -3
  350. package/docs/architecture.md +12 -9
  351. package/docs/developer_guide.md +6 -6
  352. package/market_adapter/README.md +6 -1
  353. package/modules/README.md +4 -1
  354. package/package.json +4 -1
@@ -94,16 +94,14 @@ function hasLending(bot) {
94
94
  // shared with the live credit runtime) — no local copies here.
95
95
  import { averageCollateralRatio as averageCreditCr, creditDealCollateralRatio as creditDealCr, dailyOfferFeeRate, extractOfferConversionRate, normalizeCollateralMap as normalizeOfferCollateralMap, } from '../modules/credit_pricing.js';
96
96
  function lendingAssetsOfType(bot, type) {
97
- if (!hasLending(bot))
98
- return [];
99
- return bot.debtPolicy.lending
97
+ const items = bot.debtPolicy?.lending ?? [];
98
+ return items
100
99
  .filter((item) => item && item.type === type && typeof item.asset === 'string' && item.asset.length > 0)
101
100
  .map((item) => String(item.asset));
102
101
  }
103
102
  function allLendingAssets(bot) {
104
- if (!hasLending(bot))
105
- return [];
106
- return bot.debtPolicy.lending
103
+ const items = bot.debtPolicy?.lending ?? [];
104
+ return items
107
105
  .filter((item) => item && typeof item.asset === 'string' && item.asset.length > 0)
108
106
  .map((item) => String(item.asset));
109
107
  }
@@ -271,8 +269,9 @@ async function main() {
271
269
  const res = await dbCall('get_objects', [batch]);
272
270
  if (Array.isArray(res)) {
273
271
  for (const o of res) {
274
- if (o?.id)
275
- out.set(String(o.id), o);
272
+ const offer = o;
273
+ if (offer?.id)
274
+ out.set(String(offer.id), offer);
276
275
  }
277
276
  }
278
277
  }
@@ -301,9 +300,10 @@ async function main() {
301
300
  if (!Array.isArray(rows) || rows.length === 0)
302
301
  break;
303
302
  for (const o of rows) {
304
- if (o?.id && !seen.has(String(o.id))) {
305
- seen.add(String(o.id));
306
- out.push(o);
303
+ const offer = o;
304
+ if (offer?.id && !seen.has(String(offer.id))) {
305
+ seen.add(String(offer.id));
306
+ out.push(offer);
307
307
  }
308
308
  }
309
309
  if (rows.length < 100)
@@ -324,7 +324,7 @@ async function main() {
324
324
  const out = new Map();
325
325
  try {
326
326
  const res = await dbCall('get_full_accounts', [[account], false]);
327
- const entry = Array.isArray(res) && Array.isArray(res[0]) && res[0].length >= 2 ? res[0][1] : res?.[0];
327
+ const entry = (Array.isArray(res) && Array.isArray(res[0]) && res[0].length >= 2 ? res[0][1] : res?.[0]);
328
328
  const balances = entry?.balances || [];
329
329
  for (const b of balances) {
330
330
  const aid = String(b?.asset_type || b?.asset_id || b?.asset || '');
@@ -437,11 +437,12 @@ async function main() {
437
437
  const debt = new Map();
438
438
  const coll = new Map();
439
439
  for (const it of items) {
440
+ const item = it;
440
441
  if (kind === 'mpa') {
441
- const dId = mpaDebtAssetId(it);
442
- const cId = mpaCollateralAssetId(it);
443
- const dRaw = mpaDebtRaw(it);
444
- const cRaw = mpaCollateralRaw(it);
442
+ const dId = mpaDebtAssetId(item);
443
+ const cId = mpaCollateralAssetId(item);
444
+ const dRaw = mpaDebtRaw(item);
445
+ const cRaw = mpaCollateralRaw(item);
445
446
  if (dId) {
446
447
  const f = await toFloat(dRaw, dId);
447
448
  if (f != null) {
@@ -464,10 +465,10 @@ async function main() {
464
465
  }
465
466
  }
466
467
  else {
467
- const dId = typeof it?.debt_asset === 'string' ? it.debt_asset : null;
468
- const cId = typeof it?.collateral_asset === 'string' ? it.collateral_asset : null;
469
- const dRaw = Number(it?.debt_amount);
470
- const cRaw = Number(it?.collateral_amount);
468
+ const dId = typeof item.debt_asset === 'string' ? item.debt_asset : null;
469
+ const cId = typeof item.collateral_asset === 'string' ? item.collateral_asset : null;
470
+ const dRaw = Number(item.debt_amount);
471
+ const cRaw = Number(item.collateral_amount);
471
472
  if (dId && Number.isFinite(dRaw)) {
472
473
  const f = await toFloat(dRaw, dId);
473
474
  if (f != null) {
@@ -475,7 +476,7 @@ async function main() {
475
476
  e.total += f;
476
477
  e.count += 1;
477
478
  e.max = Math.max(e.max, f);
478
- const ms = parseExpiryMs(it?.latest_repay_time ?? it?.latestRepayTime);
479
+ const ms = parseExpiryMs(item.latest_repay_time ?? item.latestRepayTime);
479
480
  if (ms !== null && (e.earliest == null || ms < e.earliest))
480
481
  e.earliest = ms;
481
482
  debt.set(dId, e);
@@ -510,9 +511,7 @@ async function main() {
510
511
  // (type creditOffer) AND the pair is listed on the current credit
511
512
  // offer (acceptable_collateral). Anything else is reported separately
512
513
  // as ignored/unpriced and excluded from the average CR.
513
- const lendingItems = hasLending(bot) && Array.isArray(bot.debtPolicy?.lending)
514
- ? bot.debtPolicy.lending
515
- : [];
514
+ const lendingItems = bot.debtPolicy?.lending ?? [];
516
515
  // Configured credit pairs drive the whitelist, per-pair CR lines, and
517
516
  // the borrow-now preview.
518
517
  const creditPairs = [];
@@ -14,6 +14,74 @@
14
14
  * node dist/scripts/analyze-orders.js --export # standalone HTML report
15
15
  */
16
16
  import { CLI_COLORS as colors } from '../modules/cli_colors.js';
17
+ /** Loose JSON-object view used across the analyzer. */
18
+ type JsonObj = Record<string, unknown>;
19
+ interface GridSlot {
20
+ type?: string;
21
+ state?: string;
22
+ price: number;
23
+ size: number;
24
+ orderId?: string | null;
25
+ [key: string]: unknown;
26
+ }
27
+ interface GridSnapshot {
28
+ meta?: JsonObj;
29
+ grid?: GridSlot[];
30
+ assets?: {
31
+ assetA?: {
32
+ symbol?: unknown;
33
+ };
34
+ assetB?: {
35
+ symbol?: unknown;
36
+ };
37
+ };
38
+ boundaryIdx?: number | null;
39
+ [key: string]: unknown;
40
+ }
41
+ interface WeightSnapshot {
42
+ effectiveWeights?: JsonObj;
43
+ baseWeights?: JsonObj;
44
+ rawAsymmetryFactor?: unknown;
45
+ appliedAsymmetryFactor?: unknown;
46
+ maxAsymmetryFactor?: unknown;
47
+ isReady?: unknown;
48
+ trend?: unknown;
49
+ finalOffset?: unknown;
50
+ [key: string]: unknown;
51
+ }
52
+ interface DynamicGridSnapshot extends GridSnapshot {
53
+ dynamicWeights?: WeightSnapshot;
54
+ asymmetricBounds?: JsonObj;
55
+ amaCenterPrice?: unknown;
56
+ gridCenterPrice?: unknown;
57
+ updatedAt?: unknown;
58
+ }
59
+ interface BotConfig {
60
+ name?: unknown;
61
+ minPrice?: unknown;
62
+ maxPrice?: unknown;
63
+ targetSpreadPercent?: unknown;
64
+ incrementPercent?: unknown;
65
+ gridPrice?: unknown;
66
+ activeOrders?: unknown;
67
+ botFunds?: JsonObj;
68
+ weightDistribution?: JsonObj;
69
+ [key: string]: unknown;
70
+ }
71
+ interface DynamicWeightInfo {
72
+ amaCenterPrice?: unknown;
73
+ rawAsymmetryFactor?: unknown;
74
+ appliedAsymmetryFactor?: unknown;
75
+ trend?: unknown;
76
+ isRecent?: unknown;
77
+ minPrice?: unknown;
78
+ maxPrice?: unknown;
79
+ effectiveWeights?: JsonObj;
80
+ baseWeights?: JsonObj;
81
+ live?: JsonObj | null;
82
+ base?: JsonObj | null;
83
+ [key: string]: unknown;
84
+ }
17
85
  declare const DYNAMIC_GRID_SNAPSHOT_MAX_AGE_MS: number;
18
86
  declare const DYNAMIC_WEIGHT_EPSILON = 0.005;
19
87
  /**
@@ -23,9 +91,9 @@ declare const DYNAMIC_WEIGHT_EPSILON = 0.005;
23
91
  * analyzer only attempts to load a dynamic grid snapshot for AMA bots. Non-AMA
24
92
  * bots never have a meaningful dynamic grid file.
25
93
  */
26
- declare function isAmaGridPrice(config: any): boolean;
27
- declare function resolveAmaKey(config: any): string | null;
28
- declare function readDynamicGridSnapshot(botKey: string): any;
94
+ declare function isAmaGridPrice(config: unknown): boolean;
95
+ declare function resolveAmaKey(config: unknown): string | null;
96
+ declare function readDynamicGridSnapshot(botKey: string): DynamicGridSnapshot | null;
29
97
  /**
30
98
  * buildDynamicWeightInfo: Extract a display-ready market-adapter payload.
31
99
  *
@@ -34,7 +102,7 @@ declare function readDynamicGridSnapshot(botKey: string): any;
34
102
  * whitelisted and the snapshot contains effective weights. AMA center and
35
103
  * freshness status remain available for AMA-only bots.
36
104
  */
37
- declare function buildDynamicWeightInfo(botKey: string, config: any): any;
105
+ declare function buildDynamicWeightInfo(botKey: string, config: BotConfig): DynamicWeightInfo | null;
38
106
  /**
39
107
  * analyzeOrder: Comprehensive analysis of a single bot's order grid
40
108
  *
@@ -56,7 +124,7 @@ declare function buildDynamicWeightInfo(botKey: string, config: any): any;
56
124
  * @param {string} [botKey] - Bot key used to locate the dynamic grid snapshot
57
125
  * @returns {Object} Analysis result with spread, increment, funds, distribution
58
126
  */
59
- declare function analyzeOrder(botData: any, config: any, botKey: string): any;
127
+ declare function analyzeOrder(botData: GridSnapshot, config: BotConfig, botKey: string): JsonObj;
60
128
  /**
61
129
  * getRawWeightValues: Extract raw buy/sell value strings for column alignment,
62
130
  * without any color codes or formatting artifacts.
@@ -67,7 +135,7 @@ declare function analyzeOrder(botData: any, config: any, botKey: string): any;
67
135
  * @param {Object|null} dynamicWeight
68
136
  * @returns {{ buy: string, sell: string } | null}
69
137
  */
70
- declare function getRawWeightValues(weightDistribution: any, dynamicWeight: any): {
138
+ declare function getRawWeightValues(weightDistribution: JsonObj | null, dynamicWeight: DynamicWeightInfo | null): {
71
139
  buy: string;
72
140
  sell: string;
73
141
  } | null;
@@ -88,7 +156,7 @@ declare function getRawWeightValues(weightDistribution: any, dynamicWeight: any)
88
156
  * @param {number} [maxSellWidth] - Target width for sell-side values (for column alignment)
89
157
  * @returns {string|null} Formatted weight line or null if no valid data
90
158
  */
91
- declare function formatWeightLine(weightDistribution: any, dynamicWeight: any, maxBuyWidth?: number, maxSellWidth?: number): string | null;
159
+ declare function formatWeightLine(weightDistribution: JsonObj | null, dynamicWeight: DynamicWeightInfo | null, maxBuyWidth?: number, maxSellWidth?: number): string | null;
92
160
  /**
93
161
  * formatAnalysis: Format analysis results into readable console output
94
162
  *
@@ -117,7 +185,7 @@ declare function formatWeightLine(weightDistribution: any, dynamicWeight: any, m
117
185
  * @param {Object} analysis - Analysis result object from analyzeOrder()
118
186
  * @returns {string} Formatted multi-line output ready for console.log
119
187
  */
120
- declare function formatAnalysis(analysis: any): string;
188
+ declare function formatAnalysis(analysisInput: JsonObj): string;
121
189
  /**
122
190
  * main: Entry point - analyze all order files and display results
123
191
  *
@@ -148,6 +216,6 @@ declare function formatAnalysis(analysis: any): string;
148
216
  *
149
217
  * @param {Array<Object>} analyses - Array of analysis results from analyzeOrder()
150
218
  */
151
- declare function generateHtmlReport(analyses: any[]): void;
219
+ declare function generateHtmlReport(analyses: JsonObj[]): void;
152
220
  export { resolveAmaKey, isAmaGridPrice, readDynamicGridSnapshot, buildDynamicWeightInfo, formatWeightLine, getRawWeightValues, analyzeOrder, formatAnalysis, generateHtmlReport, colors, DYNAMIC_GRID_SNAPSHOT_MAX_AGE_MS, DYNAMIC_WEIGHT_EPSILON };
153
221
  //# sourceMappingURL=analyze-orders.d.ts.map
@@ -54,7 +54,7 @@ const HEADER_WIDTH = 11 + BAR_WIDTH;
54
54
  */
55
55
  function createBotKey(bot, index) {
56
56
  if (bot && bot.name) {
57
- return sanitizeKey(bot.name);
57
+ return sanitizeKey(String(bot.name));
58
58
  }
59
59
  const identifier = bot && bot.assetA && bot.assetB
60
60
  ? `${bot.assetA}/${bot.assetB}`
@@ -64,9 +64,10 @@ function createBotKey(bot, index) {
64
64
  return `${sanitizeKey(identifier)}-${index}`;
65
65
  }
66
66
  function hasOrderGrid(data) {
67
- return Boolean(data && typeof data === 'object' && !Array.isArray(data) &&
68
- data.meta && typeof data.meta === 'object' &&
69
- Array.isArray(data.grid));
67
+ if (!data || typeof data !== 'object' || Array.isArray(data))
68
+ return false;
69
+ const d = data;
70
+ return Boolean(d.meta && typeof d.meta === 'object' && Array.isArray(d.grid));
70
71
  }
71
72
  /**
72
73
  * isAmaGridPrice: Detect bots whose grid price follows the AMA (Kaufman) stream.
@@ -82,7 +83,8 @@ function isAmaGridPrice(config) {
82
83
  function resolveAmaKey(config) {
83
84
  if (!config || typeof config !== 'object')
84
85
  return null;
85
- const gridPrice = typeof config.gridPrice === 'string' ? config.gridPrice.trim().toLowerCase() : '';
86
+ const cfg = config;
87
+ const gridPrice = typeof cfg.gridPrice === 'string' ? cfg.gridPrice.trim().toLowerCase() : '';
86
88
  if (!/^ama(?:[1-4])?$/.test(gridPrice))
87
89
  return null;
88
90
  if (gridPrice === 'ama')
@@ -158,8 +160,8 @@ function buildDynamicWeightInfo(botKey, config) {
158
160
  let live = null;
159
161
  let base = null;
160
162
  if (hasDynamicWeightData) {
161
- const effBuy = Number(dw.effectiveWeights.buy);
162
- const effSell = Number(dw.effectiveWeights.sell);
163
+ const effBuy = Number(dw.effectiveWeights?.buy);
164
+ const effSell = Number(dw.effectiveWeights?.sell);
163
165
  if (Number.isFinite(effBuy) && Number.isFinite(effSell)) {
164
166
  const baseFromSnapshot = dw.baseWeights && typeof dw.baseWeights === 'object' ? dw.baseWeights : null;
165
167
  const baseBuy = baseFromSnapshot && Number.isFinite(Number(baseFromSnapshot.buy))
@@ -223,14 +225,15 @@ function buildDynamicWeightInfo(botKey, config) {
223
225
  function isRealGridOrder(order) {
224
226
  if (!order || typeof order !== 'object')
225
227
  return false;
226
- const hasRealState = order.state === ORDER_STATES.ACTIVE || order.state === ORDER_STATES.PARTIAL;
227
- const hasRealType = order.type === ORDER_TYPES.BUY || order.type === ORDER_TYPES.SELL;
228
- const hasOrderId = typeof order.orderId === 'string' && order.orderId.trim().length > 0;
228
+ const o = order;
229
+ const hasRealState = o.state === ORDER_STATES.ACTIVE || o.state === ORDER_STATES.PARTIAL;
230
+ const hasRealType = o.type === ORDER_TYPES.BUY || o.type === ORDER_TYPES.SELL;
231
+ const hasOrderId = typeof o.orderId === 'string' && o.orderId.trim().length > 0;
229
232
  return hasRealState
230
233
  && hasRealType
231
234
  && hasOrderId
232
- && Number(order.price) > 0
233
- && Number(order.size) > 0;
235
+ && Number(o.price) > 0
236
+ && Number(o.size) > 0;
234
237
  }
235
238
  function getRealGridOrders(botData) {
236
239
  return Array.isArray(botData?.grid) ? botData.grid.filter(isRealGridOrder) : [];
@@ -269,7 +272,7 @@ function stripColorCodes(str) {
269
272
  * @returns {string} Padded string with original colors preserved
270
273
  */
271
274
  // Load bot configurations
272
- const botsConfig = readJSON(BOTS_CONFIG).bots;
275
+ const botsConfig = readJSON(BOTS_CONFIG).bots ?? [];
273
276
  /**
274
277
  * formatBotFunds: Normalize a botFunds side value for display.
275
278
  *
@@ -366,8 +369,8 @@ function getOrderFiles() {
366
369
  * @returns {Object} Analysis result with spread, increment, funds, distribution
367
370
  */
368
371
  function analyzeOrder(botData, config, botKey) {
369
- const meta = botData.meta;
370
- const grid = botData.grid;
372
+ const meta = botData.meta || {};
373
+ const grid = Array.isArray(botData.grid) ? botData.grid : [];
371
374
  // Extract asset pair: prioritize assets object from order data, fall back to meta
372
375
  let assetA = meta.assetA;
373
376
  let assetB = meta.assetB;
@@ -383,9 +386,20 @@ function analyzeOrder(botData, config, botKey) {
383
386
  * The grid contains buy slots (prices below market), sell slots (above market),
384
387
  * and optional spread slots. Separation enables independent analysis.
385
388
  */
386
- const boundaryIdx = botData.boundaryIdx;
387
- const buySlots = grid.filter((s, i) => i <= boundaryIdx && s.type === ORDER_TYPES.BUY);
388
- const sellSlots = grid.filter((s, i) => i > boundaryIdx && s.type === ORDER_TYPES.SELL);
389
+ // A persisted boundary can be absent: GRID-LOAD erases a poisoned boundary
390
+ // (clearPersistedBoundary) and keeps running boundary-less until fills
391
+ // re-anchor. Index-based rail slicing then degenerates (null coerces to 0),
392
+ // hiding live rail orders. Detect it and classify by slot type so every live
393
+ // order stays visible in the report.
394
+ const hasBoundary = typeof botData.boundaryIdx === 'number' && Number.isFinite(botData.boundaryIdx);
395
+ const boundaryIdx = hasBoundary ? botData.boundaryIdx : 0;
396
+ const boundaryLess = !hasBoundary;
397
+ const buySlots = boundaryLess
398
+ ? grid.filter((s) => s.type === ORDER_TYPES.BUY)
399
+ : grid.filter((s, i) => i <= boundaryIdx && s.type === ORDER_TYPES.BUY);
400
+ const sellSlots = boundaryLess
401
+ ? grid.filter((s) => s.type === ORDER_TYPES.SELL)
402
+ : grid.filter((s, i) => i > boundaryIdx && s.type === ORDER_TYPES.SELL);
389
403
  const spreadSlots = grid.filter((s) => s.type === ORDER_TYPES.SPREAD);
390
404
  const activeBuySlots = buySlots.filter((s) => s.state === ORDER_STATES.ACTIVE || s.state === ORDER_STATES.PARTIAL);
391
405
  const virtualBuySlots = buySlots.filter((s) => s.state === ORDER_STATES.VIRTUAL);
@@ -410,13 +424,15 @@ function analyzeOrder(botData, config, botKey) {
410
424
  // design (a partially-placed grid IS partially masked); it is not a bug, but
411
425
  // the output should be read with that caveat in mind.
412
426
  const hasOrderId = (s) => !!(s && s.orderId);
413
- const placedBuys = grid.slice(0, boundaryIdx + 1).filter((s) => s.type === ORDER_TYPES.BUY && hasOrderId(s));
414
- const placedSells = grid.slice(boundaryIdx + 1).filter((s) => s.type === ORDER_TYPES.SELL && hasOrderId(s));
415
- const geoBuy = grid.slice(0, boundaryIdx + 1).filter((s) => s.type === ORDER_TYPES.BUY);
416
- const geoSell = grid.slice(boundaryIdx + 1).filter((s) => s.type === ORDER_TYPES.SELL);
427
+ const railBuys = boundaryLess ? grid.filter((s) => s.type === ORDER_TYPES.BUY) : grid.slice(0, boundaryIdx + 1);
428
+ const railSells = boundaryLess ? grid.filter((s) => s.type === ORDER_TYPES.SELL) : grid.slice(boundaryIdx + 1);
429
+ const placedBuys = railBuys.filter((s) => s.type === ORDER_TYPES.BUY && hasOrderId(s));
430
+ const placedSells = railSells.filter((s) => s.type === ORDER_TYPES.SELL && hasOrderId(s));
431
+ const geoBuy = railBuys.filter((s) => s.type === ORDER_TYPES.BUY);
432
+ const geoSell = railSells.filter((s) => s.type === ORDER_TYPES.SELL);
417
433
  const bestBuySlot = placedBuys.length
418
434
  ? placedBuys.reduce((a, b) => (b.price > a.price ? b : a))
419
- : (geoBuy.length ? geoBuy.reduce((a, b) => (b.price > a.price ? b : a)) : (grid[boundaryIdx] || null));
435
+ : (geoBuy.length ? geoBuy.reduce((a, b) => (b.price > a.price ? b : a)) : (boundaryLess ? null : (grid[boundaryIdx] || null)));
420
436
  const bestSellSlot = placedSells.length
421
437
  ? placedSells.reduce((a, b) => (b.price < a.price ? b : a))
422
438
  : (geoSell.length ? geoSell.reduce((a, b) => (b.price < a.price ? b : a)) : null);
@@ -437,9 +453,9 @@ function analyzeOrder(botData, config, botKey) {
437
453
  */
438
454
  if (config) {
439
455
  // Config exists - calculate variance from target
440
- targetSpread = config.targetSpreadPercent / 100;
456
+ targetSpread = Number(config.targetSpreadPercent) / 100;
441
457
  spreadDiff = realSpread - targetSpread;
442
- incrementCheck = checkGeometricIncrement(grid, config.incrementPercent / 100);
458
+ incrementCheck = checkGeometricIncrement(grid, Number(config.incrementPercent) / 100);
443
459
  }
444
460
  else {
445
461
  // No config - report actual values only
@@ -481,7 +497,7 @@ function analyzeOrder(botData, config, botKey) {
481
497
  return {
482
498
  pair: `${assetA}/${assetB}`,
483
499
  botName: config?.name || botKey,
484
- lastUpdated: new Date(meta.updatedAt || botData.lastUpdated),
500
+ lastUpdated: new Date(String(meta.updatedAt || botData.lastUpdated)),
485
501
  gridMinPrice: gridMinPrice,
486
502
  marketPrice: marketPrice,
487
503
  gridMaxPrice: gridMaxPrice,
@@ -502,6 +518,9 @@ function analyzeOrder(botData, config, botKey) {
502
518
  virtualFunds: virtualGridFunds,
503
519
  // Slot vs fund distribution analysis
504
520
  distribution: distribution,
521
+ // True when the snapshot carries no boundary (poisoned-boundary erasure):
522
+ // slot rows are classified by slot type, not rail geometry.
523
+ boundaryLess: boundaryLess,
505
524
  // Slot counts for structure overview
506
525
  slots: {
507
526
  buy: buySlots.length,
@@ -548,11 +567,11 @@ function computeGridRangeScalingDisplay(config, dynamicWeight) {
548
567
  if (!dynamicWeight || dynamicWeight.amaCenterPrice == null) {
549
568
  return null;
550
569
  }
551
- const centerPrice = dynamicWeight.amaCenterPrice;
570
+ const centerPrice = Number(dynamicWeight.amaCenterPrice);
552
571
  let minPrice, maxPrice;
553
572
  try {
554
- minPrice = resolveConfiguredPriceBound(config && config.minPrice, undefined, centerPrice, 'min');
555
- maxPrice = resolveConfiguredPriceBound(config && config.maxPrice, undefined, centerPrice, 'max');
573
+ minPrice = resolveConfiguredPriceBound((config && config.minPrice), undefined, centerPrice, 'min');
574
+ maxPrice = resolveConfiguredPriceBound((config && config.maxPrice), undefined, centerPrice, 'max');
556
575
  }
557
576
  catch (_) {
558
577
  return null;
@@ -564,7 +583,7 @@ function computeGridRangeScalingDisplay(config, dynamicWeight) {
564
583
  let resolvedMinPrice = minPrice;
565
584
  let resolvedMaxPrice = maxPrice;
566
585
  if (hasAsym) {
567
- const prices = computeAsymmetricBoundsPrices(centerPrice, minPrice, maxPrice, dynamicWeight.trend, dynamicWeight.appliedAsymmetryFactor);
586
+ const prices = computeAsymmetricBoundsPrices(centerPrice, minPrice, maxPrice, dynamicWeight.trend, Number(dynamicWeight.appliedAsymmetryFactor));
568
587
  if (prices) {
569
588
  resolvedMinPrice = prices.resolvedMinPrice;
570
589
  resolvedMaxPrice = prices.resolvedMaxPrice;
@@ -971,13 +990,13 @@ function getRawWeightValues(weightDistribution, dynamicWeight) {
971
990
  const useLive = !!(dynamicWeight
972
991
  && dynamicWeight.isRecent
973
992
  && dynamicWeight.live
974
- && Number.isFinite(Number(dynamicWeight.live.buy))
975
- && Number.isFinite(Number(dynamicWeight.live.sell)));
993
+ && Number.isFinite(Number(dynamicWeight.live?.buy))
994
+ && Number.isFinite(Number(dynamicWeight.live?.sell)));
976
995
  if (!useLive) {
977
996
  return { buy: staticBuy.toFixed(2), sell: staticSell.toFixed(2) };
978
997
  }
979
- const liveBuy = Number(dynamicWeight.live.buy);
980
- const liveSell = Number(dynamicWeight.live.sell);
998
+ const liveBuy = Number(dynamicWeight.live?.buy);
999
+ const liveSell = Number(dynamicWeight.live?.sell);
981
1000
  return {
982
1001
  buy: liveBuy.toFixed(2),
983
1002
  sell: liveSell.toFixed(2)
@@ -1021,15 +1040,15 @@ function formatWeightLine(weightDistribution, dynamicWeight, maxBuyWidth, maxSel
1021
1040
  const useLive = !!(dynamicWeight
1022
1041
  && dynamicWeight.isRecent
1023
1042
  && dynamicWeight.live
1024
- && Number.isFinite(Number(dynamicWeight.live.buy))
1025
- && Number.isFinite(Number(dynamicWeight.live.sell)));
1043
+ && Number.isFinite(Number(dynamicWeight.live?.buy))
1044
+ && Number.isFinite(Number(dynamicWeight.live?.sell)));
1026
1045
  if (!useLive) {
1027
1046
  const buyVal = staticBuy.toFixed(2);
1028
1047
  const sellVal = staticSell.toFixed(2);
1029
1048
  return ` Weight: ${maxBuyWidth ? buyVal.padEnd(maxBuyWidth) : buyVal} ${colors.buy}buy${colors.reset} | ${maxSellWidth ? sellVal.padEnd(maxSellWidth) : sellVal} ${colors.sell}sell${colors.reset}`;
1030
1049
  }
1031
- const liveBuy = Number(dynamicWeight.live.buy);
1032
- const liveSell = Number(dynamicWeight.live.sell);
1050
+ const liveBuy = Number(dynamicWeight.live?.buy);
1051
+ const liveSell = Number(dynamicWeight.live?.sell);
1033
1052
  // Compare the two live weights, not their deltas: the side with the larger
1034
1053
  // live weight is the one the bot is leaning on most heavily (the "losing"
1035
1054
  // side for that asset). When the two live weights are equal, no side is
@@ -1089,11 +1108,17 @@ function formatWeightLine(weightDistribution, dynamicWeight, maxBuyWidth, maxSel
1089
1108
  * @param {Object} analysis - Analysis result object from analyzeOrder()
1090
1109
  * @returns {string} Formatted multi-line output ready for console.log
1091
1110
  */
1092
- function formatAnalysis(analysis) {
1111
+ function formatAnalysis(analysisInput) {
1112
+ const analysis = analysisInput;
1093
1113
  const lines = [];
1094
1114
  // Header: Trading pair name
1095
1115
  lines.push(`\n${colors.cyan}📊 ${analysis.pair}${colors.reset} (${analysis.botName})`);
1096
1116
  lines.push(` ${colors.gray}Update: ${analysis.lastUpdated.toLocaleString()}${colors.reset}`);
1117
+ // Boundary-less snapshot: say so out loud so geometry rows are read as
1118
+ // type-based counts, not rail positions.
1119
+ if (analysis.boundaryLess) {
1120
+ lines.push(` ${colors.gray}⚠️ boundary-less mode - slot rows by slot type (no rail geometry)${colors.reset}`);
1121
+ }
1097
1122
  lines.push(``);
1098
1123
  // Warning: No config available for comparison
1099
1124
  if (!analysis.hasConfig) {
@@ -1106,7 +1131,7 @@ function formatAnalysis(analysis) {
1106
1131
  * Direction: ↑ if above target, ↓ if below target
1107
1132
  */
1108
1133
  if (analysis.hasConfig) {
1109
- lines.push(` Spread:${formatPercent(analysis.spread.real).padStart(6)} (${formatPercent(analysis.spread.target)}) | Incr.:${formatPercent(analysis.increment.avg).padStart(6)} (${formatPercent(analysis.increment.target)})`);
1134
+ lines.push(` Spread:${formatPercent(analysis.spread.real).padStart(6)} (${formatPercent(Number(analysis.spread.target))}) | Incr.:${formatPercent(analysis.increment.avg).padStart(6)} (${formatPercent(Number(analysis.increment.target))})`);
1110
1135
  }
1111
1136
  else {
1112
1137
  lines.push(` Spread:${formatPercent(analysis.spread.real).padStart(6)} | Incr.:${formatPercent(analysis.increment.avg).padStart(6)}`);
@@ -1,4 +1,27 @@
1
1
  #!/usr/bin/env node
2
+ interface AssetMeta {
3
+ id?: string;
4
+ precision?: number;
5
+ symbol?: string;
6
+ [key: string]: unknown;
7
+ }
8
+ interface ChainClientLike {
9
+ BitShares?: {
10
+ db?: Record<string, (...args: unknown[]) => Promise<unknown>>;
11
+ };
12
+ }
13
+ interface MpaBackingCtx {
14
+ [key: string]: unknown;
15
+ mpa: AssetMeta;
16
+ backing: AssetMeta;
17
+ isPredictionMarket: boolean;
18
+ feedPublicationTime: string | null;
19
+ }
20
+ interface FeedCtx {
21
+ [key: string]: unknown;
22
+ kind: string;
23
+ legs: MpaBackingCtx[];
24
+ }
2
25
  declare const FEED_STALE_WARN_AGE_MS: number;
3
26
  /** Chart command identity: 'tv' → TradingView exporter, 'dw' → dynamic-weight research chart. */
4
27
  type ChartCmd = 'tv' | 'dw';
@@ -13,27 +36,13 @@ interface ChartRenderer {
13
36
  /** Lines printed directly under the `Usage:` line. */
14
37
  usageBlurb: string[];
15
38
  }
16
- declare function resolveMpaBacking(mpaSymbol: string, bitsharesClient: any): Promise<{
17
- mpa: any;
18
- backing: any;
19
- isPredictionMarket: boolean;
20
- feedPublicationTime: string | null;
21
- } | null>;
22
- declare function pickFeedContext(symA: string, symB: string, source: string, bitsharesClient: any): Promise<{
23
- kind: string;
24
- legs: any[];
25
- } | null>;
39
+ declare function resolveMpaBacking(mpaSymbol: string, bitsharesClient: ChainClientLike): Promise<MpaBackingCtx | null>;
40
+ declare function pickFeedContext(symA: string, symB: string, source: string, bitsharesClient: ChainClientLike): Promise<FeedCtx | null>;
26
41
  declare function feedAgeMs(ctx: {
27
42
  feedPublicationTime: string | null;
28
43
  }, nowMs?: number): number | null;
29
- declare function feedName(feedCtx: {
30
- kind: string;
31
- legs: any[];
32
- }): string;
33
- declare function activateFeedIfCovered(symA: string, symB: string, assetA: any, assetB: any, source: string, bitsharesClient: any, label?: string): Promise<{
34
- kind: string;
35
- legs: any[];
36
- } | null>;
44
+ declare function feedName(feedCtx: FeedCtx): string;
45
+ declare function activateFeedIfCovered(symA: string, symB: string, assetA: AssetMeta, assetB: AssetMeta, source: string, bitsharesClient: ChainClientLike, label?: string): Promise<FeedCtx | null>;
37
46
  declare function parseArgs(argv: string[], cmd?: ChartCmd): {
38
47
  target: string | null;
39
48
  months: number;
@@ -104,12 +104,12 @@ async function resolveMpaBacking(mpaSymbol, bitsharesClient) {
104
104
  return null;
105
105
  try {
106
106
  const objs = await db.get_objects([mpa.bitasset_data_id]);
107
- const bitasset = Array.isArray(objs) ? objs[0] : objs;
107
+ const bitasset = (Array.isArray(objs) ? objs[0] : objs);
108
108
  const backingId = String(bitasset?.options?.short_backing_asset || '');
109
109
  if (!backingId)
110
110
  return null;
111
111
  const metas = typeof db.get_assets === 'function' ? await db.get_assets([backingId]) : null;
112
- const list = Array.isArray(metas) ? metas.flat(Infinity) : [];
112
+ const list = (Array.isArray(metas) ? metas.flat(Infinity) : []);
113
113
  const backing = list.find((a) => String(a?.id) === backingId) || null;
114
114
  if (!backing?.id || !Number.isFinite(Number(backing.precision)))
115
115
  return null;
@@ -160,7 +160,7 @@ function feedAgeMs(ctx, nowMs = Date.now()) {
160
160
  function feedName(feedCtx) {
161
161
  if (feedCtx.kind === 'cross')
162
162
  return `${feedCtx.legs[0].mpa.symbol}/${feedCtx.legs[1].mpa.symbol}`;
163
- return feedCtx.legs[0].mpa.symbol;
163
+ return String(feedCtx.legs[0].mpa.symbol ?? '');
164
164
  }
165
165
  async function activateFeedIfCovered(symA, symB, assetA, assetB, source, bitsharesClient, label = 'tv') {
166
166
  const ctx = await pickFeedContext(symA, symB, source, bitsharesClient);
@@ -252,12 +252,12 @@ function findBotByTarget(target) {
252
252
  if (!entry)
253
253
  continue;
254
254
  if (isSameBotName(entry.name, target))
255
- return { botKey: computeBotKey(entry, i), meta: entry };
255
+ return { botKey: computeBotKey(entry, i) ?? '', meta: entry };
256
256
  }
257
257
  const meta = loadBotMeta(target);
258
258
  if (meta) {
259
259
  const idx = entries.indexOf(meta);
260
- return { botKey: computeBotKey(meta, idx >= 0 ? idx : 0), meta };
260
+ return { botKey: computeBotKey(meta, idx >= 0 ? idx : 0) ?? '', meta };
261
261
  }
262
262
  return null;
263
263
  }
@@ -271,13 +271,13 @@ async function resolvePoolAssets(poolId, bitsharesClient) {
271
271
  if (db && typeof db.get_objects === 'function') {
272
272
  try {
273
273
  const objs = await db.get_objects([fullId]);
274
- const pool = Array.isArray(objs) ? objs[0] : null;
274
+ const pool = (Array.isArray(objs) ? objs[0] : null);
275
275
  const idA = pool?.asset_a || pool?.asset_ids?.[0];
276
276
  const idB = pool?.asset_b || pool?.asset_ids?.[1];
277
277
  if (idA && idB) {
278
278
  const assets = typeof db.get_assets === 'function' ? await db.get_assets([String(idA), String(idB)]) : null;
279
279
  // Tolerate both [..] and [[..]] result shapes.
280
- const list = Array.isArray(assets) ? assets.flat(Infinity) : [];
280
+ const list = (Array.isArray(assets) ? assets.flat(Infinity) : []);
281
281
  const metaA = list.find((a) => String(a?.id) === String(idA));
282
282
  const metaB = list.find((a) => String(a?.id) === String(idB));
283
283
  if (metaA && metaB) {
@@ -299,6 +299,8 @@ async function resolvePoolAssets(poolId, bitsharesClient) {
299
299
  throw new Error(`Pool ${fullId}: expected exactly 2 assets, discovered [${(ids || []).join(', ')}]. Pass AssetA/AssetB instead.`);
300
300
  }
301
301
  const [idA, idB] = ids.map(String);
302
+ if (!db || typeof db.get_assets !== 'function')
303
+ throw new Error(`Pool ${fullId}: chain asset lookup unavailable`);
302
304
  const assets = await db.get_assets([idA, idB]);
303
305
  const metaA = (assets || []).find((a) => String(a?.id) === idA);
304
306
  const metaB = (assets || []).find((a) => String(a?.id) === idB);
@@ -347,8 +349,8 @@ async function run(cmd) {
347
349
  await waitForConnected();
348
350
  let tmpFile = null;
349
351
  try {
350
- let assetA;
351
- let assetB;
352
+ let assetA = {};
353
+ let assetB = {};
352
354
  let poolId = null;
353
355
  let feedCtx = null;
354
356
  let sourceLabel = '';
@@ -373,7 +375,7 @@ async function run(cmd) {
373
375
  }
374
376
  else {
375
377
  try {
376
- poolId = (await findPoolByAssets(assetA.id, assetB.id, { bitsharesClient, sortBy: 'assetABalance' })).id;
378
+ poolId = (await findPoolByAssets(String(assetA.id), String(assetB.id), { bitsharesClient, sortBy: 'assetABalance' })).id ?? null;
377
379
  }
378
380
  catch (_) {
379
381
  poolId = null;
@@ -401,7 +403,7 @@ async function run(cmd) {
401
403
  }
402
404
  else {
403
405
  try {
404
- poolId = (await findPoolByAssets(assetA.id, assetB.id, { bitsharesClient, sortBy: 'assetABalance' })).id;
406
+ poolId = (await findPoolByAssets(String(assetA.id), String(assetB.id), { bitsharesClient, sortBy: 'assetABalance' })).id ?? null;
405
407
  }
406
408
  catch (_) {
407
409
  poolId = null;