dexbot 1.6.10 → 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.
- package/CHANGELOG.md +50 -3
- package/README.md +3 -1
- package/analysis/README.md +51 -11
- package/analysis/bot_fitting/README.md +12 -0
- package/analysis/tradingview/README.md +3 -3
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +11 -37
- package/analysis/trend_detection/README.md +31 -0
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
- package/claw/modules/chain_broadcast.ts +7 -1
- package/claw/modules/claw_launcher.ts +1 -1
- package/claw/modules/launcher_mode_detector.ts +9 -2
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/account_resolver.d.ts +1 -1
- package/dist/analysis/account_resolver.js +15 -2
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
- package/dist/analysis/analyze_args.d.ts +31 -0
- package/dist/analysis/analyze_args.js +41 -0
- package/dist/analysis/analyze_dynamic_weight.js +7 -20
- package/dist/analysis/analyze_kalman.js +7 -17
- package/dist/analysis/analyze_regime.js +7 -17
- package/dist/analysis/analyze_regime_windows.js +8 -18
- package/dist/analysis/analyze_risk_profile.js +8 -18
- package/dist/analysis/analyze_trade_heatmap.js +7 -17
- package/dist/analysis/analyze_volatility.js +7 -17
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +55 -10
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +72 -66
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
- package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
- package/dist/analysis/bot_fitting/shared_utils.js +2 -2
- package/dist/analysis/bot_key_utils.d.ts +18 -10
- package/dist/analysis/bot_key_utils.js +10 -17
- package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
- package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
- package/dist/analysis/chain_pool.d.ts +3 -1
- package/dist/analysis/chart_ui.d.ts +5 -2
- package/dist/analysis/chart_ui.js +6 -3
- package/dist/analysis/chart_utils.d.ts +5 -5
- package/dist/analysis/chart_utils.js +9 -0
- package/dist/analysis/fills_cache.d.ts +64 -0
- package/dist/analysis/fills_cache.js +254 -0
- package/dist/analysis/fills_source.d.ts +2 -2
- package/dist/analysis/fills_source.js +19 -14
- package/dist/analysis/grid_correction_check.d.ts +1 -1
- package/dist/analysis/grid_correction_check.js +12 -11
- package/dist/analysis/math_utils.d.ts +7 -6
- package/dist/analysis/math_utils.js +5 -8
- package/dist/analysis/pnl_report.d.ts +39 -0
- package/dist/analysis/pnl_report.js +325 -0
- package/dist/analysis/price_sources.d.ts +8 -8
- package/dist/analysis/price_sources.js +5 -4
- package/dist/analysis/resolve_bot_accounts.js +2 -2
- package/dist/analysis/resolve_source.d.ts +1 -2
- package/dist/analysis/trade_profitability.d.ts +32 -2
- package/dist/analysis/trade_profitability.js +232 -106
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
- package/dist/analysis/tradingview/analyze_tradingview.js +9 -10
- package/dist/analysis/tradingview/grid_reset_config.d.ts +42 -31
- package/dist/analysis/tradingview/grid_reset_config.js +35 -6
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -8
- package/dist/analysis/tradingview/grid_reset_sim.js +42 -5
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -20
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +27 -112
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +40 -0
- package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
- package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
- package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
- package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
- package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
- package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
- package/dist/credential-daemon.js +34 -20
- package/dist/dexbot.js +17 -14
- package/dist/market_adapter/candle_utils.d.ts +22 -18
- package/dist/market_adapter/candle_utils.js +24 -20
- package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
- package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
- package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
- package/dist/market_adapter/core/kibana_candles.js +9 -7
- package/dist/market_adapter/core/kibana_client.d.ts +9 -1
- package/dist/market_adapter/core/kibana_client.js +8 -7
- package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
- package/dist/market_adapter/core/market_adapter_service.d.ts +297 -115
- package/dist/market_adapter/core/market_adapter_service.js +184 -101
- package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
- package/dist/market_adapter/core/strategies/ama.js +7 -32
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
- package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
- package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
- package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
- package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
- package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +36 -8
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +9 -9
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
- package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
- package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
- package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
- package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
- package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
- package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
- package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
- package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
- package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +97 -226
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
- package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
- package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
- package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
- package/dist/market_adapter/inputs/kibana_source.js +2 -2
- package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
- package/dist/market_adapter/inputs/window_cache.js +8 -8
- package/dist/market_adapter/interval_utils.d.ts +4 -4
- package/dist/market_adapter/log_format.d.ts +6 -6
- package/dist/market_adapter/log_format.js +28 -22
- package/dist/market_adapter/lp_chart_core.d.ts +22 -1
- package/dist/market_adapter/lp_chart_core.js +26 -192
- package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
- package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
- package/dist/market_adapter/market_adapter.d.ts +94 -33
- package/dist/market_adapter/market_adapter.js +69 -75
- package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
- package/dist/market_adapter/utils/adapter_client.js +2 -2
- package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
- package/dist/market_adapter/utils/chain.d.ts +50 -41
- package/dist/market_adapter/utils/chain.js +40 -46
- package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
- package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
- package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
- package/dist/market_adapter/utils/file_lock.d.ts +28 -14
- package/dist/market_adapter/utils/file_lock.js +36 -32
- package/dist/market_adapter/utils/native_history.d.ts +9 -2
- package/dist/market_adapter/utils/native_history.js +35 -28
- package/dist/modules/account_bots.d.ts +577 -21
- package/dist/modules/account_bots.js +182 -158
- package/dist/modules/account_orders.d.ts +66 -30
- package/dist/modules/account_orders.js +22 -20
- package/dist/modules/authority_resolver.d.ts +12 -2
- package/dist/modules/authority_resolver.js +15 -8
- package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
- package/dist/modules/bitshares-native/chain_client.js +45 -46
- package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
- package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
- package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
- package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
- package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
- package/dist/modules/bitshares-native/index.d.ts +1 -1
- package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
- package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
- package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
- package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
- package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
- package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
- package/dist/modules/bitshares-native/serial/serializer.js +7 -13
- package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
- package/dist/modules/bitshares-native/serial/types.js +55 -62
- package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
- package/dist/modules/bitshares-native/signing_client.js +19 -14
- package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
- package/dist/modules/bitshares-native/subscriptions.js +12 -12
- package/dist/modules/bitshares-native/transport.d.ts +5 -4
- package/dist/modules/bitshares-native/transport.js +5 -4
- package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
- package/dist/modules/bitshares-native/tx/builder.js +4 -3
- package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
- package/dist/modules/bitshares_client.d.ts +45 -13
- package/dist/modules/bitshares_client.js +28 -19
- package/dist/modules/bot_defaults.d.ts +6 -15
- package/dist/modules/bot_defaults.js +1 -5
- package/dist/modules/bot_settings.d.ts +44 -10
- package/dist/modules/bot_settings.js +11 -8
- package/dist/modules/bots_file_lock.d.ts +6 -6
- package/dist/modules/bots_file_lock.js +16 -12
- package/dist/modules/broadcast_failure.d.ts +2 -2
- package/dist/modules/broadcast_failure.js +5 -4
- package/dist/modules/chain_keys.d.ts +42 -40
- package/dist/modules/chain_keys.js +53 -45
- package/dist/modules/chain_orders.d.ts +93 -59
- package/dist/modules/chain_orders.js +31 -23
- package/dist/modules/constants.d.ts +530 -32
- package/dist/modules/constants.js +52 -60
- package/dist/modules/cr_planner.d.ts +40 -2
- package/dist/modules/credential_policy.d.ts +68 -8
- package/dist/modules/credential_policy.js +37 -31
- package/dist/modules/credential_session_cache.d.ts +2 -2
- package/dist/modules/credit_pricing.d.ts +42 -6
- package/dist/modules/credit_pricing.js +44 -30
- package/dist/modules/credit_runtime.d.ts +276 -118
- package/dist/modules/credit_runtime.js +462 -165
- package/dist/modules/crypto/browser_provider.js +6 -4
- package/dist/modules/crypto/node_provider.js +1 -1
- package/dist/modules/crypto/pure_scrypt.js +35 -4
- package/dist/modules/crypto/pure_secp256k1.js +72 -26
- package/dist/modules/crypto/sync.d.ts +9 -9
- package/dist/modules/crypto/sync.js +16 -9
- package/dist/modules/dexbot_class.d.ts +195 -139
- package/dist/modules/dexbot_class.js +78 -28
- package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
- package/dist/modules/dexbot_cow_runtime.js +248 -206
- package/dist/modules/dexbot_credential_client.d.ts +19 -11
- package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
- package/dist/modules/dexbot_fill_runtime.js +48 -41
- package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
- package/dist/modules/dexbot_maintenance_runtime.js +117 -80
- package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
- package/dist/modules/dexbot_startup_runtime.js +43 -43
- package/dist/modules/dexbot_state_recovery.d.ts +13 -12
- package/dist/modules/dexbot_state_recovery.js +18 -13
- package/dist/modules/fund_registry.d.ts +4 -2
- package/dist/modules/fund_registry.js +10 -10
- package/dist/modules/general_settings.d.ts +30 -4
- package/dist/modules/graceful_shutdown.d.ts +3 -3
- package/dist/modules/graceful_shutdown.js +2 -2
- package/dist/modules/grid_price_source.d.ts +1 -1
- package/dist/modules/key_store.d.ts +14 -8
- package/dist/modules/key_store.js +7 -6
- package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
- package/dist/modules/launcher/adapter_requirement.js +5 -5
- package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
- package/dist/modules/launcher/bot_supervisor.js +12 -11
- package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
- package/dist/modules/launcher/credential_bootstrap.js +1 -1
- package/dist/modules/launcher/credential_daemon.d.ts +4 -4
- package/dist/modules/launcher/credential_daemon.js +2 -2
- package/dist/modules/launcher/credential_secret.d.ts +1 -1
- package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
- package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
- package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
- package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
- package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
- package/dist/modules/launcher/status_reporting.d.ts +22 -14
- package/dist/modules/launcher/supervisor_control.d.ts +8 -1
- package/dist/modules/launcher/supervisor_control.js +4 -2
- package/dist/modules/market_adapter_whitelist.d.ts +9 -3
- package/dist/modules/market_adapter_whitelist.js +15 -3
- package/dist/modules/node_manager.d.ts +41 -11
- package/dist/modules/node_manager.js +5 -4
- package/dist/modules/order/accounting.d.ts +53 -24
- package/dist/modules/order/accounting.js +40 -14
- package/dist/modules/order/async_lock.d.ts +5 -2
- package/dist/modules/order/async_lock.js +1 -1
- package/dist/modules/order/export.d.ts +7 -6
- package/dist/modules/order/export.js +1 -7
- package/dist/modules/order/format.d.ts +39 -19
- package/dist/modules/order/format.js +62 -16
- package/dist/modules/order/genesis_policy.d.ts +21 -18
- package/dist/modules/order/genesis_policy.js +12 -8
- package/dist/modules/order/grid.d.ts +142 -36
- package/dist/modules/order/grid.js +148 -123
- package/dist/modules/order/grid_reconcile.d.ts +21 -20
- package/dist/modules/order/grid_reconcile.js +13 -12
- package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
- package/dist/modules/order/grid_reconcile_internal.js +28 -19
- package/dist/modules/order/index.d.ts +263 -1
- package/dist/modules/order/logger.d.ts +45 -11
- package/dist/modules/order/logger.js +38 -40
- package/dist/modules/order/logger_state.d.ts +4 -4
- package/dist/modules/order/manager.d.ts +226 -180
- package/dist/modules/order/manager.js +101 -83
- package/dist/modules/order/processed_fill_store.d.ts +18 -3
- package/dist/modules/order/processed_fill_store.js +16 -27
- package/dist/modules/order/strategy.d.ts +21 -13
- package/dist/modules/order/strategy.js +5 -6
- package/dist/modules/order/sync_engine.d.ts +91 -33
- package/dist/modules/order/sync_engine.js +99 -54
- package/dist/modules/order/utils/math.d.ts +157 -102
- package/dist/modules/order/utils/math.js +77 -38
- package/dist/modules/order/utils/order.d.ts +326 -106
- package/dist/modules/order/utils/order.js +200 -99
- package/dist/modules/order/utils/slot.d.ts +1 -1
- package/dist/modules/order/utils/system.d.ts +176 -26
- package/dist/modules/order/utils/system.js +86 -69
- package/dist/modules/order/utils/validate.d.ts +89 -41
- package/dist/modules/order/utils/validate.js +24 -22
- package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
- package/dist/modules/order/utils/withPoolRef.js +18 -12
- package/dist/modules/order/working_grid.d.ts +14 -13
- package/dist/modules/paths.d.ts +3 -4
- package/dist/modules/paths.js +3 -27
- package/dist/modules/process_discovery.d.ts +1 -1
- package/dist/modules/process_discovery.js +2 -1
- package/dist/modules/runtime.d.ts +7 -3
- package/dist/modules/runtime.js +4 -3
- package/dist/modules/runtime_settings.d.ts +15 -10
- package/dist/modules/runtime_settings.js +30 -24
- package/dist/modules/settings_merge.d.ts +29 -3
- package/dist/modules/settings_merge.js +56 -78
- package/dist/modules/socket_json_client.d.ts +7 -4
- package/dist/modules/storage/browser_adapter.d.ts +38 -53
- package/dist/modules/storage/browser_adapter.js +7 -30
- package/dist/modules/storage/index.d.ts +1 -1
- package/dist/modules/storage/node_adapter.d.ts +45 -27
- package/dist/modules/storage/node_adapter.js +9 -9
- package/dist/modules/storage/types.d.ts +5 -4
- package/dist/modules/types.d.ts +1071 -2
- package/dist/modules/types.js +4 -1
- package/dist/modules/utils/asset_symbols.d.ts +2 -1
- package/dist/modules/utils/asset_symbols.js +2 -1
- package/dist/modules/utils/errors.d.ts +9 -0
- package/dist/modules/utils/errors.js +23 -1
- package/dist/modules/utils/time_range.d.ts +4 -0
- package/dist/modules/utils/time_range.js +18 -0
- package/dist/modules/validate_profiles.js +53 -43
- package/dist/modules/version_notice.d.ts +14 -3
- package/dist/modules/version_notice.js +6 -4
- package/dist/pm2.d.ts +29 -27
- package/dist/pm2.js +5 -5
- package/dist/scripts/analyze-credit.d.ts +2 -1
- package/dist/scripts/analyze-credit.js +23 -24
- package/dist/scripts/analyze-orders.d.ts +77 -9
- package/dist/scripts/analyze-orders.js +66 -84
- package/dist/scripts/chart_command.d.ts +27 -18
- package/dist/scripts/chart_command.js +16 -15
- package/dist/scripts/check_any.d.ts +18 -0
- package/dist/scripts/check_any.js +126 -0
- package/dist/scripts/diagnose-pool-history.js +12 -7
- package/dist/scripts/pnl.d.ts +3 -0
- package/dist/scripts/pnl.js +40 -0
- package/dist/scripts/print_grid.js +0 -1
- package/dist/scripts/run-tests.js +39 -7
- package/dist/scripts/runner.js +1 -1
- package/dist/scripts/test-credit-renewal.js +30 -21
- package/dist/scripts/update.d.ts +10 -5
- package/dist/scripts/update.js +168 -103
- package/dist/scripts/update_dist_freshness.js +1 -0
- package/dist/scripts/update_layout.d.ts +61 -0
- package/dist/scripts/update_layout.js +180 -0
- package/dist/scripts/validate_bots.js +2 -1
- package/dist/scripts/verify-browser-bundle.js +8 -0
- package/dist/unlock.d.ts +28 -3
- package/dist/unlock.js +72 -10
- package/docs/BITSHARES_ONBOARDING.md +2 -0
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +13 -6
- package/docs/DEXBOT_COMPARISON.md +8 -8
- package/docs/EVOLUTION.md +12 -10
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
- package/docs/GRID_RECALCULATION.md +15 -16
- package/docs/GRID_RECONCILE.md +14 -3
- package/docs/LIFECYCLE.md +11 -11
- package/docs/MPA_CREDIT_USAGE.md +22 -3
- package/docs/README.md +15 -4
- package/docs/WORKFLOW.md +1 -0
- package/docs/architecture.md +12 -9
- package/docs/developer_guide.md +6 -6
- package/market_adapter/README.md +9 -26
- package/modules/README.md +4 -1
- package/package.json +4 -1
- package/scripts/README.md +14 -0
|
@@ -122,7 +122,7 @@ const GRID_RESYNC_REASONS = Object.freeze({
|
|
|
122
122
|
/**
|
|
123
123
|
* Find a bot entry in the bots config snapshot that matches a runtime config.
|
|
124
124
|
* Matches by botKey or name.
|
|
125
|
-
* @param {
|
|
125
|
+
* @param {unknown} snapshot - Bots configuration snapshot
|
|
126
126
|
* @param {Object} config - Runtime bot configuration
|
|
127
127
|
* @returns {Object|null} Matched bot entry or null
|
|
128
128
|
*/
|
|
@@ -144,7 +144,7 @@ function findSnapshotBotForRuntimeConfig(snapshot, config) {
|
|
|
144
144
|
}
|
|
145
145
|
/**
|
|
146
146
|
* Check if a runtime bot configuration requires the market adapter.
|
|
147
|
-
* @param {
|
|
147
|
+
* @param {unknown} snapshot - Bots configuration snapshot
|
|
148
148
|
* @param {Object} config - Runtime bot configuration
|
|
149
149
|
* @returns {boolean} True if the bot uses AMA grid pricing
|
|
150
150
|
*/
|
|
@@ -174,7 +174,7 @@ const BOT_CONFIG_FINGERPRINT_IGNORED_KEYS = Object.freeze([
|
|
|
174
174
|
/**
|
|
175
175
|
* Deterministic JSON stringify with recursively sorted object keys.
|
|
176
176
|
* Key order in bots.json must not count as a config change.
|
|
177
|
-
* @param {
|
|
177
|
+
* @param {unknown} value - Value to stringify
|
|
178
178
|
* @returns {string} Stable string representation
|
|
179
179
|
*/
|
|
180
180
|
function stableStringifyForBotConfig(value) {
|
|
@@ -184,32 +184,34 @@ function stableStringifyForBotConfig(value) {
|
|
|
184
184
|
return `[${value.map((v) => stableStringifyForBotConfig(v)).join(',')}]`;
|
|
185
185
|
}
|
|
186
186
|
if (typeof value === 'object') {
|
|
187
|
-
const
|
|
188
|
-
|
|
187
|
+
const obj = value;
|
|
188
|
+
const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort();
|
|
189
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringifyForBotConfig(obj[k])}`).join(',')}}`;
|
|
189
190
|
}
|
|
190
191
|
const serialized = JSON.stringify(value);
|
|
191
192
|
return serialized === undefined ? 'null' : serialized;
|
|
192
193
|
}
|
|
193
194
|
/**
|
|
194
195
|
* Normalize a raw bots.json entry for fingerprinting: drop volatile keys.
|
|
195
|
-
* @param {
|
|
196
|
-
* @returns {
|
|
196
|
+
* @param {unknown} entry - Raw bot entry from bots.json
|
|
197
|
+
* @returns {unknown} Normalized plain object ({} when entry is missing)
|
|
197
198
|
*/
|
|
198
199
|
function normalizeBotEntryForFingerprint(entry) {
|
|
199
200
|
if (!entry || typeof entry !== 'object' || Array.isArray(entry))
|
|
200
201
|
return {};
|
|
201
202
|
const out = {};
|
|
202
|
-
|
|
203
|
+
const e = entry;
|
|
204
|
+
for (const key of Object.keys(e)) {
|
|
203
205
|
if (BOT_CONFIG_FINGERPRINT_IGNORED_KEYS.includes(key))
|
|
204
206
|
continue;
|
|
205
|
-
out[key] =
|
|
207
|
+
out[key] = e[key];
|
|
206
208
|
}
|
|
207
209
|
return out;
|
|
208
210
|
}
|
|
209
211
|
/**
|
|
210
212
|
* Build the full-entry fingerprint for one bot (stable across key order and
|
|
211
213
|
* comment/whitespace edits, since those never reach the parsed entry).
|
|
212
|
-
* @param {
|
|
214
|
+
* @param {unknown} entry - Raw bot entry from bots.json
|
|
213
215
|
* @returns {string} Fingerprint ('' when entry is missing)
|
|
214
216
|
*/
|
|
215
217
|
function buildBotConfigFingerprint(entry) {
|
|
@@ -221,8 +223,8 @@ function buildBotConfigFingerprint(entry) {
|
|
|
221
223
|
* Plain-data deep clone (bots.json entries are JSON-parsed, always
|
|
222
224
|
* serializable; the fallback only guards exotic test doubles).
|
|
223
225
|
* Single helper replacing the previously triplicated inline clones.
|
|
224
|
-
* @param {
|
|
225
|
-
* @returns {
|
|
226
|
+
* @param {unknown} value - Value to clone
|
|
227
|
+
* @returns {unknown} Deep clone (or the original when unserializable)
|
|
226
228
|
*/
|
|
227
229
|
function cloneJsonValue(value) {
|
|
228
230
|
if (value === undefined)
|
|
@@ -241,8 +243,8 @@ function cloneJsonValue(value) {
|
|
|
241
243
|
* grid-resync path uses replaceBotConfigFromEntryPreservingRuntime below.
|
|
242
244
|
* Synchronous in-memory merge only: no chain I/O, no fill-lock (assignments
|
|
243
245
|
* are atomic; maintenance / targeted-reconcile ticks heal shortfalls/excess).
|
|
244
|
-
* @param {
|
|
245
|
-
* @param {
|
|
246
|
+
* @param {unknown} bot - DEXBot instance
|
|
247
|
+
* @param {unknown} entry - Raw bot entry from bots.json
|
|
246
248
|
* @param {string[]} keys - Entry keys to merge
|
|
247
249
|
* @returns {string[]} Merged key names
|
|
248
250
|
*/
|
|
@@ -250,19 +252,20 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
|
|
|
250
252
|
const applied = [];
|
|
251
253
|
if (!bot?.config || !entry || typeof entry !== 'object')
|
|
252
254
|
return applied;
|
|
255
|
+
const e = entry;
|
|
253
256
|
for (const key of keys) {
|
|
254
257
|
// A deleted key applies as null (mirrors the former ?? null diff
|
|
255
258
|
// semantics) so the running config can never keep a stale value.
|
|
256
259
|
// Cloned twice: bot.config and manager.config must never alias the
|
|
257
260
|
// same nested object, or a future in-place mutation of one would
|
|
258
261
|
// silently corrupt the other.
|
|
259
|
-
const cloned = cloneJsonValue(
|
|
262
|
+
const cloned = cloneJsonValue(e[key] ?? null);
|
|
260
263
|
bot.config[key] = cloned;
|
|
261
264
|
if (bot.manager?.config) {
|
|
262
|
-
bot.manager.config[key] = cloneJsonValue(
|
|
265
|
+
bot.manager.config[key] = cloneJsonValue(e[key] ?? null);
|
|
263
266
|
}
|
|
264
267
|
if (key === 'weightDistribution') {
|
|
265
|
-
bot._baseWeightDistribution = cloned && typeof cloned === 'object' ? { ...cloned } : cloned;
|
|
268
|
+
bot._baseWeightDistribution = (cloned && typeof cloned === 'object' ? { ...cloned } : cloned);
|
|
266
269
|
}
|
|
267
270
|
applied.push(key);
|
|
268
271
|
}
|
|
@@ -273,13 +276,14 @@ function mergeBotConfigKeysIntoRuntime(bot, entry, keys) {
|
|
|
273
276
|
* constructor-resolved runtime settings (timing, gridLimits, feeParams,
|
|
274
277
|
* etc.). Shared single implementation for performGridResync (previously an
|
|
275
278
|
* inline block duplicating the merge/weights/refresh steps).
|
|
276
|
-
* @param {
|
|
277
|
-
* @param {
|
|
279
|
+
* @param {unknown} bot - DEXBot instance
|
|
280
|
+
* @param {unknown} updatedBot - Raw bot entry from bots.json
|
|
278
281
|
* @param {string} contextLabel - Label for the weights-refresh log context
|
|
279
282
|
*/
|
|
280
283
|
function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabel) {
|
|
281
284
|
const oldKey = bot.config.botKey;
|
|
282
285
|
const oldIndex = bot.config.botIndex;
|
|
286
|
+
const u = updatedBot;
|
|
283
287
|
// Preserve runtime-only properties set by the constructor
|
|
284
288
|
// (timing, gridLimits, feeParams, etc.) that are not present
|
|
285
289
|
// in the raw profile from bots.json.
|
|
@@ -290,7 +294,7 @@ function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabe
|
|
|
290
294
|
}
|
|
291
295
|
}
|
|
292
296
|
bot._log(`Reloaded configuration for bot '${bot.config.name}'`);
|
|
293
|
-
bot.config = { ...
|
|
297
|
+
bot.config = { ...u, botKey: oldKey, botIndex: oldIndex, ...runtimeProps };
|
|
294
298
|
if (bot.manager?.config) {
|
|
295
299
|
bot.manager.config = { ...bot.manager.config, ...bot.config };
|
|
296
300
|
}
|
|
@@ -300,7 +304,7 @@ function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabe
|
|
|
300
304
|
if (bot._creditRuntime) {
|
|
301
305
|
bot._creditRuntime.config = bot.config;
|
|
302
306
|
}
|
|
303
|
-
bot._baseWeightDistribution = cloneWeightDistribution(
|
|
307
|
+
bot._baseWeightDistribution = cloneWeightDistribution(u.weightDistribution, bot._baseWeightDistribution);
|
|
304
308
|
refreshDynamicWeightDistribution(bot, contextLabel);
|
|
305
309
|
}
|
|
306
310
|
/**
|
|
@@ -309,7 +313,7 @@ function replaceBotConfigFromEntryPreservingRuntime(bot, updatedBot, contextLabe
|
|
|
309
313
|
* bot_settings.ts). Full numeric validation stays where it belongs:
|
|
310
314
|
* the `dexbot bot` editor at save time and per-offer at runtime.
|
|
311
315
|
* null/undefined (policy removal) is safe — it takes the disable path.
|
|
312
|
-
* @param {
|
|
316
|
+
* @param {unknown} value - New debtPolicy value from bots.json
|
|
313
317
|
* @returns {boolean} True when safe to merge live
|
|
314
318
|
*/
|
|
315
319
|
function isDebtPolicyLiveApplySafe(value) {
|
|
@@ -320,10 +324,14 @@ function isDebtPolicyLiveApplySafe(value) {
|
|
|
320
324
|
const lending = value.lending;
|
|
321
325
|
if (!Array.isArray(lending) || lending.length === 0)
|
|
322
326
|
return false;
|
|
323
|
-
return lending.every((item) =>
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
+
return lending.every((item) => {
|
|
328
|
+
if (!item || typeof item !== 'object')
|
|
329
|
+
return false;
|
|
330
|
+
const it = item;
|
|
331
|
+
return typeof it.type === 'string' && it.type.length > 0
|
|
332
|
+
&& typeof it.asset === 'string' && it.asset.length > 0
|
|
333
|
+
&& typeof it.collateralAsset === 'string' && it.collateralAsset.length > 0;
|
|
334
|
+
});
|
|
327
335
|
}
|
|
328
336
|
/**
|
|
329
337
|
* Reconcile the credit runtime after a live debtPolicy merge: (re)create +
|
|
@@ -332,7 +340,7 @@ function isDebtPolicyLiveApplySafe(value) {
|
|
|
332
340
|
* an already-loaded runtime and both maintenance entry points bail while
|
|
333
341
|
* disabled or in-flight, so this is safe on any tick (bot-level seams
|
|
334
342
|
* guarded for stripped test doubles).
|
|
335
|
-
* @param {
|
|
343
|
+
* @param {unknown} bot - DEXBot instance
|
|
336
344
|
*/
|
|
337
345
|
async function reconcileCreditRuntimeAfterPolicyChange(bot) {
|
|
338
346
|
try {
|
|
@@ -362,13 +370,13 @@ async function reconcileCreditRuntimeAfterPolicyChange(bot) {
|
|
|
362
370
|
* Diff two normalized entries in a single pass over the key union.
|
|
363
371
|
* Replaces the former twin-loop diffLiveBotConfig +
|
|
364
372
|
* detectNonLiveBotConfigChanges pair.
|
|
365
|
-
* @param {
|
|
366
|
-
* @param {
|
|
373
|
+
* @param {unknown} oldNormalized - Previously seen normalized entry
|
|
374
|
+
* @param {unknown} newNormalized - New normalized entry
|
|
367
375
|
* @returns {{liveChanges: Array<{key: string, oldValue: any, newValue: any}>, otherKeys: string[]}} Split changes
|
|
368
376
|
*/
|
|
369
377
|
function diffBotConfigEntries(oldNormalized, newNormalized) {
|
|
370
|
-
const prev = oldNormalized && typeof oldNormalized === 'object' ? oldNormalized : {};
|
|
371
|
-
const next = newNormalized && typeof newNormalized === 'object' ? newNormalized : {};
|
|
378
|
+
const prev = (oldNormalized && typeof oldNormalized === 'object' ? oldNormalized : {});
|
|
379
|
+
const next = (newNormalized && typeof newNormalized === 'object' ? newNormalized : {});
|
|
372
380
|
const liveChanges = [];
|
|
373
381
|
const otherKeys = [];
|
|
374
382
|
for (const key of new Set([...Object.keys(prev), ...Object.keys(next)])) {
|
|
@@ -402,9 +410,9 @@ function diffBotConfigEntries(oldNormalized, newNormalized) {
|
|
|
402
410
|
* the baseline with no hint. Corrupt/unreadable files and missing entries
|
|
403
411
|
* never touch the stored fingerprint (except the missing-entry hint
|
|
404
412
|
* throttle) so the next tick re-evaluates.
|
|
405
|
-
* @param {
|
|
413
|
+
* @param {unknown} bot - DEXBot instance
|
|
406
414
|
* @param {string} [context='bots-config poll'] - Context label for logging
|
|
407
|
-
* @param {
|
|
415
|
+
* @param {unknown} [preloadedSnapshot=null] - Reuse an already-loaded snapshot
|
|
408
416
|
* @returns {Promise<any>} Result with applied/liveChanges/otherKeys or skipped
|
|
409
417
|
*/
|
|
410
418
|
async function checkAndApplyBotConfigChanges(bot, context = 'bots-config poll', preloadedSnapshot = null) {
|
|
@@ -497,6 +505,19 @@ async function checkAndApplyBotConfigChanges(bot, context = 'bots-config poll',
|
|
|
497
505
|
.join('; ');
|
|
498
506
|
bot._log?.(`Applied bots.json changes for '${botName}' live during ${context} (no restart needed): ${summary}. ` +
|
|
499
507
|
`Targeted maintenance will place missing / cancel excess orders.`, 'info');
|
|
508
|
+
// Deliver the promise above instead of waiting for the next fill
|
|
509
|
+
// or the 240-min fetch: run the targeted drift reconciliation
|
|
510
|
+
// right away (same fire-and-forget shape as the poll tick). The
|
|
511
|
+
// callee owns the cooldown; the periodic call site additionally
|
|
512
|
+
// gates on an empty pipeline, which this config-pickup path does
|
|
513
|
+
// not — it retries on the next maintenance tick either way.
|
|
514
|
+
try {
|
|
515
|
+
const driftRun = maybeRunTargetedDriftReconciliation(bot, `${context} config pickup`);
|
|
516
|
+
driftRun?.catch?.((err) => {
|
|
517
|
+
bot._log?.(`[TARGETED-SYNC] Config-pickup reconciliation failed: ${getErrorMessage(err)}`, 'debug');
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
catch { /* never break the poll tick */ }
|
|
500
521
|
}
|
|
501
522
|
if (otherKeys.length > 0) {
|
|
502
523
|
const shown = otherKeys.slice(0, 8).join(', ');
|
|
@@ -559,9 +580,9 @@ function getTargetActiveOrders(config, side) {
|
|
|
559
580
|
* window = bottom slots = floor edge) makes the edge pick land on window
|
|
560
581
|
* members and the count reads N/N with zero dedicated reserves, so the
|
|
561
582
|
* deficit never fires (issue #27 follow-up).
|
|
562
|
-
* @param {
|
|
563
|
-
* @param {
|
|
564
|
-
* @param {
|
|
583
|
+
* @param {unknown} manager - OrderManager
|
|
584
|
+
* @param {unknown} config - Bot configuration (reserve count source)
|
|
585
|
+
* @param {unknown} type - ORDER_TYPES.BUY or ORDER_TYPES.SELL
|
|
565
586
|
* @returns {number|null} Live reserve count, or null when unclassifiable
|
|
566
587
|
*/
|
|
567
588
|
function countLiveReserveOrders(manager, config, type) {
|
|
@@ -667,10 +688,12 @@ function getTargetedSyncReason(bot) {
|
|
|
667
688
|
if (drift && drift.isValid === false) {
|
|
668
689
|
return { reason: `fund drift: ${drift.reason}`, targetBuy, targetSell, liveBuy, liveSell, drift };
|
|
669
690
|
}
|
|
670
|
-
//
|
|
671
|
-
//
|
|
672
|
-
//
|
|
673
|
-
//
|
|
691
|
+
// Spread correction placed no effective orders: either it found no free
|
|
692
|
+
// funds on either side, or the prepared batch did not execute. The balances
|
|
693
|
+
// or holds may simply be a stale snapshot (the grid does not lose funds, it
|
|
694
|
+
// holds them in resting/virtual slots), so the only fallback is to refresh
|
|
695
|
+
// account totals + open orders and let the next correction cycle re-check.
|
|
696
|
+
// Never recycle resting inventory.
|
|
674
697
|
if (bot._spreadFundsExhausted === true) {
|
|
675
698
|
return { reason: 'spread correction had no free funds', targetBuy, targetSell, liveBuy, liveSell, drift };
|
|
676
699
|
}
|
|
@@ -704,6 +727,16 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
|
|
|
704
727
|
bot._warn(`[TARGETED-SYNC] Chain sync failed during ${context}, skipping reconciliation`);
|
|
705
728
|
return false;
|
|
706
729
|
}
|
|
730
|
+
// The point of a funds-exhausted trigger is the REFRESH itself: it
|
|
731
|
+
// exists to correct a stale balance/reservation read, not to force a
|
|
732
|
+
// reconcile. Clear the flag now so the re-check below (and the next
|
|
733
|
+
// tick's gate) treats "funds appeared after the refresh" as resolved and
|
|
734
|
+
// only reconciles on a still-concrete signal — fund drift or a counted
|
|
735
|
+
// order shortfall. The spread check later this tick re-derives the flag
|
|
736
|
+
// from fresh state, so a genuinely empty balance re-arms it for the next
|
|
737
|
+
// tick (subject to the cooldown below).
|
|
738
|
+
if (bot._spreadFundsExhausted === true)
|
|
739
|
+
bot._spreadFundsExhausted = false;
|
|
707
740
|
const remaining = getTargetedSyncReason(bot);
|
|
708
741
|
const unmatchedCount = Number(syncResult?.unmatchedChainOrders?.length || 0);
|
|
709
742
|
if (remaining || unmatchedCount > 0) {
|
|
@@ -738,7 +771,7 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
|
|
|
738
771
|
* Delegates to the canonical launcher/adapter_requirement helper so the
|
|
739
772
|
* fingerprint is semantic (AMA-relevant changes only) and identical to the
|
|
740
773
|
* unlock wrapper watchdog's view of the same file.
|
|
741
|
-
* @returns {
|
|
774
|
+
* @returns {unknown} Snapshot with exists flag, fingerprint, active bots list, and adapter requirement
|
|
742
775
|
*/
|
|
743
776
|
function loadBotsConfigSnapshot() {
|
|
744
777
|
return readAdapterRequirement(PROFILES_BOTS_FILE);
|
|
@@ -841,9 +874,9 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
|
|
|
841
874
|
// fingerprints, retry next tick.
|
|
842
875
|
let snapshot = null;
|
|
843
876
|
try {
|
|
844
|
-
snapshot = typeof bot._loadBotsConfigSnapshot === 'function'
|
|
877
|
+
snapshot = (typeof bot._loadBotsConfigSnapshot === 'function'
|
|
845
878
|
? await bot._loadBotsConfigSnapshot()
|
|
846
|
-
: loadBotsConfigSnapshot();
|
|
879
|
+
: loadBotsConfigSnapshot());
|
|
847
880
|
}
|
|
848
881
|
catch (err) {
|
|
849
882
|
bot._warn(`Ignoring unreadable bots.json during ${context}; keeping previous market adapter state.`);
|
|
@@ -885,8 +918,9 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
|
|
|
885
918
|
// ?? (not ||): the semantic fingerprint is legitimately '' when no
|
|
886
919
|
// active AMA bot exists, and '' must compare equal to a stored ''.
|
|
887
920
|
const previousFingerprint = bot._marketAdapterWatchdogFingerprint ?? null;
|
|
888
|
-
const
|
|
889
|
-
|
|
921
|
+
const fingerprint = snapshot.fingerprint;
|
|
922
|
+
const changed = fingerprint !== previousFingerprint;
|
|
923
|
+
bot._marketAdapterWatchdogFingerprint = fingerprint;
|
|
890
924
|
if (changed) {
|
|
891
925
|
bot._log(`Detected bots.json changes during ${context}; re-evaluating market adapter requirements.`);
|
|
892
926
|
}
|
|
@@ -941,9 +975,10 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
|
|
|
941
975
|
}
|
|
942
976
|
// Cross-reference config-active bots against actually running PM2 processes
|
|
943
977
|
// so we don't start the adapter for configured AMA bots that aren't running.
|
|
978
|
+
const activeBots = (snapshot.activeBots ?? []);
|
|
944
979
|
const runningActiveBots = pm2QueryFailed
|
|
945
|
-
?
|
|
946
|
-
:
|
|
980
|
+
? activeBots
|
|
981
|
+
: activeBots.filter((b) => processNames.includes(String(b.name)));
|
|
947
982
|
const needsAdapterForRunningBots = runningActiveBots.some(usesAmaGridPrice);
|
|
948
983
|
if (!snapshot.exists || !needsAdapterForRunningBots) {
|
|
949
984
|
const shouldStop = pm2QueryFailed || processNames.includes(MARKET_ADAPTER_APP_NAME);
|
|
@@ -1009,7 +1044,7 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
|
|
|
1009
1044
|
* Applies live dynamic weights if the bot is whitelisted and weights are ready.
|
|
1010
1045
|
* @param {import('./dexbot_class.js').DEXBot} bot
|
|
1011
1046
|
* @param {string} [context='runtime'] - Context label for logging
|
|
1012
|
-
* @returns {
|
|
1047
|
+
* @returns {unknown}
|
|
1013
1048
|
*/
|
|
1014
1049
|
function refreshDynamicWeightDistribution(bot, context = 'runtime') {
|
|
1015
1050
|
const baseWeights = cloneWeightDistribution(bot._baseWeightDistribution, bot.config?.weightDistribution || bot.manager?.config?.weightDistribution);
|
|
@@ -1065,7 +1100,7 @@ function refreshDynamicWeightDistribution(bot, context = 'runtime') {
|
|
|
1065
1100
|
* Read and parse a trigger file's metadata payload.
|
|
1066
1101
|
* Determines whether the trigger originated from the market adapter or was manual.
|
|
1067
1102
|
* @param {string} triggerFile - Path to the trigger file
|
|
1068
|
-
* @returns {
|
|
1103
|
+
* @returns {unknown} Parsed trigger metadata
|
|
1069
1104
|
*/
|
|
1070
1105
|
function readTriggerMetadata(triggerFile) {
|
|
1071
1106
|
const manualTriggerMetadata = (payload = null) => ({
|
|
@@ -1099,7 +1134,7 @@ function readTriggerMetadata(triggerFile) {
|
|
|
1099
1134
|
* Build grid resync metadata from a reason string.
|
|
1100
1135
|
* Maps known reason strings to structured metadata with refresh flags.
|
|
1101
1136
|
* @param {string} reason - Resync reason identifier (e.g. 'manual_grid_resync', 'rms_structural_grid_resync')
|
|
1102
|
-
* @returns {
|
|
1137
|
+
* @returns {unknown}
|
|
1103
1138
|
*/
|
|
1104
1139
|
function buildGridResyncMetadata(reason) {
|
|
1105
1140
|
const resetSource = String(reason || '').trim() || 'dexbot_grid_resync';
|
|
@@ -1124,12 +1159,12 @@ function buildGridResyncMetadata(reason) {
|
|
|
1124
1159
|
/**
|
|
1125
1160
|
* Build grid resync options from a reason string or metadata object.
|
|
1126
1161
|
* @param {string|any} reasonOrMetadata - Reason string or metadata object
|
|
1127
|
-
* @returns {
|
|
1162
|
+
* @returns {unknown}
|
|
1128
1163
|
*/
|
|
1129
1164
|
function buildGridResyncOptions(reasonOrMetadata) {
|
|
1130
|
-
const metadata = typeof reasonOrMetadata === 'string'
|
|
1165
|
+
const metadata = (typeof reasonOrMetadata === 'string'
|
|
1131
1166
|
? buildGridResyncMetadata(reasonOrMetadata)
|
|
1132
|
-
: reasonOrMetadata;
|
|
1167
|
+
: reasonOrMetadata);
|
|
1133
1168
|
return {
|
|
1134
1169
|
refreshCenterPrice: !!metadata?.shouldRefreshCenterPrice,
|
|
1135
1170
|
centerRefreshContext: metadata?.centerRefreshContext,
|
|
@@ -1152,16 +1187,17 @@ function promoteAmaCenterSnapshotForGridReset(botKey) {
|
|
|
1152
1187
|
const snapshotPath = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
|
|
1153
1188
|
try {
|
|
1154
1189
|
const result = updateDynamicGridSnapshotSync(snapshotPath, (snapshot) => {
|
|
1155
|
-
const
|
|
1190
|
+
const snap = snapshot;
|
|
1191
|
+
const amaCenterPrice = Number(snap?.amaCenterPrice);
|
|
1156
1192
|
if (!Number.isFinite(amaCenterPrice) || amaCenterPrice <= 0) {
|
|
1157
1193
|
return { ok: false, write: false };
|
|
1158
1194
|
}
|
|
1159
|
-
const currentCenterPrice = Number(
|
|
1195
|
+
const currentCenterPrice = Number(snap?.gridCenterPrice ?? snap?.centerPrice);
|
|
1160
1196
|
if (Number.isFinite(currentCenterPrice) && currentCenterPrice === amaCenterPrice) {
|
|
1161
1197
|
return { write: false };
|
|
1162
1198
|
}
|
|
1163
1199
|
return {
|
|
1164
|
-
...
|
|
1200
|
+
...snap,
|
|
1165
1201
|
gridCenterPrice: amaCenterPrice,
|
|
1166
1202
|
centerPrice: amaCenterPrice,
|
|
1167
1203
|
updatedAt: nowIso(),
|
|
@@ -1189,12 +1225,13 @@ function updateBotGridResetMetadata(botKey, options = {}) {
|
|
|
1189
1225
|
const snapshotPath = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
|
|
1190
1226
|
try {
|
|
1191
1227
|
const result = updateDynamicGridSnapshotSync(snapshotPath, (snapshot) => {
|
|
1192
|
-
const
|
|
1228
|
+
const snap = snapshot;
|
|
1229
|
+
const gridCenterPrice = Number(snap?.gridCenterPrice ?? snap?.centerPrice);
|
|
1193
1230
|
if (!Number.isFinite(gridCenterPrice) || gridCenterPrice <= 0) {
|
|
1194
1231
|
return { ok: false, write: false };
|
|
1195
1232
|
}
|
|
1196
1233
|
return {
|
|
1197
|
-
...
|
|
1234
|
+
...snap,
|
|
1198
1235
|
gridCenterPrice,
|
|
1199
1236
|
centerPrice: gridCenterPrice,
|
|
1200
1237
|
lastGridResetAt: resetAt,
|
|
@@ -1212,7 +1249,7 @@ function updateBotGridResetMetadata(botKey, options = {}) {
|
|
|
1212
1249
|
* Perform a full grid resync: reload config, optionally refresh center price,
|
|
1213
1250
|
* recalculate the grid, persist, and record reset metadata.
|
|
1214
1251
|
* @param {import('./dexbot_class.js').DEXBot} bot
|
|
1215
|
-
* @param {
|
|
1252
|
+
* @param {unknown} [options] - Grid resync options
|
|
1216
1253
|
* @param {boolean} [options.skipIdle=false] - Skip the idle-cooldown deferral
|
|
1217
1254
|
* @returns {Promise<boolean>} True if resync succeeded
|
|
1218
1255
|
*/
|
|
@@ -1850,12 +1887,12 @@ function setupBlockchainFetchInterval(bot) {
|
|
|
1850
1887
|
// from the window (then re-create them as duplicates).
|
|
1851
1888
|
// Defer the sync to a clean read; fills are still
|
|
1852
1889
|
// caught by subscription events and the next cycle.
|
|
1853
|
-
chainOpenOrders = (typeof bot._readOpenOrdersHook === 'function')
|
|
1890
|
+
chainOpenOrders = ((typeof bot._readOpenOrdersHook === 'function')
|
|
1854
1891
|
? await bot._readOpenOrdersHook()
|
|
1855
1892
|
: await readOpenOrdersGuarded(chainOrders, bot.accountId, {
|
|
1856
1893
|
log: (message, level) => bot._log(message, level),
|
|
1857
1894
|
label: 'PERIODIC-SYNC',
|
|
1858
|
-
});
|
|
1895
|
+
}));
|
|
1859
1896
|
if (chainOpenOrders !== null) {
|
|
1860
1897
|
const syncResult = await bot.manager.synchronizeWithChain(chainOpenOrders, 'periodicBlockchainFetch');
|
|
1861
1898
|
if (syncResult.filledOrders && syncResult.filledOrders.length > 0) {
|
|
@@ -2039,7 +2076,7 @@ function isOrderDoesNotExistError(message, orderId) {
|
|
|
2039
2076
|
* manager._broadcastingStartedAt on every holder, so its age stays small;
|
|
2040
2077
|
* a frozen timestamp ages past BROADCAST_STALE_CLEAR_MS and we let the tick
|
|
2041
2078
|
* through so maintenance can hard-reset the flag.
|
|
2042
|
-
* @param {
|
|
2079
|
+
* @param {unknown} bot
|
|
2043
2080
|
* @returns {boolean} true when the caller should skip this tick
|
|
2044
2081
|
*/
|
|
2045
2082
|
function shouldDeferMaintenanceForBroadcast(bot) {
|
|
@@ -2067,7 +2104,7 @@ function shouldDeferMaintenanceForBroadcast(bot) {
|
|
|
2067
2104
|
* any such section visible: when the live hold crosses
|
|
2068
2105
|
* TIMING.GRID_LOCK_HOLD_WARN_MS it emits a rate-limited warn. Called from the
|
|
2069
2106
|
* maintenance tick so holds outside a broadcast region are observed too.
|
|
2070
|
-
* @param {
|
|
2107
|
+
* @param {unknown} bot
|
|
2071
2108
|
* @returns {number} Observed hold duration in ms (0 when not held)
|
|
2072
2109
|
*/
|
|
2073
2110
|
function checkGridLockHoldDuration(bot) {
|
|
@@ -2112,7 +2149,7 @@ function getMaintenanceIdleDelayMs(ctx) {
|
|
|
2112
2149
|
: TIMING.BLOCKCHAIN_SETTLE_DELAY_MS;
|
|
2113
2150
|
if (settleDelayMs <= 0)
|
|
2114
2151
|
return 0;
|
|
2115
|
-
if (ctx?._incomingFillQueue?.length > 0)
|
|
2152
|
+
if ((ctx?._incomingFillQueue?.length ?? 0) > 0)
|
|
2116
2153
|
return settleDelayMs;
|
|
2117
2154
|
const lastActivityAt = Number(ctx?._lastGridActivityAt || 0);
|
|
2118
2155
|
if (!Number.isFinite(lastActivityAt) || lastActivityAt <= 0)
|
|
@@ -2138,9 +2175,9 @@ function scheduleMaintenanceAfterIdle(ctx, context, options = {}) {
|
|
|
2138
2175
|
ctx._maintenanceIdleTimer = null;
|
|
2139
2176
|
if (ctx._shuttingDown)
|
|
2140
2177
|
return;
|
|
2141
|
-
ctx._runGridMaintenance(context, timerOptions)
|
|
2142
|
-
|
|
2143
|
-
ctx._warn(`Deferred ${context} grid maintenance failed: ${getErrorMessage(err)}`);
|
|
2178
|
+
ctx._runGridMaintenance?.(context, timerOptions)
|
|
2179
|
+
?.catch((err) => {
|
|
2180
|
+
ctx._warn?.(`Deferred ${context} grid maintenance failed: ${getErrorMessage(err)}`);
|
|
2144
2181
|
if (ctx.manager) {
|
|
2145
2182
|
ctx.manager._recoveryState = { ...ctx.manager._recoveryState, lastFailureAt: Date.now() };
|
|
2146
2183
|
}
|
|
@@ -2150,7 +2187,7 @@ function scheduleMaintenanceAfterIdle(ctx, context, options = {}) {
|
|
|
2150
2187
|
/**
|
|
2151
2188
|
* Schedule a deferred grid resync after idle delay elapses.
|
|
2152
2189
|
* @param {Object} ctx - Bot context
|
|
2153
|
-
* @param {
|
|
2190
|
+
* @param {unknown} [options] - Grid resync options
|
|
2154
2191
|
*/
|
|
2155
2192
|
function scheduleDeferredGridResync(ctx, options = {}) {
|
|
2156
2193
|
if (!ctx ||
|
|
@@ -2173,17 +2210,17 @@ function scheduleDeferredGridResync(ctx, options = {}) {
|
|
|
2173
2210
|
return;
|
|
2174
2211
|
if (triggerFileWasPresent && !storage.exists(ctx.triggerFile))
|
|
2175
2212
|
return;
|
|
2176
|
-
ctx.manager
|
|
2177
|
-
const ok = await ctx._performGridResync(options);
|
|
2213
|
+
ctx.manager?._fillProcessingLock?.acquire?.(async () => {
|
|
2214
|
+
const ok = await ctx._performGridResync?.(options);
|
|
2178
2215
|
if (!ok && !ctx._shuttingDown) {
|
|
2179
2216
|
const curIdleMs = getMaintenanceIdleDelayMs(ctx);
|
|
2180
2217
|
const reason = curIdleMs > 0
|
|
2181
2218
|
? `idle cooldown (${Math.ceil(curIdleMs / TIMING.MILLISECONDS_PER_SECOND)}s)`
|
|
2182
2219
|
: 'grid resync rejected or failed';
|
|
2183
|
-
ctx._warn(`Deferred trigger reset blocked: ${reason}; retaining existing grid state.`);
|
|
2220
|
+
ctx._warn?.(`Deferred trigger reset blocked: ${reason}; retaining existing grid state.`);
|
|
2184
2221
|
}
|
|
2185
|
-
})
|
|
2186
|
-
ctx._warn(`Deferred trigger reset lock error: ${getErrorMessage(err)}`);
|
|
2222
|
+
})?.catch((err) => {
|
|
2223
|
+
ctx._warn?.(`Deferred trigger reset lock error: ${getErrorMessage(err)}`);
|
|
2187
2224
|
if (ctx.manager) {
|
|
2188
2225
|
ctx.manager._recoveryState = { ...ctx.manager._recoveryState, lastFailureAt: Date.now() };
|
|
2189
2226
|
}
|
|
@@ -2466,7 +2503,7 @@ async function executeMaintenanceLogic(bot, context) {
|
|
|
2466
2503
|
* dedupe concurrent requests; the re-center moves the boundary, which clears
|
|
2467
2504
|
* any held-plan signature). Resets whenever the spread heals or a correction
|
|
2468
2505
|
* places orders.
|
|
2469
|
-
* @param {
|
|
2506
|
+
* @param {unknown} bot
|
|
2470
2507
|
* @param {boolean} spreadChecked - Whether the spread check ran this tick
|
|
2471
2508
|
* @param {number} ordersPlaced - Correction orders placed this tick
|
|
2472
2509
|
* @returns {{staleMs: number, escalated: boolean}}
|
|
@@ -2552,9 +2589,9 @@ async function cancelOrderDeferredOnUncertain(bot, order) {
|
|
|
2552
2589
|
// Test seam: compiled ESM exports cannot be monkey-patched, so tests
|
|
2553
2590
|
// may override cancellation through this bot-level hook.
|
|
2554
2591
|
if (typeof bot._submitCancelOrder === 'function') {
|
|
2555
|
-
return await bot._submitCancelOrder(order.orderId);
|
|
2592
|
+
return await bot._submitCancelOrder(String(order.orderId));
|
|
2556
2593
|
}
|
|
2557
|
-
return await chainOrders.cancelOrder(bot.account, bot.privateKey, order.orderId);
|
|
2594
|
+
return await chainOrders.cancelOrder(bot.account, bot.privateKey, String(order.orderId));
|
|
2558
2595
|
}
|
|
2559
2596
|
catch (err) {
|
|
2560
2597
|
if (err instanceof BroadcastUncertainError) {
|
|
@@ -2712,7 +2749,7 @@ async function checkBtsBalanceAndAcquire(bot) {
|
|
|
2712
2749
|
const minBtsVal = calculateOrderCreationFees(bot.config.assetA, bot.config.assetB, totalTarget, btsReservationMultiplier);
|
|
2713
2750
|
if (minBtsVal <= 0)
|
|
2714
2751
|
return;
|
|
2715
|
-
const effectiveMin = (bot.config.min_BTS_value > 0) ? bot.config.min_BTS_value : minBtsVal;
|
|
2752
|
+
const effectiveMin = ((bot.config.min_BTS_value ?? 0) > 0) ? bot.config.min_BTS_value : minBtsVal;
|
|
2716
2753
|
const btsFree = bot.manager.btsBalance.free || 0;
|
|
2717
2754
|
const btsAcquireThreshold = bot.config?.feeParams?.BTS_ACQUIRE_THRESHOLD;
|
|
2718
2755
|
const triggerAt = effectiveMin * btsAcquireThreshold;
|
|
@@ -3047,14 +3084,14 @@ function wireStructuralGridResyncRequest(bot) {
|
|
|
3047
3084
|
bot._recoverySyncInFlight = (bot._recoverySyncInFlight || 0) + 1;
|
|
3048
3085
|
let resetResult;
|
|
3049
3086
|
try {
|
|
3050
|
-
resetResult = await bot.requestGridReset('rms_structural_grid_resync', {
|
|
3087
|
+
resetResult = await (bot.requestGridReset('rms_structural_grid_resync', {
|
|
3051
3088
|
refreshCenterPrice: false,
|
|
3052
3089
|
// Structural resync is a chain-read/rebuild; do not let a
|
|
3053
3090
|
// fill storm starve it behind the idle cooldown or the
|
|
3054
3091
|
// fill-processing lock.
|
|
3055
3092
|
skipIdle: true,
|
|
3056
3093
|
skipFillLock: true,
|
|
3057
|
-
});
|
|
3094
|
+
}));
|
|
3058
3095
|
}
|
|
3059
3096
|
finally {
|
|
3060
3097
|
bot._recoverySyncInFlight = Math.max(0, (bot._recoverySyncInFlight || 0) - 1);
|
|
@@ -3203,7 +3240,7 @@ async function syncOpenOrdersAndProcessFillsImpl(bot, tag) {
|
|
|
3203
3240
|
return { syncResult: null, aborted: true, hasUnmatched: -1, openOrders: null };
|
|
3204
3241
|
}
|
|
3205
3242
|
}
|
|
3206
|
-
export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, countLiveReserveOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
|
|
3243
|
+
export { loadBotsConfigSnapshot, isWrapperAdapterOwner, checkAndApplyBotConfigChanges, buildBotConfigFingerprint, refreshDynamicWeightDistribution, performGridResync, updateBotGridResetMetadata, handlePendingTriggerReset, setupTriggerFileDetection, performPeriodicGridChecks, isOpenOrdersSyncLoopEnabled, startOpenOrdersSyncLoop, stopOpenOrdersSyncLoop, setupBlockchainFetchInterval, stopBlockchainFetchInterval, setupBotsConfigPollInterval, stopBotsConfigPollInterval, executeMaintenanceLogic, getTargetedSyncReason, maybeRunTargetedDriftReconciliation, countLiveReserveOrders, cancelDustOrders, isOrderDoesNotExistError, runGridMaintenance, releaseMarketAdapterRuntime, syncMarketAdapterOnPeriodicConfigCheck, usesAmaGridPrice, runDustHealthCheck, setupDustHealthCheckInterval, requestGridReset, wireStructuralGridResyncRequest, getPipelineSignals, markGridActivity, getMetrics, syncOpenOrdersAndProcessFills, shouldDeferMaintenanceForBroadcast, checkGridLockHoldDuration };
|
|
3207
3244
|
export default {
|
|
3208
3245
|
loadBotsConfigSnapshot,
|
|
3209
3246
|
isWrapperAdapterOwner,
|
|
@@ -1,28 +1,29 @@
|
|
|
1
1
|
/** Startup runtime - bot initialization, grid placement, and startup sequence */
|
|
2
|
+
import type { BotLike } from './types.js';
|
|
2
3
|
/**
|
|
3
4
|
* Initialize the startup state: account orders, manager, persisted data.
|
|
4
5
|
* @param {import('./dexbot_class.js').DEXBot} bot
|
|
5
6
|
* @returns {Promise<Object>} startupState
|
|
6
7
|
*/
|
|
7
|
-
declare function initializeStartupState(bot:
|
|
8
|
-
persistedGrid:
|
|
9
|
-
persistedBtsFeesOwed:
|
|
10
|
-
persistedBoundaryIdx:
|
|
11
|
-
persistedBtsBalance:
|
|
12
|
-
persistedRecentFillKeys:
|
|
13
|
-
persistedGenesis:
|
|
14
|
-
persistedGapEvacStreaks:
|
|
8
|
+
declare function initializeStartupState(bot: BotLike): Promise<{
|
|
9
|
+
persistedGrid: unknown[] | null;
|
|
10
|
+
persistedBtsFeesOwed: unknown;
|
|
11
|
+
persistedBoundaryIdx: number | null;
|
|
12
|
+
persistedBtsBalance: unknown;
|
|
13
|
+
persistedRecentFillKeys: unknown;
|
|
14
|
+
persistedGenesis: {} | null;
|
|
15
|
+
persistedGapEvacStreaks: {} | null;
|
|
15
16
|
}>;
|
|
16
17
|
/**
|
|
17
18
|
* Finish the startup sequence: activate fill listener, reconcile grid, place initial orders.
|
|
18
19
|
* @param {import('./dexbot_class.js').DEXBot} bot
|
|
19
20
|
* @param {Object} startupState
|
|
20
21
|
*/
|
|
21
|
-
declare function finishStartupSequence(bot:
|
|
22
|
+
declare function finishStartupSequence(bot: BotLike, startupState: Awaited<ReturnType<typeof initializeStartupState>>): Promise<void>;
|
|
22
23
|
/**
|
|
23
24
|
* Place initial orders on the blockchain (extracted logic from original placeInitialOrders).
|
|
24
25
|
* @param {import('./dexbot_class.js').DEXBot} bot
|
|
25
26
|
*/
|
|
26
|
-
declare function placeInitialOrdersImpl(bot:
|
|
27
|
+
declare function placeInitialOrdersImpl(bot: BotLike): Promise<void>;
|
|
27
28
|
export { initializeStartupState, finishStartupSequence, placeInitialOrdersImpl };
|
|
28
29
|
//# sourceMappingURL=dexbot_startup_runtime.d.ts.map
|