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
|
@@ -101,7 +101,7 @@ const GRID_CONSTANTS = {
|
|
|
101
101
|
* Single source of truth: per-bot override wins, global GRID_COMPARISON default
|
|
102
102
|
* is the fallback. Used by compareGrids() and re-exported for the maintenance
|
|
103
103
|
* runtime so the reset log always shows the level that actually fired.
|
|
104
|
-
* @param {
|
|
104
|
+
* @param {unknown} manager - OrderManager instance (may be null)
|
|
105
105
|
* @returns {number} Threshold in percent (0 = disabled)
|
|
106
106
|
*/
|
|
107
107
|
export function resolveRmsThresholdPct(manager) {
|
|
@@ -117,12 +117,13 @@ function _snapshotFundState(manager) {
|
|
|
117
117
|
};
|
|
118
118
|
}
|
|
119
119
|
import { floatToBlockchainInt, getPrecisionByOrderType, getPrecisionsForManager, calculateOrderCreationFees, calculateOrderSizes, calculateRotationOrderSizes, calculateAvailableFundsValue, calculateGridSideDivergenceMetric, getPrecisionSlack, getMinOrderSize, getSingleDustThreshold, getGridBestPrices, calculateSpreadFromOrders, allocateFundsByWeights, calculateGapSlots as _mathGapSlots, priceSlotEqual, getBtsSide, getSellStartIdx, resolveGapBand, countGapBandSpread, validatePersistedBoundary, isTransientInBandRejection, adjustBudgetForBtsFees, clamp, derivePriceLevels, buildGenesisFromPriceLevels, assertSlotPriceInvariant, priceForSlot, hashPriceLevels, } from './utils/math.js';
|
|
120
|
-
import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveReserveCount, reserveEdgeIdSet, resolveLiveReserveEdgeAnchorPrice, liveWindowIdSet } from './utils/order.js';
|
|
120
|
+
import { filterOrdersByType, checkSizesBeforeMinimum, checkSizeThreshold, resolveConfiguredPriceBound, shouldFlagOutOfSpread, isOrderHealthy, isPhantomOrder, isSlotAvailable, isOrderOnChain, isOrderPlaced, hasOnChainId, isEmptyGridSlot, parseSlotIndex, calculateIdealBoundary, assignGridRoles, resolveOnChainRetypeType, resolveReserveCount, reserveEdgeIdSet, resolveLiveReserveEdgeAnchorPrice, liveWindowIdSet, getOrderTypeFromUpdatedFlags } from './utils/order.js';
|
|
121
121
|
import { loadAmaCenterPrice, loadAmaCenterSnapshot, withBlockchainRetry, restoreLastFillPivot, resetLastFillPivot } from './utils/system.js';
|
|
122
122
|
import * as MathUtils from './utils/math.js';
|
|
123
123
|
import { derivePriceWithPoolRef, resolveStartPriceMode } from './utils/withPoolRef.js';
|
|
124
124
|
import { getWhitelistFlags } from '../market_adapter_whitelist.js';
|
|
125
125
|
import { hasGenesisLadder, recordMissingGenesisFault, resolvePersistedGenesis } from './genesis_policy.js';
|
|
126
|
+
import { WorkingGrid } from './working_grid.js';
|
|
126
127
|
import { getErrorMessage } from '../utils/errors.js';
|
|
127
128
|
const calculateGapSlots = _mathGapSlots;
|
|
128
129
|
export { calculateGapSlots };
|
|
@@ -301,11 +302,14 @@ export async function _getSizingContext(manager, side, { skipRecalc = false } =
|
|
|
301
302
|
* - n = ceil(ln(1.02) / ln(1.005)) = ceil(3.98) = 4 steps
|
|
302
303
|
* - G = max(2, 4) = 4 slots
|
|
303
304
|
*
|
|
304
|
-
* @param {
|
|
305
|
-
* @returns {
|
|
305
|
+
* @param {unknown} config - Grid configuration
|
|
306
|
+
* @returns {unknown}
|
|
306
307
|
*/
|
|
307
308
|
export function createOrderGrid(config) {
|
|
308
|
-
const
|
|
309
|
+
const startPrice = Number(config.startPrice);
|
|
310
|
+
const minPrice = Number(config.minPrice);
|
|
311
|
+
const maxPrice = Number(config.maxPrice);
|
|
312
|
+
const incrementPercent = Number(config.incrementPercent);
|
|
309
313
|
// FIX: Add comprehensive input validation to prevent silent grid creation failures
|
|
310
314
|
if (!Number.isFinite(startPrice)) {
|
|
311
315
|
throw new Error(`Invalid startPrice: ${startPrice}. Must be a finite number.`);
|
|
@@ -361,10 +365,6 @@ export function createOrderGrid(config) {
|
|
|
361
365
|
//
|
|
362
366
|
// STRATEGY: Center the spread gap around startPrice
|
|
363
367
|
const boundaryIdx = calculateIdealBoundary(priceLevels.map((p) => ({ price: p })), startPrice, gapSlots);
|
|
364
|
-
// ================================================================================
|
|
365
|
-
// STEP 4: CREATE ORDER OBJECTS
|
|
366
|
-
// ================================================================================
|
|
367
|
-
// Convert price levels to order objects with assigned roles.
|
|
368
368
|
const orders = priceLevels.map((price, i) => ({
|
|
369
369
|
id: `slot-${i}`,
|
|
370
370
|
price,
|
|
@@ -445,7 +445,8 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
|
|
|
445
445
|
let genesis = null;
|
|
446
446
|
const validationMode = (() => {
|
|
447
447
|
try {
|
|
448
|
-
const
|
|
448
|
+
const proc = globalThis.process;
|
|
449
|
+
const raw = proc?.env?.GRID_PRICE_SLOT_VALIDATION ?? 'log';
|
|
449
450
|
return String(raw).toLowerCase() === 'enforce' ? 'enforce' : 'log';
|
|
450
451
|
}
|
|
451
452
|
catch {
|
|
@@ -667,7 +668,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
|
|
|
667
668
|
// a row). Best-effort — load continues boundary-less
|
|
668
669
|
// either way and the next fill batch re-anchors live.
|
|
669
670
|
try {
|
|
670
|
-
const acct = manager
|
|
671
|
+
const acct = manager.accountOrders;
|
|
671
672
|
if (acct && typeof acct.clearPersistedBoundary === 'function') {
|
|
672
673
|
await acct.clearPersistedBoundary();
|
|
673
674
|
manager.logger?.log?.(`[GRID-LOAD] Erased poisoned persisted boundary (${boundaryIdx}); ` +
|
|
@@ -693,7 +694,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
|
|
|
693
694
|
// same one-increment drift rule the runtime guard applies.
|
|
694
695
|
if (restoredBoundary !== null) {
|
|
695
696
|
try {
|
|
696
|
-
restoreLastFillPivot(manager, manager
|
|
697
|
+
restoreLastFillPivot(manager, manager.accountOrders?.loadLastFillPivot?.() ?? null);
|
|
697
698
|
}
|
|
698
699
|
catch (pivotErr) {
|
|
699
700
|
manager.logger?.log?.(`[LAST-FILL-GUARD] Persisted pivot restore failed (${getErrorMessage(pivotErr)}); book seed takes over`, 'warn');
|
|
@@ -784,7 +785,7 @@ export async function loadGrid(manager, grid, boundaryIdx = null, genesisInput =
|
|
|
784
785
|
// Gap 6: Grid size cap — validate grid slot count against expected maximum.
|
|
785
786
|
// Formula: placedOrders (active+partial with orderId) + gapSlots + 1 tolerance slot.
|
|
786
787
|
const bloatResult = isGridBloated(manager, grid);
|
|
787
|
-
if (bloatResult.bloated) {
|
|
788
|
+
if (bloatResult.bloated && bloatResult.details) {
|
|
788
789
|
const d = bloatResult.details;
|
|
789
790
|
const grace = isGridBloatGraceActive(manager);
|
|
790
791
|
if (grace.active) {
|
|
@@ -904,7 +905,7 @@ export async function initializeGrid(manager) {
|
|
|
904
905
|
// the old `priceMode || 'auto'` read (priceMode is never set in
|
|
905
906
|
// the runtime path) let a poolRef override startPrice:"book".
|
|
906
907
|
const startPriceMode = resolveStartPriceMode(mpRaw, manager.config.priceMode || 'auto');
|
|
907
|
-
const derived = await derivePriceWithPoolRef(BitShares, manager.config.assetA, manager.config.assetB, startPriceMode, manager.config.poolRef);
|
|
908
|
+
const derived = await derivePriceWithPoolRef(BitShares, manager.config.assetA ?? '', manager.config.assetB ?? '', startPriceMode, manager.config.poolRef);
|
|
908
909
|
if (derived) {
|
|
909
910
|
manager.logger?.log?.(`[DIAGNOSTIC] initializeGrid: Derived new startPrice=${derived.toFixed(8)} (mode=${startPriceMode})`, 'info');
|
|
910
911
|
manager.config.startPrice = Number(derived);
|
|
@@ -930,7 +931,7 @@ export async function initializeGrid(manager) {
|
|
|
930
931
|
let gp = mp;
|
|
931
932
|
let gpSource = 'startPrice';
|
|
932
933
|
let amaSnapshot = null;
|
|
933
|
-
const whitelistFlags = getWhitelistFlags(manager.config.botKey);
|
|
934
|
+
const whitelistFlags = getWhitelistFlags(manager.config.botKey ?? '');
|
|
934
935
|
const isGridRangeScalingWhitelisted = whitelistFlags.asymmetricBounds === true;
|
|
935
936
|
let gridPriceOffsetPct = 0;
|
|
936
937
|
const gpRaw = manager.config.gridPrice;
|
|
@@ -943,7 +944,7 @@ export async function initializeGrid(manager) {
|
|
|
943
944
|
else if (gpMode === 'pool' || gpMode === 'book') {
|
|
944
945
|
try {
|
|
945
946
|
const { BitShares } = require('../bitshares_client');
|
|
946
|
-
const derived = await derivePriceWithPoolRef(BitShares, manager.config.assetA, manager.config.assetB, gpMode, manager.config.poolRef);
|
|
947
|
+
const derived = await derivePriceWithPoolRef(BitShares, manager.config.assetA ?? '', manager.config.assetB ?? '', gpMode, manager.config.poolRef);
|
|
947
948
|
if (derived) {
|
|
948
949
|
gp = Number(derived);
|
|
949
950
|
gpSource = gpMode;
|
|
@@ -958,8 +959,8 @@ export async function initializeGrid(manager) {
|
|
|
958
959
|
}
|
|
959
960
|
}
|
|
960
961
|
else if (/^ama(?:[1-4])?$/.test(gpMode || '')) {
|
|
961
|
-
amaSnapshot = loadAmaCenterSnapshot(manager.config.botKey);
|
|
962
|
-
const amaCenter = amaSnapshot?.gridCenterPrice ?? loadAmaCenterPrice(manager.config.botKey);
|
|
962
|
+
amaSnapshot = loadAmaCenterSnapshot(manager.config.botKey ?? '');
|
|
963
|
+
const amaCenter = Number(amaSnapshot?.gridCenterPrice ?? loadAmaCenterPrice(manager.config.botKey ?? ''));
|
|
963
964
|
if (Number.isFinite(amaCenter) && amaCenter > 0) {
|
|
964
965
|
gp = amaCenter;
|
|
965
966
|
gpSource = 'ama';
|
|
@@ -1123,7 +1124,7 @@ export async function initializeGrid(manager) {
|
|
|
1123
1124
|
// against the OLD generation (manager.orders is replaced below)
|
|
1124
1125
|
// with the same live anchors the runtime derivation uses, so the
|
|
1125
1126
|
// fold can never be driven by a reserve fill.
|
|
1126
|
-
const oldSlots = Array.from(manager.orders
|
|
1127
|
+
const oldSlots = Array.from(manager.orders.values());
|
|
1127
1128
|
const edgeAnchors = {
|
|
1128
1129
|
buy: resolveLiveReserveEdgeAnchorPrice(manager, 'buy'),
|
|
1129
1130
|
sell: resolveLiveReserveEdgeAnchorPrice(manager, 'sell')
|
|
@@ -1410,7 +1411,7 @@ export async function recalculateGrid(manager, opts) {
|
|
|
1410
1411
|
* Check for grid divergence and trigger update if threshold is met.
|
|
1411
1412
|
*
|
|
1412
1413
|
* @param {import('./types').OrderManager} manager - Manager instance with order state
|
|
1413
|
-
* @returns {
|
|
1414
|
+
* @returns {unknown}
|
|
1414
1415
|
*/
|
|
1415
1416
|
export function checkAndUpdateGridIfNeeded(manager) {
|
|
1416
1417
|
const rawThreshold = manager.config?.gridLimits?.GRID_REGENERATION_PERCENTAGE;
|
|
@@ -1647,9 +1648,7 @@ export async function _recalculateGridOrderSizesFromBlockchain(manager, orderTyp
|
|
|
1647
1648
|
newSize,
|
|
1648
1649
|
newPrice: slot.price,
|
|
1649
1650
|
order: {
|
|
1650
|
-
|
|
1651
|
-
type: slot.type,
|
|
1652
|
-
price: slot.price,
|
|
1651
|
+
...slot,
|
|
1653
1652
|
size: newSize
|
|
1654
1653
|
}
|
|
1655
1654
|
});
|
|
@@ -1692,7 +1691,6 @@ export async function updateGridFromBlockchainSnapshot(manager, orderType = 'bot
|
|
|
1692
1691
|
if (!fromBlockchainTimer && manager.config?.accountId) {
|
|
1693
1692
|
await manager.fetchAccountTotals(manager.config.accountId);
|
|
1694
1693
|
}
|
|
1695
|
-
const { WorkingGrid } = require('./working_grid');
|
|
1696
1694
|
const workingGrid = new WorkingGrid(manager.orders, { baseVersion: manager._gridVersion });
|
|
1697
1695
|
const allActions = [];
|
|
1698
1696
|
let hasWorkingChanges = false;
|
|
@@ -1715,7 +1713,7 @@ export async function updateGridFromBlockchainSnapshot(manager, orderType = 'bot
|
|
|
1715
1713
|
const allSlots = Array.from(workingGrid.values())
|
|
1716
1714
|
.filter((s) => s.price != null)
|
|
1717
1715
|
.sort((a, b) => a.price - b.price);
|
|
1718
|
-
const updatedSlots = assignGridRoles(allSlots,
|
|
1716
|
+
const updatedSlots = assignGridRoles(allSlots, overrideBoundaryIdx, gapSlots, ORDER_TYPES, ORDER_STATES, { assignOnChain: true });
|
|
1719
1717
|
for (const slot of updatedSlots) {
|
|
1720
1718
|
workingGrid.set(slot.id, slot);
|
|
1721
1719
|
}
|
|
@@ -1726,13 +1724,13 @@ export async function updateGridFromBlockchainSnapshot(manager, orderType = 'bot
|
|
|
1726
1724
|
// one is passed, so boundary-crossing slots are now correctly classified.
|
|
1727
1725
|
if (orderType === ORDER_TYPES.BUY || orderType === 'both') {
|
|
1728
1726
|
const buyResult = await _recalculateGridOrderSizesFromBlockchain(manager, ORDER_TYPES.BUY, { workingGrid });
|
|
1729
|
-
allActions.push(...buyResult
|
|
1730
|
-
hasWorkingChanges = hasWorkingChanges || buyResult
|
|
1727
|
+
allActions.push(...(buyResult?.actions ?? []));
|
|
1728
|
+
hasWorkingChanges = hasWorkingChanges || (buyResult?.changed ?? false);
|
|
1731
1729
|
}
|
|
1732
1730
|
if (orderType === ORDER_TYPES.SELL || orderType === 'both') {
|
|
1733
1731
|
const sellResult = await _recalculateGridOrderSizesFromBlockchain(manager, ORDER_TYPES.SELL, { workingGrid });
|
|
1734
|
-
allActions.push(...sellResult
|
|
1735
|
-
hasWorkingChanges = hasWorkingChanges || sellResult
|
|
1732
|
+
allActions.push(...(sellResult?.actions ?? []));
|
|
1733
|
+
hasWorkingChanges = hasWorkingChanges || (sellResult?.changed ?? false);
|
|
1736
1734
|
}
|
|
1737
1735
|
// Return COW result only if there are changes
|
|
1738
1736
|
if (allActions.length === 0 && !hasWorkingChanges) {
|
|
@@ -1911,7 +1909,6 @@ export async function monitorDivergence(manager, calculatedGrid, persistedGrid)
|
|
|
1911
1909
|
// 1. Check ratio-based divergence (available funds vs allocated)
|
|
1912
1910
|
const ratioResult = checkAndUpdateGridIfNeeded(manager);
|
|
1913
1911
|
if (ratioResult.buyUpdated || ratioResult.sellUpdated) {
|
|
1914
|
-
const { getOrderTypeFromUpdatedFlags } = require('./utils/order');
|
|
1915
1912
|
return {
|
|
1916
1913
|
needsUpdate: true,
|
|
1917
1914
|
buy: { updated: ratioResult.buyUpdated, ratio: ratioResult.buyUpdated, rms: false, metric: 0, shrink: ratioResult.buyShrink === true },
|
|
@@ -1923,7 +1920,6 @@ export async function monitorDivergence(manager, calculatedGrid, persistedGrid)
|
|
|
1923
1920
|
const rmsResult = await compareGrids(calculatedGrid, persistedGrid, manager);
|
|
1924
1921
|
const buyUpdated = ratioResult.buyUpdated || rmsResult.buy.updated;
|
|
1925
1922
|
const sellUpdated = ratioResult.sellUpdated || rmsResult.sell.updated;
|
|
1926
|
-
const { getOrderTypeFromUpdatedFlags } = require('./utils/order');
|
|
1927
1923
|
return {
|
|
1928
1924
|
needsUpdate: buyUpdated || sellUpdated,
|
|
1929
1925
|
buy: { updated: buyUpdated, ratio: ratioResult.buyUpdated, rms: rmsResult.buy.updated, metric: rmsResult.buy.metric, shrink: ratioResult.buyShrink === true },
|
|
@@ -1945,7 +1941,7 @@ function _getOnChainOrders(manager) {
|
|
|
1945
1941
|
// Without this, a live shelf masks an empty window side (oneSideEmpty
|
|
1946
1942
|
// stays false) and skews the spread inputs. No-op on grids that only
|
|
1947
1943
|
// mint slot-N ids.
|
|
1948
|
-
const isGridSlot = (o) => o?.orderId && Number(o?.size || 0) > 0 && parseSlotIndex(o?.id) !== null;
|
|
1944
|
+
const isGridSlot = (o) => !!(o?.orderId && Number(o?.size || 0) > 0 && parseSlotIndex(o?.id) !== null);
|
|
1949
1945
|
const onChainBuys = [
|
|
1950
1946
|
...manager.getOrdersByTypeAndState(ORDER_TYPES.BUY, ORDER_STATES.ACTIVE),
|
|
1951
1947
|
...manager.getOrdersByTypeAndState(ORDER_TYPES.BUY, ORDER_STATES.PARTIAL)
|
|
@@ -2071,7 +2067,7 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2071
2067
|
}
|
|
2072
2068
|
}
|
|
2073
2069
|
// Limit spread = nominal + half increment tolerance (0.5 steps).
|
|
2074
|
-
const limitSpread = nominalSpread + (manager.config.incrementPercent * toleranceSteps);
|
|
2070
|
+
const limitSpread = nominalSpread + ((manager.config.incrementPercent ?? 0) * toleranceSteps);
|
|
2075
2071
|
// One-sided book: currentSpread is Infinity (no opposing quote), so
|
|
2076
2072
|
// log the empty side instead of a bogus "0% > limit" comparison.
|
|
2077
2073
|
const spreadDesc = oneSideEmpty
|
|
@@ -2107,12 +2103,20 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2107
2103
|
const oppositeCorrection = await prepareSpreadCorrectionOrders(manager, oppositeSide, manager.outOfSpread);
|
|
2108
2104
|
if (oppositeCorrection) {
|
|
2109
2105
|
correction = oppositeCorrection;
|
|
2110
|
-
placeCount =
|
|
2111
|
-
updateCount =
|
|
2106
|
+
placeCount = oppositeCorrection.ordersToPlace?.length || 0;
|
|
2107
|
+
updateCount = oppositeCorrection.ordersToUpdate?.length || 0;
|
|
2112
2108
|
}
|
|
2113
2109
|
}
|
|
2114
2110
|
// Capture fund snapshot under lock for pre-flight verification before broadcast
|
|
2115
2111
|
fundSnapshot = _snapshotFundState(manager);
|
|
2112
|
+
// No executable correction on EITHER side: the balances/holds may be a
|
|
2113
|
+
// stale snapshot (the grid does not lose funds, it holds them in
|
|
2114
|
+
// resting/virtual slots), so ask the caller to refresh account totals +
|
|
2115
|
+
// open orders instead of re-deriving the identical starved plan next
|
|
2116
|
+
// tick. Previously only the "no side at all" case set this flag, so a
|
|
2117
|
+
// fund-constrained plan on a chosen side never triggered a refresh.
|
|
2118
|
+
if ((placeCount + updateCount) === 0)
|
|
2119
|
+
fundsExhausted = true;
|
|
2116
2120
|
return (placeCount + updateCount) > 0;
|
|
2117
2121
|
};
|
|
2118
2122
|
try {
|
|
@@ -2134,11 +2138,13 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2134
2138
|
// The lock is only needed for fund verification; order placement doesn't need it.
|
|
2135
2139
|
// Pre-flight fund verification mitigates TOCTOU between lock release and broadcast.
|
|
2136
2140
|
if (shouldApplyCorrection && updateOrdersOnChainBatch && correction && fundSnapshot) {
|
|
2141
|
+
let activeCorrection = correction;
|
|
2142
|
+
let activeSnapshot = fundSnapshot;
|
|
2137
2143
|
const currentFunds = _snapshotFundState(manager);
|
|
2138
|
-
const fundChanged =
|
|
2139
|
-
||
|
|
2140
|
-
||
|
|
2141
|
-
||
|
|
2144
|
+
const fundChanged = activeSnapshot.buyFree !== currentFunds.buyFree
|
|
2145
|
+
|| activeSnapshot.sellFree !== currentFunds.sellFree
|
|
2146
|
+
|| activeSnapshot.buyLocked !== currentFunds.buyLocked
|
|
2147
|
+
|| activeSnapshot.sellLocked !== currentFunds.sellLocked;
|
|
2142
2148
|
if (fundChanged) {
|
|
2143
2149
|
// TOCTOU: fund state changed between lock release and broadcast.
|
|
2144
2150
|
// Lock-free re-plan — no _gridLock needed because the fund read
|
|
@@ -2164,11 +2170,10 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2164
2170
|
}
|
|
2165
2171
|
const rePlanCorrection = await prepareSpreadCorrectionOrders(manager, rePlanDecision.side, manager.outOfSpread);
|
|
2166
2172
|
if (rePlanCorrection && ((rePlanCorrection.ordersToPlace?.length || 0) + (rePlanCorrection.ordersToUpdate?.length || 0) > 0)) {
|
|
2167
|
-
|
|
2168
|
-
|
|
2173
|
+
activeCorrection = rePlanCorrection;
|
|
2174
|
+
activeSnapshot = currentFunds;
|
|
2169
2175
|
manager.logger?.log?.(`[SPREAD] Fund state changed between lock release and broadcast — ` +
|
|
2170
|
-
`re-planned with updated funds: ${
|
|
2171
|
-
`${correction.ordersToUpdate?.length || 0} updates`, 'info');
|
|
2176
|
+
`re-planned with updated funds: ${activeCorrection.ordersToPlace?.length || 0} creates`, 'info');
|
|
2172
2177
|
}
|
|
2173
2178
|
else {
|
|
2174
2179
|
manager.logger?.log?.(`[SPREAD] Fund state changed; re-plan produced no viable orders. Skipping cycle.`, 'warn');
|
|
@@ -2176,19 +2181,22 @@ export async function checkSpreadCondition(manager, _BitShares, updateOrdersOnCh
|
|
|
2176
2181
|
}
|
|
2177
2182
|
}
|
|
2178
2183
|
try {
|
|
2179
|
-
const batchResult = await updateOrdersOnChainBatch(
|
|
2184
|
+
const batchResult = await updateOrdersOnChainBatch(activeCorrection);
|
|
2180
2185
|
if (!batchResult || batchResult.executed !== true) {
|
|
2181
2186
|
manager.logger?.log?.(`Spread correction batch was prepared but not executed. Keeping local state unchanged.`, 'warn');
|
|
2182
|
-
|
|
2187
|
+
// Nothing landed: ask the caller to refresh account totals +
|
|
2188
|
+
// open orders (stale holds/balances can make the same plan
|
|
2189
|
+
// re-derive every cycle).
|
|
2190
|
+
return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted: true };
|
|
2183
2191
|
}
|
|
2184
2192
|
await manager.recalculateFunds();
|
|
2185
|
-
const placed =
|
|
2186
|
-
const updated =
|
|
2193
|
+
const placed = activeCorrection.ordersToPlace?.length || 0;
|
|
2194
|
+
const updated = activeCorrection.ordersToUpdate?.length || 0;
|
|
2187
2195
|
return { ordersPlaced: placed + updated, partialsMoved: updated };
|
|
2188
2196
|
}
|
|
2189
2197
|
catch (err) {
|
|
2190
2198
|
manager.logger?.log?.(`Error applying spread correction on-chain: ${getErrorMessage(err)}`, 'warn');
|
|
2191
|
-
return { ordersPlaced: 0, partialsMoved: 0 };
|
|
2199
|
+
return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted: true };
|
|
2192
2200
|
}
|
|
2193
2201
|
}
|
|
2194
2202
|
return { ordersPlaced: 0, partialsMoved: 0, fundsExhausted };
|
|
@@ -2245,10 +2253,10 @@ export async function checkWindowDust(manager) {
|
|
|
2245
2253
|
if (!manager)
|
|
2246
2254
|
return { buyDust: false, sellDust: false, buyDustOrders: [], sellDustOrders: [] };
|
|
2247
2255
|
const allOrders = Array.from(manager.orders.values());
|
|
2248
|
-
const isLiveOrder = (order) => order &&
|
|
2256
|
+
const isLiveOrder = (order) => !!(order &&
|
|
2249
2257
|
order.orderId &&
|
|
2250
2258
|
order.price != null &&
|
|
2251
|
-
(order.state === ORDER_STATES.ACTIVE || order.state === ORDER_STATES.PARTIAL);
|
|
2259
|
+
(order.state === ORDER_STATES.ACTIVE || order.state === ORDER_STATES.PARTIAL));
|
|
2252
2260
|
// Identify top-of-window orders (closest to market per side).
|
|
2253
2261
|
const topBuyOrder = allOrders
|
|
2254
2262
|
.filter((o) => o.type === ORDER_TYPES.BUY && isLiveOrder(o))
|
|
@@ -2277,8 +2285,8 @@ export async function checkWindowDust(manager) {
|
|
|
2277
2285
|
};
|
|
2278
2286
|
const assets = manager.assets;
|
|
2279
2287
|
const allPartials = allOrders.filter((o) => isLiveOrder(o) && o.state === ORDER_STATES.PARTIAL);
|
|
2280
|
-
const isTopBuy = (o) => topBuyOrder && o.id === topBuyOrder.id;
|
|
2281
|
-
const isTopSell = (o) => topSellOrder && o.id === topSellOrder.id;
|
|
2288
|
+
const isTopBuy = (o) => !!(topBuyOrder && o.id === topBuyOrder.id);
|
|
2289
|
+
const isTopSell = (o) => !!(topSellOrder && o.id === topSellOrder.id);
|
|
2282
2290
|
// Compute per-slot dust thresholds once per side so the eligibility
|
|
2283
2291
|
// filter below and _getDustOrders share the same sizing context
|
|
2284
2292
|
// (avoids a duplicate recalculateFunds round per side). Each side's map
|
|
@@ -2334,7 +2342,7 @@ async function _computeDustThresholdMap(manager, type) {
|
|
|
2334
2342
|
.filter((o) => o.type === type)
|
|
2335
2343
|
.sort((a, b) => a.price - b.price);
|
|
2336
2344
|
const idealSizes = ctx && ctx.budget > 0
|
|
2337
|
-
? allocateFundsByWeights(ctx.budget, sideSlots.length, manager.config.weightDistribution[side], manager.config.incrementPercent / 100, type === ORDER_TYPES.BUY, 0, ctx.precision)
|
|
2345
|
+
? allocateFundsByWeights(ctx.budget, sideSlots.length, (manager.config.weightDistribution ?? {})[side], (manager.config.incrementPercent ?? 0) / 100, type === ORDER_TYPES.BUY, 0, ctx.precision)
|
|
2338
2346
|
: [];
|
|
2339
2347
|
const map = new Map();
|
|
2340
2348
|
sideSlots.forEach((s, idx) => {
|
|
@@ -2540,7 +2548,6 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2540
2548
|
throw new Error(`Invalid preferredSide: ${preferredSide}. Must be '${ORDER_TYPES.BUY}' or '${ORDER_TYPES.SELL}'.`);
|
|
2541
2549
|
}
|
|
2542
2550
|
const ordersToPlace = [];
|
|
2543
|
-
const ordersToUpdate = [];
|
|
2544
2551
|
const railType = preferredSide;
|
|
2545
2552
|
const sideName = railType === ORDER_TYPES.BUY ? 'buy' : 'sell';
|
|
2546
2553
|
const configuredMissingSlots = Number(outOfSpread || 0);
|
|
@@ -2596,38 +2603,45 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2596
2603
|
return ORDER_TYPES.SELL;
|
|
2597
2604
|
return ORDER_TYPES.SPREAD;
|
|
2598
2605
|
};
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
if (partials.length > 0) {
|
|
2605
|
-
edgePartial = partials[0];
|
|
2606
|
-
manager.logger?.log?.(`[SPREAD-CORRECTION] Identified partial order at ${edgePartial.price} for update`, 'debug');
|
|
2607
|
-
}
|
|
2606
|
+
// NOTE: rail partials are deliberately NOT correction targets. A
|
|
2607
|
+
// top-up cannot change bestBuy/bestSell (spread is price-based) and is
|
|
2608
|
+
// forbidden in place by clampPostFillUpdateSize, so the old
|
|
2609
|
+
// edge-partial update was always a no-op that starved the creates.
|
|
2610
|
+
// Spread repair is create-only; the sizing/rotation paths own partials.
|
|
2608
2611
|
// Primary candidates: SPREAD-type slots adjacent to the gap. Filter by
|
|
2609
2612
|
// boundary-correct type so a SPREAD slot that, after a boundary shift, now sits
|
|
2610
2613
|
// in the BUY or SELL zone is excluded — it would otherwise be placed on the
|
|
2611
2614
|
// correction side at a price the grid already considers the opposite side.
|
|
2612
2615
|
//
|
|
2613
|
-
// Candidate ordering:
|
|
2614
|
-
//
|
|
2615
|
-
//
|
|
2616
|
-
//
|
|
2617
|
-
//
|
|
2618
|
-
//
|
|
2619
|
-
//
|
|
2620
|
-
//
|
|
2621
|
-
// market-nearest slot is by definition the best one to create).
|
|
2616
|
+
// Candidate ordering: WINDOW-CONTIGUOUS FIRST. The SPREAD-TIGHTENING
|
|
2617
|
+
// GUARD below keeps only candidates on the market side of the live
|
|
2618
|
+
// window; among those the correction must EXTEND the window, i.e. pick
|
|
2619
|
+
// the slot closest to the live edge (highest SELL / lowest BUY). Picking
|
|
2620
|
+
// the far end instead leaves an interior hole between the new order and
|
|
2621
|
+
// the live window and over-tightens past the target spread. With no live
|
|
2622
|
+
// order (fully-empty rail) there is no anchor, so fall back to
|
|
2623
|
+
// market-nearest (lowest SELL / highest BUY) — the best available level.
|
|
2622
2624
|
//
|
|
2623
|
-
//
|
|
2624
|
-
//
|
|
2625
|
-
// rail with a live window sorted DESCENDING and picked the grid
|
|
2625
|
+
// The previous two-branch comparator (windowFirst vs edgeFirst, exact
|
|
2626
|
+
// OPPOSITES) sorted a windowed SELL rail DESCENDING and picked the grid
|
|
2626
2627
|
// ceiling: an order ~50% above bestSell that cannot tighten the spread
|
|
2627
|
-
//
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2628
|
+
// and is cancelled as surplus on the next resync. The single
|
|
2629
|
+
// market-nearest comparator that replaced it fixed that case but sorts
|
|
2630
|
+
// the FAR end first when the empties sit BELOW the window (the normal
|
|
2631
|
+
// post-fill state), which is the same class of bug mirrored.
|
|
2632
|
+
const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
|
|
2633
|
+
const railBestIsMax = railType === ORDER_TYPES.BUY;
|
|
2634
|
+
const bestLiveOnRail = railBestIsMax
|
|
2635
|
+
? (onChainBuys.length ? Math.max(...onChainBuys.map((o) => o.price)) : null)
|
|
2636
|
+
: (onChainSells.length ? Math.min(...onChainSells.map((o) => o.price)) : null);
|
|
2637
|
+
const sortCandidates = (a, b) => {
|
|
2638
|
+
if (bestLiveOnRail != null && a?.price != null && b?.price != null) {
|
|
2639
|
+
// Callers have already applied tightensSpread, so both prices
|
|
2640
|
+
// are on the same side of the anchor and distance is monotone.
|
|
2641
|
+
return Math.abs(a.price - bestLiveOnRail) - Math.abs(b.price - bestLiveOnRail);
|
|
2642
|
+
}
|
|
2643
|
+
return railBestIsMax ? b.price - a.price : a.price - b.price;
|
|
2644
|
+
};
|
|
2631
2645
|
// SPREAD-TIGHTENING GUARD: on a rail that already has a live order, only
|
|
2632
2646
|
// a candidate that IMPROVES that rail's best price is a spread repair at
|
|
2633
2647
|
// all. A SELL must land below the lowest live sell, a BUY above the
|
|
@@ -2662,11 +2676,6 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2662
2676
|
// With no live order on the side there is no reference to improve, so
|
|
2663
2677
|
// the market-nearest slot is by definition the best available and the
|
|
2664
2678
|
// guard stays open.
|
|
2665
|
-
const { onChainBuys, onChainSells } = _getOnChainOrders(manager);
|
|
2666
|
-
const railBestIsMax = railType === ORDER_TYPES.BUY;
|
|
2667
|
-
const bestLiveOnRail = railBestIsMax
|
|
2668
|
-
? (onChainBuys.length ? Math.max(...onChainBuys.map((o) => o.price)) : null)
|
|
2669
|
-
: (onChainSells.length ? Math.min(...onChainSells.map((o) => o.price)) : null);
|
|
2670
2679
|
const tightensSpread = (c) => {
|
|
2671
2680
|
if (bestLiveOnRail == null || c?.price == null)
|
|
2672
2681
|
return true;
|
|
@@ -2837,9 +2846,9 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2837
2846
|
if (spreadCandidates.length > 0) {
|
|
2838
2847
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Identified ${spreadCandidates.length}/${missingSlots} slot(s) for activation on ${sideName} (orphaned=${orphanedVirtualCandidates.length}, spread=${spreadCandidates.length - orphanedVirtualCandidates.length})`, 'debug');
|
|
2839
2848
|
}
|
|
2840
|
-
if (
|
|
2849
|
+
if (spreadCandidates.length === 0) {
|
|
2841
2850
|
manager.logger?.log?.(bestLiveOnRail == null
|
|
2842
|
-
? `[SPREAD-CORRECTION] No
|
|
2851
|
+
? `[SPREAD-CORRECTION] No orphaned virtual slots or spread slots found. Skipping.`
|
|
2843
2852
|
: `[SPREAD-CORRECTION] No spread-tightening slot on ${sideName} (best live ${bestLiveOnRail}); every remaining empty slot sits beyond the live window and cannot narrow the spread. Skipping.`, 'warn');
|
|
2844
2853
|
return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
|
|
2845
2854
|
}
|
|
@@ -2856,44 +2865,38 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2856
2865
|
return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
|
|
2857
2866
|
}
|
|
2858
2867
|
const precisionEpsilon = getPrecisionSlack(ctx.precision, 1);
|
|
2859
|
-
const idealSizes = allocateFundsByWeights(ctx.budget, syntheticSideSlots.length, manager.config.weightDistribution[sideName], manager.config.incrementPercent / 100, railType === ORDER_TYPES.BUY, 0, ctx.precision);
|
|
2868
|
+
const idealSizes = allocateFundsByWeights(ctx.budget, syntheticSideSlots.length, (manager.config.weightDistribution ?? {})[sideName], (manager.config.incrementPercent ?? 0) / 100, railType === ORDER_TYPES.BUY, 0, ctx.precision);
|
|
2860
2869
|
const idealById = new Map();
|
|
2861
2870
|
syntheticSideSlots.forEach((slot, idx) => {
|
|
2862
2871
|
idealById.set(slot.id, Number(idealSizes[idx] || 0));
|
|
2863
2872
|
});
|
|
2864
2873
|
const availableFund = Math.max(0, Math.min(Number(manager.funds?.available?.[sideName] || 0), Number(sideName === 'buy' ? manager.accountTotals?.buyFree : manager.accountTotals?.sellFree) || 0));
|
|
2865
|
-
// PURE FUND-DRIVEN: corrections are funded exclusively by
|
|
2866
|
-
// available
|
|
2874
|
+
// PURE FUND-DRIVEN: corrections are funded exclusively by
|
|
2875
|
+
// funds.available[side] and the cached accountTotals[side]Free read.
|
|
2876
|
+
// No resting order is ever shrunk to manufacture
|
|
2867
2877
|
// budget (the previous self-funded/redistribution paths moved
|
|
2868
2878
|
// inventory within a rail and were gamed by stale-size snapshots).
|
|
2869
|
-
// When free funds cannot cover every
|
|
2870
|
-
//
|
|
2871
|
-
//
|
|
2872
|
-
//
|
|
2873
|
-
// resting orders).
|
|
2879
|
+
// When free funds cannot cover every candidate, the loop below places
|
|
2880
|
+
// what they allow and stops; the caller refreshes account totals + open
|
|
2881
|
+
// orders to find out whether the shortfall was a stale accounting read
|
|
2882
|
+
// (the grid does not lose funds, it holds them in resting orders).
|
|
2874
2883
|
const prioritizedTargets = [];
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
needed: Math.max(0, ideal - current)
|
|
2885
|
-
});
|
|
2886
|
-
}
|
|
2887
|
-
}
|
|
2884
|
+
// Spread repair works by adding PRICE LEVELS, never by deepening an
|
|
2885
|
+
// existing one: a top-up grows an order at its current price and so
|
|
2886
|
+
// cannot move bestBuy/bestSell, and it is un-executable in place
|
|
2887
|
+
// (a PARTIAL slot may not be grown by a COW update —
|
|
2888
|
+
// clampPostFillUpdateSize). The old edge-partial top-up always clamped
|
|
2889
|
+
// to a no-op yet ran FIRST and consumed the whole budget, leaving the
|
|
2890
|
+
// creates unfunded ("planned N, placing 0") and the batch empty
|
|
2891
|
+
// ("prepared but not executed"). Fund creates only, still from
|
|
2892
|
+
// available free funds alone.
|
|
2888
2893
|
for (const slot of spreadCandidates) {
|
|
2889
2894
|
const ideal = Number(idealById.get(slot.id) || 0);
|
|
2890
2895
|
if (ideal > precisionEpsilon) {
|
|
2891
2896
|
prioritizedTargets.push({
|
|
2892
2897
|
kind: 'create',
|
|
2893
2898
|
order: slot,
|
|
2894
|
-
|
|
2895
|
-
ideal,
|
|
2896
|
-
needed: ideal
|
|
2899
|
+
ideal
|
|
2897
2900
|
});
|
|
2898
2901
|
}
|
|
2899
2902
|
}
|
|
@@ -2901,18 +2904,41 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2901
2904
|
return { ordersToPlace: [], ordersToUpdate: [], origin: 'spread-correction' };
|
|
2902
2905
|
}
|
|
2903
2906
|
let remainingBudget = availableFund;
|
|
2907
|
+
// FUNDING PROBE (diagnostic): one line per correction cycle showing the
|
|
2908
|
+
// quantities that decide whether candidates can be funded. availableFund
|
|
2909
|
+
// is min(funds.available[side], accountTotals[side]Free); when the
|
|
2910
|
+
// virtual rail has already reserved the free balance this reads ~0 even
|
|
2911
|
+
// though the side still holds inventory — the state that makes the loop
|
|
2912
|
+
// below place fewer orders than the plan's candidates.
|
|
2913
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Funding probe side=${sideName}: ` +
|
|
2914
|
+
`availableFund=${Format.formatAmount8(availableFund)} ` +
|
|
2915
|
+
`budget=${Format.formatAmount8(Number(ctx.budget || 0))} ` +
|
|
2916
|
+
`virtual=${Format.formatAmount8(Number(sideName === 'buy' ? manager.funds?.virtual?.buy : manager.funds?.virtual?.sell) || 0)} ` +
|
|
2917
|
+
`free=${Format.formatAmount8(Number(sideName === 'buy' ? manager.accountTotals?.buyFree : manager.accountTotals?.sellFree) || 0)} ` +
|
|
2918
|
+
`virtualSell=${Format.formatAmount8(Number(manager.funds?.virtual?.sell || 0))} ` +
|
|
2919
|
+
`sellFree=${Format.formatAmount8(Number(manager.accountTotals?.sellFree || 0))} ` +
|
|
2920
|
+
`candidates=${prioritizedTargets.length} ` +
|
|
2921
|
+
`ideals=[${prioritizedTargets.map((t) => `${t.order.id}:${Format.formatAmount8(Number(t.ideal || 0))}`).join(', ')}]`, 'debug');
|
|
2922
|
+
// A truncated create (ideal >> residual) may fail isOrderHealthy's
|
|
2923
|
+
// dust/minimum check against its OWN ideal; that candidate is skipped
|
|
2924
|
+
// (continue) and the next one is tried with the SAME residual, so a
|
|
2925
|
+
// small budget can still fund a smaller candidate. When every candidate
|
|
2926
|
+
// is too truncated the residual is intentionally left UNSPENT rather
|
|
2927
|
+
// than force-placed as dust — the refresh above is what distinguishes
|
|
2928
|
+
// "genuinely no room" from "stale accounting read".
|
|
2904
2929
|
for (const target of prioritizedTargets) {
|
|
2930
|
+
// FUNDING PROBE (per candidate): remainingBudget is read BEFORE this
|
|
2931
|
+
// target is applied, so a "placing 0" cycle can be attributed to the
|
|
2932
|
+
// residual gate rather than to isOrderHealthy/dust rejection.
|
|
2933
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Funding probe ${target.kind} ${target.order.id}: ` +
|
|
2934
|
+
`ideal=${Format.formatAmount8(Number(target.ideal || 0))} ` +
|
|
2935
|
+
`remainingBudget=${Format.formatAmount8(remainingBudget)} ` +
|
|
2936
|
+
`availableFund=${Format.formatAmount8(availableFund)} ` +
|
|
2937
|
+
`budget=${Format.formatAmount8(Number(ctx.budget || 0))} ` +
|
|
2938
|
+
`virtualSell=${Format.formatAmount8(Number(manager.funds?.virtual?.sell || 0))} ` +
|
|
2939
|
+
`sellFree=${Format.formatAmount8(Number(manager.accountTotals?.sellFree || 0))}`, 'debug');
|
|
2905
2940
|
if (remainingBudget <= precisionEpsilon)
|
|
2906
2941
|
break;
|
|
2907
|
-
if (target.kind === 'partial-topup') {
|
|
2908
|
-
const topUp = Math.min(target.needed, remainingBudget);
|
|
2909
|
-
const newSize = target.current + topUp;
|
|
2910
|
-
if (newSize > target.current + precisionEpsilon && isOrderHealthy(newSize, railType, manager.assets, target.ideal)) {
|
|
2911
|
-
ordersToUpdate.push({ partialOrder: { ...target.order }, newSize });
|
|
2912
|
-
remainingBudget -= topUp;
|
|
2913
|
-
}
|
|
2914
|
-
continue;
|
|
2915
|
-
}
|
|
2916
2942
|
const createSize = Math.min(target.ideal, remainingBudget);
|
|
2917
2943
|
if (createSize <= precisionEpsilon)
|
|
2918
2944
|
continue;
|
|
@@ -2978,16 +3004,15 @@ export async function prepareSpreadCorrectionOrders(manager, preferredSide, outO
|
|
|
2978
3004
|
boundaryIdx = undefined;
|
|
2979
3005
|
}
|
|
2980
3006
|
}
|
|
2981
|
-
const combinedUpdates = [...ordersToUpdate];
|
|
2982
3007
|
if (spreadCandidates.length < missingSlots) {
|
|
2983
3008
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Requested ${missingSlots} extra slot(s), found ${spreadCandidates.length} available slot(s) on ${sideName}`, 'warn');
|
|
2984
3009
|
}
|
|
2985
3010
|
if (ordersToPlace.length < spreadCandidates.length) {
|
|
2986
3011
|
manager.logger?.log?.(`[SPREAD-CORRECTION] Fund-constrained placement on ${sideName}: planned ${spreadCandidates.length}, placing ${ordersToPlace.length}`, 'info');
|
|
2987
3012
|
}
|
|
2988
|
-
if (
|
|
2989
|
-
manager.logger?.log?.(`[SPREAD-CORRECTION] Prepared
|
|
3013
|
+
if (ordersToPlace.length > 0) {
|
|
3014
|
+
manager.logger?.log?.(`[SPREAD-CORRECTION] Prepared creates=${ordersToPlace.length}, remainingBudget=${Format.formatSizeByOrderType(Math.max(0, remainingBudget), railType, manager.assets)}`, 'debug');
|
|
2990
3015
|
}
|
|
2991
|
-
return { ordersToPlace, ordersToUpdate:
|
|
3016
|
+
return { ordersToPlace, ordersToUpdate: [], ...(boundaryIdx === undefined ? {} : { boundaryIdx }), origin: 'spread-correction' };
|
|
2992
3017
|
}
|
|
2993
3018
|
//# sourceMappingURL=grid.js.map
|