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.
- package/CHANGELOG.md +35 -4
- package/README.md +2 -1
- package/analysis/README.md +2 -0
- package/analysis/tradingview/README.md +1 -1
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
- 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 +2 -1
- 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 -17
- 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 +6 -5
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +11 -63
- 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 +7 -4
- 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 +1 -1
- package/dist/analysis/fills_source.d.ts +2 -2
- package/dist/analysis/fills_source.js +14 -12
- 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.js +29 -29
- 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 -1
- package/dist/analysis/trade_profitability.d.ts +23 -2
- package/dist/analysis/trade_profitability.js +50 -50
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
- package/dist/analysis/tradingview/analyze_tradingview.js +6 -5
- package/dist/analysis/tradingview/grid_reset_config.d.ts +41 -32
- package/dist/analysis/tradingview/grid_reset_config.js +23 -11
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -9
- package/dist/analysis/tradingview/grid_reset_sim.js +4 -3
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +18 -19
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -1
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +5 -5
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +5 -4
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +9 -3
- package/dist/analysis/trend_detection/huber_scale_variants.js +4 -4
- 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 +11 -11
- 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 +284 -117
- package/dist/market_adapter/core/market_adapter_service.js +137 -113
- package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
- package/dist/market_adapter/core/strategies/ama.js +2 -4
- 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 +34 -6
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +7 -7
- 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 +96 -224
- 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 -21
- 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 -32
- package/dist/market_adapter/market_adapter.js +67 -48
- 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 +527 -31
- package/dist/modules/constants.js +15 -47
- 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 +108 -83
- 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 +16 -15
- 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 +4 -4
- 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 +225 -180
- package/dist/modules/order/manager.js +80 -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 +84 -53
- 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 +310 -110
- package/dist/modules/order/utils/order.js +122 -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 +1 -4
- package/dist/modules/paths.js +1 -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 +1 -12
- package/dist/modules/utils/time_range.js +1 -1
- 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 +65 -40
- package/dist/scripts/chart_command.d.ts +27 -18
- package/dist/scripts/chart_command.js +13 -11
- 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/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 +63 -35
- 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 +10 -9
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
- package/docs/GRID_RECALCULATION.md +4 -2
- 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 +14 -3
- package/docs/architecture.md +12 -9
- package/docs/developer_guide.md +6 -6
- package/market_adapter/README.md +6 -1
- package/modules/README.md +4 -1
- package/package.json +4 -1
|
@@ -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) {
|
|
@@ -499,9 +507,10 @@ async function checkAndApplyBotConfigChanges(bot, context = 'bots-config poll',
|
|
|
499
507
|
`Targeted maintenance will place missing / cancel excess orders.`, 'info');
|
|
500
508
|
// Deliver the promise above instead of waiting for the next fill
|
|
501
509
|
// or the 240-min fetch: run the targeted drift reconciliation
|
|
502
|
-
// right away (same fire-and-forget shape as the poll tick
|
|
503
|
-
// callee owns
|
|
504
|
-
//
|
|
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.
|
|
505
514
|
try {
|
|
506
515
|
const driftRun = maybeRunTargetedDriftReconciliation(bot, `${context} config pickup`);
|
|
507
516
|
driftRun?.catch?.((err) => {
|
|
@@ -571,9 +580,9 @@ function getTargetActiveOrders(config, side) {
|
|
|
571
580
|
* window = bottom slots = floor edge) makes the edge pick land on window
|
|
572
581
|
* members and the count reads N/N with zero dedicated reserves, so the
|
|
573
582
|
* deficit never fires (issue #27 follow-up).
|
|
574
|
-
* @param {
|
|
575
|
-
* @param {
|
|
576
|
-
* @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
|
|
577
586
|
* @returns {number|null} Live reserve count, or null when unclassifiable
|
|
578
587
|
*/
|
|
579
588
|
function countLiveReserveOrders(manager, config, type) {
|
|
@@ -679,10 +688,12 @@ function getTargetedSyncReason(bot) {
|
|
|
679
688
|
if (drift && drift.isValid === false) {
|
|
680
689
|
return { reason: `fund drift: ${drift.reason}`, targetBuy, targetSell, liveBuy, liveSell, drift };
|
|
681
690
|
}
|
|
682
|
-
//
|
|
683
|
-
//
|
|
684
|
-
//
|
|
685
|
-
//
|
|
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.
|
|
686
697
|
if (bot._spreadFundsExhausted === true) {
|
|
687
698
|
return { reason: 'spread correction had no free funds', targetBuy, targetSell, liveBuy, liveSell, drift };
|
|
688
699
|
}
|
|
@@ -716,6 +727,16 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
|
|
|
716
727
|
bot._warn(`[TARGETED-SYNC] Chain sync failed during ${context}, skipping reconciliation`);
|
|
717
728
|
return false;
|
|
718
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;
|
|
719
740
|
const remaining = getTargetedSyncReason(bot);
|
|
720
741
|
const unmatchedCount = Number(syncResult?.unmatchedChainOrders?.length || 0);
|
|
721
742
|
if (remaining || unmatchedCount > 0) {
|
|
@@ -750,7 +771,7 @@ async function maybeRunTargetedDriftReconciliation(bot, context) {
|
|
|
750
771
|
* Delegates to the canonical launcher/adapter_requirement helper so the
|
|
751
772
|
* fingerprint is semantic (AMA-relevant changes only) and identical to the
|
|
752
773
|
* unlock wrapper watchdog's view of the same file.
|
|
753
|
-
* @returns {
|
|
774
|
+
* @returns {unknown} Snapshot with exists flag, fingerprint, active bots list, and adapter requirement
|
|
754
775
|
*/
|
|
755
776
|
function loadBotsConfigSnapshot() {
|
|
756
777
|
return readAdapterRequirement(PROFILES_BOTS_FILE);
|
|
@@ -853,9 +874,9 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
|
|
|
853
874
|
// fingerprints, retry next tick.
|
|
854
875
|
let snapshot = null;
|
|
855
876
|
try {
|
|
856
|
-
snapshot = typeof bot._loadBotsConfigSnapshot === 'function'
|
|
877
|
+
snapshot = (typeof bot._loadBotsConfigSnapshot === 'function'
|
|
857
878
|
? await bot._loadBotsConfigSnapshot()
|
|
858
|
-
: loadBotsConfigSnapshot();
|
|
879
|
+
: loadBotsConfigSnapshot());
|
|
859
880
|
}
|
|
860
881
|
catch (err) {
|
|
861
882
|
bot._warn(`Ignoring unreadable bots.json during ${context}; keeping previous market adapter state.`);
|
|
@@ -897,8 +918,9 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
|
|
|
897
918
|
// ?? (not ||): the semantic fingerprint is legitimately '' when no
|
|
898
919
|
// active AMA bot exists, and '' must compare equal to a stored ''.
|
|
899
920
|
const previousFingerprint = bot._marketAdapterWatchdogFingerprint ?? null;
|
|
900
|
-
const
|
|
901
|
-
|
|
921
|
+
const fingerprint = snapshot.fingerprint;
|
|
922
|
+
const changed = fingerprint !== previousFingerprint;
|
|
923
|
+
bot._marketAdapterWatchdogFingerprint = fingerprint;
|
|
902
924
|
if (changed) {
|
|
903
925
|
bot._log(`Detected bots.json changes during ${context}; re-evaluating market adapter requirements.`);
|
|
904
926
|
}
|
|
@@ -953,9 +975,10 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
|
|
|
953
975
|
}
|
|
954
976
|
// Cross-reference config-active bots against actually running PM2 processes
|
|
955
977
|
// so we don't start the adapter for configured AMA bots that aren't running.
|
|
978
|
+
const activeBots = (snapshot.activeBots ?? []);
|
|
956
979
|
const runningActiveBots = pm2QueryFailed
|
|
957
|
-
?
|
|
958
|
-
:
|
|
980
|
+
? activeBots
|
|
981
|
+
: activeBots.filter((b) => processNames.includes(String(b.name)));
|
|
959
982
|
const needsAdapterForRunningBots = runningActiveBots.some(usesAmaGridPrice);
|
|
960
983
|
if (!snapshot.exists || !needsAdapterForRunningBots) {
|
|
961
984
|
const shouldStop = pm2QueryFailed || processNames.includes(MARKET_ADAPTER_APP_NAME);
|
|
@@ -1021,7 +1044,7 @@ async function syncMarketAdapterOnPeriodicConfigCheck(bot, context = 'periodic')
|
|
|
1021
1044
|
* Applies live dynamic weights if the bot is whitelisted and weights are ready.
|
|
1022
1045
|
* @param {import('./dexbot_class.js').DEXBot} bot
|
|
1023
1046
|
* @param {string} [context='runtime'] - Context label for logging
|
|
1024
|
-
* @returns {
|
|
1047
|
+
* @returns {unknown}
|
|
1025
1048
|
*/
|
|
1026
1049
|
function refreshDynamicWeightDistribution(bot, context = 'runtime') {
|
|
1027
1050
|
const baseWeights = cloneWeightDistribution(bot._baseWeightDistribution, bot.config?.weightDistribution || bot.manager?.config?.weightDistribution);
|
|
@@ -1077,7 +1100,7 @@ function refreshDynamicWeightDistribution(bot, context = 'runtime') {
|
|
|
1077
1100
|
* Read and parse a trigger file's metadata payload.
|
|
1078
1101
|
* Determines whether the trigger originated from the market adapter or was manual.
|
|
1079
1102
|
* @param {string} triggerFile - Path to the trigger file
|
|
1080
|
-
* @returns {
|
|
1103
|
+
* @returns {unknown} Parsed trigger metadata
|
|
1081
1104
|
*/
|
|
1082
1105
|
function readTriggerMetadata(triggerFile) {
|
|
1083
1106
|
const manualTriggerMetadata = (payload = null) => ({
|
|
@@ -1111,7 +1134,7 @@ function readTriggerMetadata(triggerFile) {
|
|
|
1111
1134
|
* Build grid resync metadata from a reason string.
|
|
1112
1135
|
* Maps known reason strings to structured metadata with refresh flags.
|
|
1113
1136
|
* @param {string} reason - Resync reason identifier (e.g. 'manual_grid_resync', 'rms_structural_grid_resync')
|
|
1114
|
-
* @returns {
|
|
1137
|
+
* @returns {unknown}
|
|
1115
1138
|
*/
|
|
1116
1139
|
function buildGridResyncMetadata(reason) {
|
|
1117
1140
|
const resetSource = String(reason || '').trim() || 'dexbot_grid_resync';
|
|
@@ -1136,12 +1159,12 @@ function buildGridResyncMetadata(reason) {
|
|
|
1136
1159
|
/**
|
|
1137
1160
|
* Build grid resync options from a reason string or metadata object.
|
|
1138
1161
|
* @param {string|any} reasonOrMetadata - Reason string or metadata object
|
|
1139
|
-
* @returns {
|
|
1162
|
+
* @returns {unknown}
|
|
1140
1163
|
*/
|
|
1141
1164
|
function buildGridResyncOptions(reasonOrMetadata) {
|
|
1142
|
-
const metadata = typeof reasonOrMetadata === 'string'
|
|
1165
|
+
const metadata = (typeof reasonOrMetadata === 'string'
|
|
1143
1166
|
? buildGridResyncMetadata(reasonOrMetadata)
|
|
1144
|
-
: reasonOrMetadata;
|
|
1167
|
+
: reasonOrMetadata);
|
|
1145
1168
|
return {
|
|
1146
1169
|
refreshCenterPrice: !!metadata?.shouldRefreshCenterPrice,
|
|
1147
1170
|
centerRefreshContext: metadata?.centerRefreshContext,
|
|
@@ -1164,16 +1187,17 @@ function promoteAmaCenterSnapshotForGridReset(botKey) {
|
|
|
1164
1187
|
const snapshotPath = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
|
|
1165
1188
|
try {
|
|
1166
1189
|
const result = updateDynamicGridSnapshotSync(snapshotPath, (snapshot) => {
|
|
1167
|
-
const
|
|
1190
|
+
const snap = snapshot;
|
|
1191
|
+
const amaCenterPrice = Number(snap?.amaCenterPrice);
|
|
1168
1192
|
if (!Number.isFinite(amaCenterPrice) || amaCenterPrice <= 0) {
|
|
1169
1193
|
return { ok: false, write: false };
|
|
1170
1194
|
}
|
|
1171
|
-
const currentCenterPrice = Number(
|
|
1195
|
+
const currentCenterPrice = Number(snap?.gridCenterPrice ?? snap?.centerPrice);
|
|
1172
1196
|
if (Number.isFinite(currentCenterPrice) && currentCenterPrice === amaCenterPrice) {
|
|
1173
1197
|
return { write: false };
|
|
1174
1198
|
}
|
|
1175
1199
|
return {
|
|
1176
|
-
...
|
|
1200
|
+
...snap,
|
|
1177
1201
|
gridCenterPrice: amaCenterPrice,
|
|
1178
1202
|
centerPrice: amaCenterPrice,
|
|
1179
1203
|
updatedAt: nowIso(),
|
|
@@ -1201,12 +1225,13 @@ function updateBotGridResetMetadata(botKey, options = {}) {
|
|
|
1201
1225
|
const snapshotPath = path.join(PATHS.ORDERS_DIR, `${botKey}.dynamicgrid.json`);
|
|
1202
1226
|
try {
|
|
1203
1227
|
const result = updateDynamicGridSnapshotSync(snapshotPath, (snapshot) => {
|
|
1204
|
-
const
|
|
1228
|
+
const snap = snapshot;
|
|
1229
|
+
const gridCenterPrice = Number(snap?.gridCenterPrice ?? snap?.centerPrice);
|
|
1205
1230
|
if (!Number.isFinite(gridCenterPrice) || gridCenterPrice <= 0) {
|
|
1206
1231
|
return { ok: false, write: false };
|
|
1207
1232
|
}
|
|
1208
1233
|
return {
|
|
1209
|
-
...
|
|
1234
|
+
...snap,
|
|
1210
1235
|
gridCenterPrice,
|
|
1211
1236
|
centerPrice: gridCenterPrice,
|
|
1212
1237
|
lastGridResetAt: resetAt,
|
|
@@ -1224,7 +1249,7 @@ function updateBotGridResetMetadata(botKey, options = {}) {
|
|
|
1224
1249
|
* Perform a full grid resync: reload config, optionally refresh center price,
|
|
1225
1250
|
* recalculate the grid, persist, and record reset metadata.
|
|
1226
1251
|
* @param {import('./dexbot_class.js').DEXBot} bot
|
|
1227
|
-
* @param {
|
|
1252
|
+
* @param {unknown} [options] - Grid resync options
|
|
1228
1253
|
* @param {boolean} [options.skipIdle=false] - Skip the idle-cooldown deferral
|
|
1229
1254
|
* @returns {Promise<boolean>} True if resync succeeded
|
|
1230
1255
|
*/
|
|
@@ -1862,12 +1887,12 @@ function setupBlockchainFetchInterval(bot) {
|
|
|
1862
1887
|
// from the window (then re-create them as duplicates).
|
|
1863
1888
|
// Defer the sync to a clean read; fills are still
|
|
1864
1889
|
// caught by subscription events and the next cycle.
|
|
1865
|
-
chainOpenOrders = (typeof bot._readOpenOrdersHook === 'function')
|
|
1890
|
+
chainOpenOrders = ((typeof bot._readOpenOrdersHook === 'function')
|
|
1866
1891
|
? await bot._readOpenOrdersHook()
|
|
1867
1892
|
: await readOpenOrdersGuarded(chainOrders, bot.accountId, {
|
|
1868
1893
|
log: (message, level) => bot._log(message, level),
|
|
1869
1894
|
label: 'PERIODIC-SYNC',
|
|
1870
|
-
});
|
|
1895
|
+
}));
|
|
1871
1896
|
if (chainOpenOrders !== null) {
|
|
1872
1897
|
const syncResult = await bot.manager.synchronizeWithChain(chainOpenOrders, 'periodicBlockchainFetch');
|
|
1873
1898
|
if (syncResult.filledOrders && syncResult.filledOrders.length > 0) {
|
|
@@ -2051,7 +2076,7 @@ function isOrderDoesNotExistError(message, orderId) {
|
|
|
2051
2076
|
* manager._broadcastingStartedAt on every holder, so its age stays small;
|
|
2052
2077
|
* a frozen timestamp ages past BROADCAST_STALE_CLEAR_MS and we let the tick
|
|
2053
2078
|
* through so maintenance can hard-reset the flag.
|
|
2054
|
-
* @param {
|
|
2079
|
+
* @param {unknown} bot
|
|
2055
2080
|
* @returns {boolean} true when the caller should skip this tick
|
|
2056
2081
|
*/
|
|
2057
2082
|
function shouldDeferMaintenanceForBroadcast(bot) {
|
|
@@ -2079,7 +2104,7 @@ function shouldDeferMaintenanceForBroadcast(bot) {
|
|
|
2079
2104
|
* any such section visible: when the live hold crosses
|
|
2080
2105
|
* TIMING.GRID_LOCK_HOLD_WARN_MS it emits a rate-limited warn. Called from the
|
|
2081
2106
|
* maintenance tick so holds outside a broadcast region are observed too.
|
|
2082
|
-
* @param {
|
|
2107
|
+
* @param {unknown} bot
|
|
2083
2108
|
* @returns {number} Observed hold duration in ms (0 when not held)
|
|
2084
2109
|
*/
|
|
2085
2110
|
function checkGridLockHoldDuration(bot) {
|
|
@@ -2124,7 +2149,7 @@ function getMaintenanceIdleDelayMs(ctx) {
|
|
|
2124
2149
|
: TIMING.BLOCKCHAIN_SETTLE_DELAY_MS;
|
|
2125
2150
|
if (settleDelayMs <= 0)
|
|
2126
2151
|
return 0;
|
|
2127
|
-
if (ctx?._incomingFillQueue?.length > 0)
|
|
2152
|
+
if ((ctx?._incomingFillQueue?.length ?? 0) > 0)
|
|
2128
2153
|
return settleDelayMs;
|
|
2129
2154
|
const lastActivityAt = Number(ctx?._lastGridActivityAt || 0);
|
|
2130
2155
|
if (!Number.isFinite(lastActivityAt) || lastActivityAt <= 0)
|
|
@@ -2150,9 +2175,9 @@ function scheduleMaintenanceAfterIdle(ctx, context, options = {}) {
|
|
|
2150
2175
|
ctx._maintenanceIdleTimer = null;
|
|
2151
2176
|
if (ctx._shuttingDown)
|
|
2152
2177
|
return;
|
|
2153
|
-
ctx._runGridMaintenance(context, timerOptions)
|
|
2154
|
-
|
|
2155
|
-
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)}`);
|
|
2156
2181
|
if (ctx.manager) {
|
|
2157
2182
|
ctx.manager._recoveryState = { ...ctx.manager._recoveryState, lastFailureAt: Date.now() };
|
|
2158
2183
|
}
|
|
@@ -2162,7 +2187,7 @@ function scheduleMaintenanceAfterIdle(ctx, context, options = {}) {
|
|
|
2162
2187
|
/**
|
|
2163
2188
|
* Schedule a deferred grid resync after idle delay elapses.
|
|
2164
2189
|
* @param {Object} ctx - Bot context
|
|
2165
|
-
* @param {
|
|
2190
|
+
* @param {unknown} [options] - Grid resync options
|
|
2166
2191
|
*/
|
|
2167
2192
|
function scheduleDeferredGridResync(ctx, options = {}) {
|
|
2168
2193
|
if (!ctx ||
|
|
@@ -2185,17 +2210,17 @@ function scheduleDeferredGridResync(ctx, options = {}) {
|
|
|
2185
2210
|
return;
|
|
2186
2211
|
if (triggerFileWasPresent && !storage.exists(ctx.triggerFile))
|
|
2187
2212
|
return;
|
|
2188
|
-
ctx.manager
|
|
2189
|
-
const ok = await ctx._performGridResync(options);
|
|
2213
|
+
ctx.manager?._fillProcessingLock?.acquire?.(async () => {
|
|
2214
|
+
const ok = await ctx._performGridResync?.(options);
|
|
2190
2215
|
if (!ok && !ctx._shuttingDown) {
|
|
2191
2216
|
const curIdleMs = getMaintenanceIdleDelayMs(ctx);
|
|
2192
2217
|
const reason = curIdleMs > 0
|
|
2193
2218
|
? `idle cooldown (${Math.ceil(curIdleMs / TIMING.MILLISECONDS_PER_SECOND)}s)`
|
|
2194
2219
|
: 'grid resync rejected or failed';
|
|
2195
|
-
ctx._warn(`Deferred trigger reset blocked: ${reason}; retaining existing grid state.`);
|
|
2220
|
+
ctx._warn?.(`Deferred trigger reset blocked: ${reason}; retaining existing grid state.`);
|
|
2196
2221
|
}
|
|
2197
|
-
})
|
|
2198
|
-
ctx._warn(`Deferred trigger reset lock error: ${getErrorMessage(err)}`);
|
|
2222
|
+
})?.catch((err) => {
|
|
2223
|
+
ctx._warn?.(`Deferred trigger reset lock error: ${getErrorMessage(err)}`);
|
|
2199
2224
|
if (ctx.manager) {
|
|
2200
2225
|
ctx.manager._recoveryState = { ...ctx.manager._recoveryState, lastFailureAt: Date.now() };
|
|
2201
2226
|
}
|
|
@@ -2478,7 +2503,7 @@ async function executeMaintenanceLogic(bot, context) {
|
|
|
2478
2503
|
* dedupe concurrent requests; the re-center moves the boundary, which clears
|
|
2479
2504
|
* any held-plan signature). Resets whenever the spread heals or a correction
|
|
2480
2505
|
* places orders.
|
|
2481
|
-
* @param {
|
|
2506
|
+
* @param {unknown} bot
|
|
2482
2507
|
* @param {boolean} spreadChecked - Whether the spread check ran this tick
|
|
2483
2508
|
* @param {number} ordersPlaced - Correction orders placed this tick
|
|
2484
2509
|
* @returns {{staleMs: number, escalated: boolean}}
|
|
@@ -2564,9 +2589,9 @@ async function cancelOrderDeferredOnUncertain(bot, order) {
|
|
|
2564
2589
|
// Test seam: compiled ESM exports cannot be monkey-patched, so tests
|
|
2565
2590
|
// may override cancellation through this bot-level hook.
|
|
2566
2591
|
if (typeof bot._submitCancelOrder === 'function') {
|
|
2567
|
-
return await bot._submitCancelOrder(order.orderId);
|
|
2592
|
+
return await bot._submitCancelOrder(String(order.orderId));
|
|
2568
2593
|
}
|
|
2569
|
-
return await chainOrders.cancelOrder(bot.account, bot.privateKey, order.orderId);
|
|
2594
|
+
return await chainOrders.cancelOrder(bot.account, bot.privateKey, String(order.orderId));
|
|
2570
2595
|
}
|
|
2571
2596
|
catch (err) {
|
|
2572
2597
|
if (err instanceof BroadcastUncertainError) {
|
|
@@ -2724,7 +2749,7 @@ async function checkBtsBalanceAndAcquire(bot) {
|
|
|
2724
2749
|
const minBtsVal = calculateOrderCreationFees(bot.config.assetA, bot.config.assetB, totalTarget, btsReservationMultiplier);
|
|
2725
2750
|
if (minBtsVal <= 0)
|
|
2726
2751
|
return;
|
|
2727
|
-
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;
|
|
2728
2753
|
const btsFree = bot.manager.btsBalance.free || 0;
|
|
2729
2754
|
const btsAcquireThreshold = bot.config?.feeParams?.BTS_ACQUIRE_THRESHOLD;
|
|
2730
2755
|
const triggerAt = effectiveMin * btsAcquireThreshold;
|
|
@@ -3059,14 +3084,14 @@ function wireStructuralGridResyncRequest(bot) {
|
|
|
3059
3084
|
bot._recoverySyncInFlight = (bot._recoverySyncInFlight || 0) + 1;
|
|
3060
3085
|
let resetResult;
|
|
3061
3086
|
try {
|
|
3062
|
-
resetResult = await bot.requestGridReset('rms_structural_grid_resync', {
|
|
3087
|
+
resetResult = await (bot.requestGridReset('rms_structural_grid_resync', {
|
|
3063
3088
|
refreshCenterPrice: false,
|
|
3064
3089
|
// Structural resync is a chain-read/rebuild; do not let a
|
|
3065
3090
|
// fill storm starve it behind the idle cooldown or the
|
|
3066
3091
|
// fill-processing lock.
|
|
3067
3092
|
skipIdle: true,
|
|
3068
3093
|
skipFillLock: true,
|
|
3069
|
-
});
|
|
3094
|
+
}));
|
|
3070
3095
|
}
|
|
3071
3096
|
finally {
|
|
3072
3097
|
bot._recoverySyncInFlight = Math.max(0, (bot._recoverySyncInFlight || 0) - 1);
|
|
@@ -3215,7 +3240,7 @@ async function syncOpenOrdersAndProcessFillsImpl(bot, tag) {
|
|
|
3215
3240
|
return { syncResult: null, aborted: true, hasUnmatched: -1, openOrders: null };
|
|
3216
3241
|
}
|
|
3217
3242
|
}
|
|
3218
|
-
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 };
|
|
3219
3244
|
export default {
|
|
3220
3245
|
loadBotsConfigSnapshot,
|
|
3221
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
|