dexbot 1.6.11 → 1.6.13
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 +67 -4
- package/README.md +2 -1
- package/analysis/README.md +11 -11
- package/analysis/ama_fitting/README.md +5 -3
- package/analysis/tradingview/README.md +1 -1
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +3 -3
- package/claw/README.md +1 -0
- package/claw/docs/AI_BOT_LIBRARY_API.md +2 -0
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
- package/claw/modules/chain_broadcast.ts +7 -1
- package/claw/modules/claw_bridge.ts +0 -3
- package/claw/modules/claw_launcher.ts +1 -1
- package/claw/modules/claw_skill_md.ts +1 -0
- package/claw/modules/launcher_mode_detector.ts +9 -2
- package/claw/package.json +3 -3
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/claw/tsconfig.json +2 -2
- 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 +3 -21
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +55 -45
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +1 -8
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +45 -24
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +34 -78
- package/dist/analysis/analyze_args.d.ts +43 -0
- package/dist/analysis/analyze_args.js +61 -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 +221 -28
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +23 -103
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +32 -150
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +19 -34
- package/dist/analysis/bot_fitting/shared_utils.d.ts +77 -9
- package/dist/analysis/bot_fitting/shared_utils.js +125 -9
- 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 +35 -3
- package/dist/analysis/chart_ui.js +43 -4
- package/dist/analysis/chart_utils.d.ts +5 -5
- package/dist/analysis/chart_utils.js +9 -0
- package/dist/analysis/fills_cache.d.ts +4 -24
- package/dist/analysis/fills_cache.js +3 -84
- package/dist/analysis/fills_source.d.ts +33 -3
- package/dist/analysis/fills_source.js +83 -13
- package/dist/analysis/grid_correction_check.d.ts +2 -24
- package/dist/analysis/grid_correction_check.js +27 -69
- package/dist/analysis/math_utils.d.ts +91 -6
- package/dist/analysis/math_utils.js +119 -7
- package/dist/analysis/pnl_report.js +29 -29
- package/dist/analysis/price_sources.d.ts +30 -9
- package/dist/analysis/price_sources.js +28 -4
- package/dist/analysis/resolve_bot_accounts.js +2 -2
- package/dist/analysis/resolve_source.d.ts +1 -1
- package/dist/analysis/resolve_source.js +31 -10
- package/dist/analysis/trade_profitability.d.ts +29 -2
- package/dist/analysis/trade_profitability.js +73 -147
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +3 -8
- package/dist/analysis/tradingview/analyze_tradingview.js +7 -6
- 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 +20 -34
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +1 -101
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +26 -84
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +16 -41
- 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/analysis/trend_detection/volatility_chart_generator.js +9 -10
- package/dist/analysis/worker_pool.d.ts +38 -0
- package/dist/analysis/worker_pool.js +67 -0
- package/dist/credential-daemon.js +34 -20
- package/dist/dexbot.js +78 -59
- package/dist/market_adapter/ama_signal_runner.js +21 -54
- package/dist/market_adapter/candle_utils.d.ts +29 -19
- package/dist/market_adapter/candle_utils.js +35 -21
- package/dist/market_adapter/cli_args.d.ts +22 -0
- package/dist/market_adapter/cli_args.js +30 -0
- 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/config_normalizers.js +11 -6
- package/dist/market_adapter/core/kibana_candles.d.ts +56 -19
- package/dist/market_adapter/core/kibana_candles.js +12 -9
- 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 +320 -153
- package/dist/market_adapter/core/market_adapter_service.js +228 -269
- package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +1 -6
- package/dist/market_adapter/core/signals/hurst_analyzer.js +1 -1
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +1 -11
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +1 -1
- 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 -2
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +160 -332
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +50 -8
- package/dist/market_adapter/inputs/fetch_lp_data.js +47 -22
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
- package/dist/market_adapter/inputs/kibana_feed_source.js +26 -41
- 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 +93 -156
- package/dist/market_adapter/inputs/window_cache.js +59 -184
- package/dist/market_adapter/interval_utils.d.ts +15 -5
- package/dist/market_adapter/interval_utils.js +16 -1
- 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 +10 -7
- package/dist/market_adapter/lp_chart_runner.js +37 -19
- 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 +94 -120
- 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 +49 -2
- package/dist/market_adapter/utils/data_discovery.js +220 -27
- 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/month_shards.d.ts +84 -0
- package/dist/market_adapter/utils/month_shards.js +237 -0
- 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 +578 -21
- package/dist/modules/account_bots.js +272 -267
- package/dist/modules/account_orders.d.ts +79 -30
- package/dist/modules/account_orders.js +60 -64
- 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 +39 -4
- package/dist/modules/bitshares-native/chain_client.js +59 -59
- 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/resolvers.js +22 -25
- 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 +73 -108
- 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 +8 -16
- 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 +4 -3
- 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 +94 -60
- package/dist/modules/chain_orders.js +81 -118
- package/dist/modules/cli_start_onboarding.d.ts +2 -1
- package/dist/modules/constants.d.ts +534 -32
- package/dist/modules/constants.js +35 -48
- package/dist/modules/cr_planner.d.ts +41 -3
- package/dist/modules/cr_planner.js +1 -5
- 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 +43 -6
- package/dist/modules/credit_pricing.js +70 -60
- package/dist/modules/credit_runtime.d.ts +283 -118
- package/dist/modules/credit_runtime.js +500 -231
- 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/daemon_node_health.d.ts +4 -3
- package/dist/modules/dexbot_class.d.ts +213 -146
- package/dist/modules/dexbot_class.js +183 -86
- package/dist/modules/dexbot_cow_runtime.d.ts +160 -87
- package/dist/modules/dexbot_cow_runtime.js +302 -234
- package/dist/modules/dexbot_credential_client.d.ts +19 -18
- package/dist/modules/dexbot_credential_client.js +1 -2
- package/dist/modules/dexbot_fill_runtime.d.ts +63 -49
- package/dist/modules/dexbot_fill_runtime.js +53 -47
- package/dist/modules/dexbot_maintenance_runtime.d.ts +127 -71
- package/dist/modules/dexbot_maintenance_runtime.js +187 -147
- package/dist/modules/dexbot_startup_runtime.d.ts +11 -11
- package/dist/modules/dexbot_startup_runtime.js +56 -57
- 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 +19 -13
- 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 -7
- 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/lazy_shim.d.ts +11 -0
- package/dist/modules/lazy_shim.js +16 -0
- package/dist/modules/market_adapter_whitelist.d.ts +9 -3
- package/dist/modules/market_adapter_whitelist.js +15 -3
- package/dist/modules/node_connect_policy.d.ts +3 -2
- package/dist/modules/node_failure_ledger.d.ts +6 -5
- 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 +16 -7
- package/dist/modules/order/format.js +15 -3
- package/dist/modules/order/genesis_policy.d.ts +24 -21
- package/dist/modules/order/genesis_policy.js +17 -10
- package/dist/modules/order/grid.d.ts +144 -36
- package/dist/modules/order/grid.js +226 -145
- 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 +264 -1
- package/dist/modules/order/logger.d.ts +46 -19
- package/dist/modules/order/logger.js +38 -49
- package/dist/modules/order/logger_state.d.ts +4 -4
- package/dist/modules/order/manager.d.ts +232 -191
- package/dist/modules/order/manager.js +110 -130
- 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 +153 -126
- package/dist/modules/order/utils/slot.d.ts +1 -1
- package/dist/modules/order/utils/system.d.ts +156 -26
- package/dist/modules/order/utils/system.js +103 -71
- package/dist/modules/order/utils/validate.d.ts +89 -41
- package/dist/modules/order/utils/validate.js +26 -24
- package/dist/modules/order/utils/withPoolRef.d.ts +6 -4
- 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 +33 -61
- 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 +14 -11
- 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 +9 -5
- 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 +1090 -6
- 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 +24 -4
- 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 +23 -11
- package/dist/modules/version_notice.js +6 -4
- package/dist/pm2.d.ts +28 -27
- package/dist/pm2.js +61 -40
- package/dist/scripts/analyze-credit.d.ts +2 -1
- package/dist/scripts/analyze-credit.js +23 -24
- package/dist/scripts/analyze-git.js +2 -15
- 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 +15 -13
- package/dist/scripts/check_any.d.ts +22 -0
- package/dist/scripts/check_any.js +158 -0
- package/dist/scripts/diagnose-pool-history.js +13 -13
- package/dist/scripts/print_grid.js +0 -1
- package/dist/scripts/run-tests.js +39 -8
- package/dist/scripts/runner.js +1 -1
- package/dist/scripts/sync-version.js +0 -10
- 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 +10 -12
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +2 -2
- package/docs/COW_INVARIANTS.md +13 -6
- package/docs/DEXBOT_COMPARISON.md +8 -8
- package/docs/EVOLUTION.md +10 -8
- 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/WORKFLOW.md +1 -0
- package/docs/architecture.md +31 -19
- package/docs/developer_guide.md +6 -6
- package/market_adapter/README.md +12 -5
- package/modules/README.md +4 -1
- package/package.json +9 -9
- package/scripts/README.md +43 -38
- package/tests/README.md +25 -10
- package/dist/scripts/diagnose-kibana-candles.d.ts +0 -3
- package/dist/scripts/diagnose-kibana-candles.js +0 -82
- package/scripts/git-viewer.sh +0 -489
- package/scripts/postinstall.js +0 -16
|
@@ -48,8 +48,9 @@ function convertSlopePercentToPerBar(value, lookbackBars, mode) {
|
|
|
48
48
|
function normalizePersistedAmaSlopeSnapshot(snapshot, lookbackBars, mode) {
|
|
49
49
|
if (!snapshot || typeof snapshot !== 'object')
|
|
50
50
|
return null;
|
|
51
|
-
const
|
|
52
|
-
const
|
|
51
|
+
const s = snapshot;
|
|
52
|
+
const normalized = { ...s };
|
|
53
|
+
const slopePct = convertSlopePercentToPerBar(s.slopePct, lookbackBars, mode);
|
|
53
54
|
if (Number.isFinite(slopePct)) {
|
|
54
55
|
normalized.slopePct = slopePct;
|
|
55
56
|
}
|
|
@@ -58,34 +59,37 @@ function normalizePersistedAmaSlopeSnapshot(snapshot, lookbackBars, mode) {
|
|
|
58
59
|
function normalizePersistedAmaSlopeDiagnostics(data, lookbackBars) {
|
|
59
60
|
if (!data || typeof data !== 'object')
|
|
60
61
|
return data;
|
|
61
|
-
const
|
|
62
|
-
const
|
|
62
|
+
const d = data;
|
|
63
|
+
const mode = normalizeAmaSlopePercentMode(d.amaSlopePercentMode) || AMA_SLOPE_PERCENT_MODE_WINDOW;
|
|
64
|
+
const normalized = { ...d };
|
|
63
65
|
normalized.amaSlopePercentMode = AMA_SLOPE_PERCENT_MODE_PER_BAR;
|
|
64
|
-
normalized.amaSlope = normalizePersistedAmaSlopeSnapshot(
|
|
65
|
-
normalized.gridRangeScalingAmaSlope = normalizePersistedAmaSlopeSnapshot(
|
|
66
|
-
const deltaPercent = convertSlopePercentToPerBar(
|
|
67
|
-
const thresholdPercent = convertSlopePercentToPerBar(
|
|
66
|
+
normalized.amaSlope = normalizePersistedAmaSlopeSnapshot(d.amaSlope, lookbackBars, mode);
|
|
67
|
+
normalized.gridRangeScalingAmaSlope = normalizePersistedAmaSlopeSnapshot(d.gridRangeScalingAmaSlope, lookbackBars, mode);
|
|
68
|
+
const deltaPercent = convertSlopePercentToPerBar(d.amaSlopeDeltaPercent, lookbackBars, mode);
|
|
69
|
+
const thresholdPercent = convertSlopePercentToPerBar(d.amaSlopeThresholdPercent, lookbackBars, mode);
|
|
68
70
|
normalized.amaSlopeDeltaPercent = Number.isFinite(deltaPercent) ? deltaPercent : null;
|
|
69
71
|
normalized.amaSlopeThresholdPercent = Number.isFinite(thresholdPercent) ? thresholdPercent : null;
|
|
70
72
|
// Persistence-gate state carried across restarts (see advanceAmaSlopePersistence).
|
|
71
|
-
const persistCount = Number(
|
|
73
|
+
const persistCount = Number(d.amaSlopePersistCount);
|
|
72
74
|
normalized.amaSlopePersistCount = Number.isFinite(persistCount) && persistCount > 0 ? Math.floor(persistCount) : 0;
|
|
73
|
-
const persistDir = Number(
|
|
75
|
+
const persistDir = Number(d.amaSlopePersistDir);
|
|
74
76
|
normalized.amaSlopePersistDir = persistDir === 1 ? 1 : (persistDir === -1 ? -1 : 0);
|
|
75
77
|
return normalized;
|
|
76
78
|
}
|
|
77
79
|
function computeGridPriceOffsetPlan(bot, amaSlope) {
|
|
78
|
-
const
|
|
80
|
+
const b = bot;
|
|
81
|
+
const a = amaSlope;
|
|
82
|
+
const targetSpreadPercentRaw = Number(b?.targetSpreadPercent);
|
|
79
83
|
const targetSpreadPercent = Number.isFinite(targetSpreadPercentRaw) && targetSpreadPercentRaw > 0
|
|
80
84
|
? targetSpreadPercentRaw
|
|
81
85
|
: Number(DEFAULT_CONFIG.targetSpreadPercent);
|
|
82
86
|
const maxGridPriceOffsetPct = targetSpreadPercent / 2;
|
|
83
|
-
const trend =
|
|
84
|
-
const rawSlopeOffset = Number(
|
|
85
|
-
const maxSlopeOffset = Number(
|
|
87
|
+
const trend = a?.trend;
|
|
88
|
+
const rawSlopeOffset = Number(a?.rawSlopeOffset);
|
|
89
|
+
const maxSlopeOffset = Number(a?.maxSlopeOffset);
|
|
86
90
|
const directionalSlope = Number.isFinite(rawSlopeOffset)
|
|
87
91
|
? Math.abs(rawSlopeOffset)
|
|
88
|
-
: Math.abs(Number(
|
|
92
|
+
: Math.abs(Number(a?.slopeOffset));
|
|
89
93
|
const slopeRatio = Number.isFinite(directionalSlope) && Number.isFinite(maxSlopeOffset) && maxSlopeOffset > 0
|
|
90
94
|
? Math.min(directionalSlope / maxSlopeOffset, 1)
|
|
91
95
|
: 0;
|
|
@@ -254,7 +258,8 @@ class MarketAdapterService {
|
|
|
254
258
|
* shortfall) is evaluateStateRepairVeto above; keep the two in step.
|
|
255
259
|
*/
|
|
256
260
|
candleFileCoversClosedBucket(candles, meta, marketSource, closedBucketStartMs, requiredCount = 0) {
|
|
257
|
-
|
|
261
|
+
const closedBucketMs = Number(closedBucketStartMs);
|
|
262
|
+
if (!Number.isFinite(closedBucketMs) || closedBucketMs <= 0)
|
|
258
263
|
return false;
|
|
259
264
|
if (this.isCandleSourceMismatch(meta, marketSource))
|
|
260
265
|
return false;
|
|
@@ -269,7 +274,7 @@ class MarketAdapterService {
|
|
|
269
274
|
const newestTs = Number(candles[candles.length - 1]?.[0]);
|
|
270
275
|
if (!Number.isFinite(newestTs))
|
|
271
276
|
return false;
|
|
272
|
-
return newestTs >=
|
|
277
|
+
return newestTs >= closedBucketMs;
|
|
273
278
|
}
|
|
274
279
|
selectClosedCandles(candles, intervalSeconds, nowMs = this.getNowMs()) {
|
|
275
280
|
const currentBucketStart = bucketStartMs(nowMs, intervalSeconds);
|
|
@@ -313,8 +318,8 @@ class MarketAdapterService {
|
|
|
313
318
|
getMissingTimestampsWithinTimeRange(missingTimestamps, timeRange) {
|
|
314
319
|
if (!Array.isArray(missingTimestamps) || missingTimestamps.length === 0 || !timeRange)
|
|
315
320
|
return [];
|
|
316
|
-
const gteMs = Date.parse(timeRange.gte);
|
|
317
|
-
const lteMs = Date.parse(timeRange.lte);
|
|
321
|
+
const gteMs = Date.parse(String(timeRange.gte));
|
|
322
|
+
const lteMs = Date.parse(String(timeRange.lte));
|
|
318
323
|
if (!Number.isFinite(gteMs) || !Number.isFinite(lteMs) || lteMs < gteMs)
|
|
319
324
|
return [];
|
|
320
325
|
return missingTimestamps.filter((ts) => Number.isFinite(ts) && ts >= gteMs && ts <= lteMs);
|
|
@@ -325,7 +330,7 @@ class MarketAdapterService {
|
|
|
325
330
|
? intervalSeconds / 3600
|
|
326
331
|
: 1;
|
|
327
332
|
const maxCandles = Number.isFinite(cfg?.maxNativeGapFillCandles)
|
|
328
|
-
? cfg.maxNativeGapFillCandles
|
|
333
|
+
? Number(Number(cfg.maxNativeGapFillCandles))
|
|
329
334
|
: MARKET_ADAPTER.STALE_TAIL_THRESHOLD_CANDLES;
|
|
330
335
|
// Include the candle before and after the missing run so Kibana repair
|
|
331
336
|
// does not truncate a valid threshold-sized gap while still respecting
|
|
@@ -334,7 +339,7 @@ class MarketAdapterService {
|
|
|
334
339
|
}
|
|
335
340
|
getTrustedNoTradeGapThresholdCandles(cfg) {
|
|
336
341
|
return Number.isFinite(cfg?.maxNativeGapFillCandles)
|
|
337
|
-
? cfg.maxNativeGapFillCandles
|
|
342
|
+
? Number(Number(cfg.maxNativeGapFillCandles))
|
|
338
343
|
: MARKET_ADAPTER.STALE_TAIL_THRESHOLD_CANDLES;
|
|
339
344
|
}
|
|
340
345
|
fillNativeIncrementalClosedGaps(candles, previousLastTs, intervalSeconds, nowMs = this.getNowMs()) {
|
|
@@ -385,12 +390,12 @@ class MarketAdapterService {
|
|
|
385
390
|
const deps = this.deps;
|
|
386
391
|
const bucketMs = Number(intervalSeconds) * 1000;
|
|
387
392
|
if (!Array.isArray(candles) || candles.length === 0 || !Array.isArray(missingTimestamps) || missingTimestamps.length === 0) {
|
|
388
|
-
return { candles, filledTimestamps: [] };
|
|
393
|
+
return { candles: candles, filledTimestamps: [] };
|
|
389
394
|
}
|
|
390
395
|
if (!Number.isFinite(bucketMs) || bucketMs <= 0)
|
|
391
|
-
return { candles, filledTimestamps: [] };
|
|
396
|
+
return { candles: candles, filledTimestamps: [] };
|
|
392
397
|
if (!Number.isFinite(maxGapCandles) || maxGapCandles <= 0)
|
|
393
|
-
return { candles, filledTimestamps: [] };
|
|
398
|
+
return { candles: candles, filledTimestamps: [] };
|
|
394
399
|
const sortedCandles = candles
|
|
395
400
|
.filter((c) => Array.isArray(c) && Number.isFinite(c[0]))
|
|
396
401
|
.slice()
|
|
@@ -495,7 +500,7 @@ class MarketAdapterService {
|
|
|
495
500
|
const base = Number(centerPrice);
|
|
496
501
|
const ref = Number(referencePrice);
|
|
497
502
|
if (!Number.isFinite(base) || base <= 0)
|
|
498
|
-
return
|
|
503
|
+
return base;
|
|
499
504
|
try {
|
|
500
505
|
const startPrice = Number.isFinite(ref) && ref > 0 ? ref : base;
|
|
501
506
|
const minP = resolveConfiguredPriceBound(bot?.minPrice, DEFAULT_CONFIG.minPrice, startPrice, 'min') ?? 0;
|
|
@@ -672,12 +677,25 @@ class MarketAdapterService {
|
|
|
672
677
|
* (legacy fire-on-first-crossing).
|
|
673
678
|
*/
|
|
674
679
|
resolveAmaSlopePersistBars(cfg) {
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
const
|
|
679
|
-
|
|
680
|
-
|
|
680
|
+
// Per-bot/market `persistBars`: >= 1 sets the gate length, exactly 0
|
|
681
|
+
// disables it (legacy 1). Negative/NaN fall through to the enable flags.
|
|
682
|
+
const rawBars = cfg?.amaSlope?.persistBars ?? cfg?.amaSlopePersistBars;
|
|
683
|
+
const explicit = (rawBars === null || rawBars === undefined) ? NaN : Number(rawBars);
|
|
684
|
+
if (Number.isFinite(explicit)) {
|
|
685
|
+
if (explicit >= 1)
|
|
686
|
+
return Math.round(explicit);
|
|
687
|
+
if (explicit === 0)
|
|
688
|
+
return 1;
|
|
689
|
+
}
|
|
690
|
+
// `persistEnabled` is a tri-state override: an explicit false disables
|
|
691
|
+
// the gate even when the global default is on; undefined falls back to
|
|
692
|
+
// the global flag; explicit true enables it. Must be an explicit
|
|
693
|
+
// tri-state check — a `||` chain lets the global `true` mask a per-bot
|
|
694
|
+
// `false`, silently killing the documented per-bot rollback.
|
|
695
|
+
const override = cfg?.amaSlope?.persistEnabled ?? cfg?.amaSlopePersistEnabled;
|
|
696
|
+
const enabled = override === false ? false
|
|
697
|
+
: override === true ? true
|
|
698
|
+
: MARKET_ADAPTER.AMA_SLOPE_PERSIST_ENABLED === true;
|
|
681
699
|
if (!enabled)
|
|
682
700
|
return 1;
|
|
683
701
|
const bars = Number(MARKET_ADAPTER.AMA_SLOPE_PERSIST_BARS);
|
|
@@ -716,7 +734,7 @@ class MarketAdapterService {
|
|
|
716
734
|
normalizePersistedBotState(botState, lookbackBars) {
|
|
717
735
|
if (!botState || typeof botState !== 'object')
|
|
718
736
|
return {};
|
|
719
|
-
return normalizePersistedAmaSlopeDiagnostics(botState, lookbackBars);
|
|
737
|
+
return (normalizePersistedAmaSlopeDiagnostics(botState, lookbackBars) ?? {});
|
|
720
738
|
}
|
|
721
739
|
extractPersistedDynamicGridState(snapshot, lookbackBars) {
|
|
722
740
|
if (!snapshot || typeof snapshot !== 'object')
|
|
@@ -819,7 +837,7 @@ class MarketAdapterService {
|
|
|
819
837
|
// The gate still recomputes from scratch whenever the cached
|
|
820
838
|
// closes are not a prefix of the incoming window (gap repair,
|
|
821
839
|
// rewritten bar, shortened window) or a parameter changed.
|
|
822
|
-
cacheKey: `${bot?.botKey ?? 'bot'}:${cfg.intervalSeconds}`,
|
|
840
|
+
cacheKey: `${bot?.botKey ?? 'bot'}:${Number(cfg.intervalSeconds)}`,
|
|
823
841
|
});
|
|
824
842
|
regimeMultiplier = regimeResult.isReady && Math.abs(regimeResult.multiplier - 1.0) >= absoluteThreshold
|
|
825
843
|
? regimeResult.multiplier
|
|
@@ -868,16 +886,14 @@ class MarketAdapterService {
|
|
|
868
886
|
const outputThreshold = minOutputThreshold;
|
|
869
887
|
// Per-bar directional offset series — canonical implementation shared
|
|
870
888
|
// with the research chart and test harness (see dynamic_weight_series.ts).
|
|
871
|
-
|
|
889
|
+
// The base inputs are identical for the real series and the AMA-only
|
|
890
|
+
// diagnostic; only the Kalman inputs and clip threshold differ.
|
|
891
|
+
const seriesBaseInputs = {
|
|
872
892
|
amaValues,
|
|
873
|
-
kalmanVelocityPct: kalmanSmoothedVelocityPct,
|
|
874
|
-
kalmanDisplacementPct: kalmanHistory.map((kr) => kr.displacementRawPct),
|
|
875
|
-
kalmanIsReady: kalmanHistory.map((kr) => kr.isReady),
|
|
876
893
|
regimeMultipliers,
|
|
877
894
|
lookbackBars,
|
|
878
895
|
amaErPeriod: botAma.erPeriod,
|
|
879
896
|
amaClipThreshold,
|
|
880
|
-
kalClipThreshold,
|
|
881
897
|
neutralZonePct: nz,
|
|
882
898
|
amaMaxSlopePct: amaMaxS,
|
|
883
899
|
kalmanMaxSlopePct: kalMaxS,
|
|
@@ -889,6 +905,13 @@ class MarketAdapterService {
|
|
|
889
905
|
minOutputThreshold,
|
|
890
906
|
signalConfirmBars,
|
|
891
907
|
clampFinalOutput: true,
|
|
908
|
+
};
|
|
909
|
+
const seriesResult = computeDynamicWeightSeries({
|
|
910
|
+
...seriesBaseInputs,
|
|
911
|
+
kalmanVelocityPct: kalmanSmoothedVelocityPct,
|
|
912
|
+
kalmanDisplacementPct: kalmanHistory.map((kr) => kr.displacementRawPct),
|
|
913
|
+
kalmanIsReady: kalmanHistory.map((kr) => kr.isReady),
|
|
914
|
+
kalClipThreshold,
|
|
892
915
|
});
|
|
893
916
|
const { combinedOffSeries, gatedOffSeries, echoedOffSeries, echoedGatedOffSeries, } = seriesResult;
|
|
894
917
|
const rawFinalOff = combinedOffSeries[combinedOffSeries.length - 1] ?? 0;
|
|
@@ -902,55 +925,44 @@ class MarketAdapterService {
|
|
|
902
925
|
// alpha*(offset/norm)*gain*regime recomputation diverged from
|
|
903
926
|
// finalOffset whenever gating or signal confirmation was active.)
|
|
904
927
|
const amaOnlySeriesResult = computeDynamicWeightSeries({
|
|
905
|
-
|
|
928
|
+
...seriesBaseInputs,
|
|
906
929
|
kalmanVelocityPct: kalmanSmoothedVelocityPct.map(() => null),
|
|
907
930
|
kalmanDisplacementPct: kalmanHistory.map(() => null),
|
|
908
931
|
kalmanIsReady: kalmanHistory.map(() => false),
|
|
909
|
-
regimeMultipliers,
|
|
910
|
-
lookbackBars,
|
|
911
|
-
amaErPeriod: botAma.erPeriod,
|
|
912
|
-
amaClipThreshold,
|
|
913
932
|
kalClipThreshold: Infinity,
|
|
914
|
-
neutralZonePct: nz,
|
|
915
|
-
amaMaxSlopePct: amaMaxS,
|
|
916
|
-
kalmanMaxSlopePct: kalMaxS,
|
|
917
|
-
offsetClamp,
|
|
918
|
-
dispScaleMinPct,
|
|
919
|
-
alpha,
|
|
920
|
-
dw,
|
|
921
|
-
gain,
|
|
922
|
-
minOutputThreshold,
|
|
923
|
-
signalConfirmBars,
|
|
924
|
-
clampFinalOutput: true,
|
|
925
933
|
});
|
|
926
934
|
const amaSlopeGated = slopeResult.isReady
|
|
927
935
|
? (useAmaBlend
|
|
928
936
|
? (amaOnlySeriesResult.echoedOffSeries[amaOnlySeriesResult.echoedOffSeries.length - 1] ?? 0)
|
|
929
937
|
: 0)
|
|
930
938
|
: 0;
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
rawSlopeOffset: slopeResult.rawSlopeOffset,
|
|
937
|
-
amaSlopeGated,
|
|
938
|
-
regimeMultiplier,
|
|
939
|
-
symmetricDelta: slopeResult.symmetricDelta,
|
|
940
|
-
weightVariance,
|
|
941
|
-
isReady: slopeResult.isReady,
|
|
942
|
-
kalmanReady: kalmanResult?.isReady ?? false,
|
|
939
|
+
// Shared report fragments so the diagnostic `amaSlope` snapshot, the
|
|
940
|
+
// persisted `weights.meta` and `dynamicWeightsPayload` cannot drift
|
|
941
|
+
// apart. Kept as separate pieces so each object keeps its original
|
|
942
|
+
// key order.
|
|
943
|
+
const blendReport = {
|
|
943
944
|
alpha,
|
|
944
945
|
dw,
|
|
945
946
|
gain,
|
|
946
|
-
atrPeriod
|
|
947
|
+
atrPeriod,
|
|
947
948
|
maxSlopeOffset: mo,
|
|
949
|
+
};
|
|
950
|
+
const slopeConfigReport = {
|
|
948
951
|
amaSlope: {
|
|
949
952
|
maxSlopePct: amaMaxS,
|
|
950
953
|
},
|
|
951
954
|
kalmanSlope: {
|
|
952
955
|
maxSlopePct: kalMaxS,
|
|
953
956
|
},
|
|
957
|
+
};
|
|
958
|
+
const volatilityReport = {
|
|
959
|
+
clipPercentile,
|
|
960
|
+
neutralZonePct: nz,
|
|
961
|
+
volatilityThreshold,
|
|
962
|
+
volatilityExponent,
|
|
963
|
+
volatilityScaleX,
|
|
964
|
+
};
|
|
965
|
+
const kalmanReport = {
|
|
954
966
|
maxVolatilityOffset: volatilityClamp,
|
|
955
967
|
kalmanSmoothPct,
|
|
956
968
|
kalmanDispScaleMult,
|
|
@@ -958,8 +970,24 @@ class MarketAdapterService {
|
|
|
958
970
|
kalmanSmoothSpanPct,
|
|
959
971
|
signalConfirmBars,
|
|
960
972
|
};
|
|
961
|
-
const
|
|
962
|
-
|
|
973
|
+
const amaSlope = {
|
|
974
|
+
trend: slopeResult.trend,
|
|
975
|
+
confidence: slopeResult.confidence,
|
|
976
|
+
slopePct: slopeResult.slopePct,
|
|
977
|
+
slopeOffset: slopeResult.slopeOffset,
|
|
978
|
+
rawSlopeOffset: slopeResult.rawSlopeOffset,
|
|
979
|
+
amaSlopeGated,
|
|
980
|
+
regimeMultiplier,
|
|
981
|
+
symmetricDelta: slopeResult.symmetricDelta,
|
|
982
|
+
weightVariance,
|
|
983
|
+
isReady: slopeResult.isReady,
|
|
984
|
+
kalmanReady: kalmanResult?.isReady ?? false,
|
|
985
|
+
...blendReport,
|
|
986
|
+
...slopeConfigReport,
|
|
987
|
+
...kalmanReport,
|
|
988
|
+
};
|
|
989
|
+
const staticSell = bot.weightDistribution?.sell ?? 0;
|
|
990
|
+
const staticBuy = bot.weightDistribution?.buy ?? 0;
|
|
963
991
|
const MIN_W = MARKET_ADAPTER.DYNAMIC_WEIGHT_MIN_WEIGHT;
|
|
964
992
|
const MAX_W = MARKET_ADAPTER.DYNAMIC_WEIGHT_MAX_WEIGHT;
|
|
965
993
|
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
|
|
@@ -989,34 +1017,16 @@ class MarketAdapterService {
|
|
|
989
1017
|
regimeSensitivity,
|
|
990
1018
|
absoluteThreshold,
|
|
991
1019
|
volatilityPenalty: volPenalty,
|
|
992
|
-
|
|
993
|
-
dw,
|
|
994
|
-
gain,
|
|
995
|
-
atrPeriod: atrPeriod,
|
|
996
|
-
maxSlopeOffset: mo,
|
|
1020
|
+
...blendReport,
|
|
997
1021
|
maxAsymmetryFactor: (cfg.asymmetricBounds?.maxAsymmetryFactor != null)
|
|
998
1022
|
? cfg.asymmetricBounds.maxAsymmetryFactor
|
|
999
1023
|
: null,
|
|
1000
1024
|
minScaleSlots: (cfg.asymmetricBounds?.minScaleSlots != null)
|
|
1001
1025
|
? cfg.asymmetricBounds.minScaleSlots
|
|
1002
1026
|
: null,
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
volatilityExponent,
|
|
1007
|
-
volatilityScaleX,
|
|
1008
|
-
amaSlope: {
|
|
1009
|
-
maxSlopePct: amaMaxS,
|
|
1010
|
-
},
|
|
1011
|
-
kalmanSlope: {
|
|
1012
|
-
maxSlopePct: kalMaxS,
|
|
1013
|
-
},
|
|
1014
|
-
maxVolatilityOffset: volatilityClamp,
|
|
1015
|
-
kalmanSmoothPct,
|
|
1016
|
-
kalmanDispScaleMult,
|
|
1017
|
-
kalmanDispThresholdMult,
|
|
1018
|
-
kalmanSmoothSpanPct,
|
|
1019
|
-
signalConfirmBars,
|
|
1027
|
+
...volatilityReport,
|
|
1028
|
+
...slopeConfigReport,
|
|
1029
|
+
...kalmanReport,
|
|
1020
1030
|
amaChannelContribution: amaSlopeGated,
|
|
1021
1031
|
rawFinalOffset: rawFinalOff,
|
|
1022
1032
|
trendOffset: trendOff,
|
|
@@ -1036,28 +1046,10 @@ class MarketAdapterService {
|
|
|
1036
1046
|
amaSlopeGated,
|
|
1037
1047
|
volatilityPenalty: volPenalty,
|
|
1038
1048
|
finalOffset: finalOff,
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
maxSlopeOffset: mo,
|
|
1044
|
-
amaSlope: {
|
|
1045
|
-
maxSlopePct: amaMaxS,
|
|
1046
|
-
},
|
|
1047
|
-
kalmanSlope: {
|
|
1048
|
-
maxSlopePct: kalMaxS,
|
|
1049
|
-
},
|
|
1050
|
-
clipPercentile,
|
|
1051
|
-
neutralZonePct: nz,
|
|
1052
|
-
volatilityThreshold,
|
|
1053
|
-
volatilityExponent,
|
|
1054
|
-
volatilityScaleX,
|
|
1055
|
-
maxVolatilityOffset: volatilityClamp,
|
|
1056
|
-
kalmanSmoothPct,
|
|
1057
|
-
kalmanDispScaleMult,
|
|
1058
|
-
kalmanDispThresholdMult,
|
|
1059
|
-
kalmanSmoothSpanPct,
|
|
1060
|
-
signalConfirmBars,
|
|
1049
|
+
...blendReport,
|
|
1050
|
+
...slopeConfigReport,
|
|
1051
|
+
...volatilityReport,
|
|
1052
|
+
...kalmanReport,
|
|
1061
1053
|
rawFinalOffset: rawFinalOff,
|
|
1062
1054
|
maxAsymmetryFactor: (cfg.asymmetricBounds?.maxAsymmetryFactor != null)
|
|
1063
1055
|
? cfg.asymmetricBounds.maxAsymmetryFactor
|
|
@@ -1109,7 +1101,7 @@ class MarketAdapterService {
|
|
|
1109
1101
|
const thresholdPercent = typeof deps.calculateBotThreshold === 'function'
|
|
1110
1102
|
? deps.calculateBotThreshold(cfg)
|
|
1111
1103
|
: null;
|
|
1112
|
-
state.bots[bot.botKey] = this.buildDefaultBotState(bot, {
|
|
1104
|
+
state.bots[String(bot.botKey)] = this.buildDefaultBotState(bot, {
|
|
1113
1105
|
startPrice: bot.startPrice,
|
|
1114
1106
|
priceMode: 'fixed',
|
|
1115
1107
|
lastCycleSource: 'fixed-start-price',
|
|
@@ -1124,13 +1116,13 @@ class MarketAdapterService {
|
|
|
1124
1116
|
});
|
|
1125
1117
|
}
|
|
1126
1118
|
const contextSignature = this.buildBotContextSignature(bot);
|
|
1127
|
-
const cached = contextCache.get(bot.botKey);
|
|
1128
|
-
const cachedCtx = cached && typeof cached === 'object' && cached.ctx ? cached.ctx : cached;
|
|
1119
|
+
const cached = contextCache.get(String(bot.botKey));
|
|
1120
|
+
const cachedCtx = (cached && typeof cached === 'object' && cached.ctx ? cached.ctx : cached);
|
|
1129
1121
|
const cachedSignature = cached && typeof cached === 'object' && cached.signature ? cached.signature : null;
|
|
1130
|
-
let ctx = cachedCtx;
|
|
1131
|
-
if (!
|
|
1132
|
-
ctx = await deps.resolveBotContext(bot);
|
|
1133
|
-
contextCache.set(bot.botKey, {
|
|
1122
|
+
let ctx = cachedCtx ?? {};
|
|
1123
|
+
if (!cachedCtx || cachedSignature !== contextSignature) {
|
|
1124
|
+
ctx = (await deps.resolveBotContext(bot)) ?? {};
|
|
1125
|
+
contextCache.set(String(bot.botKey), {
|
|
1134
1126
|
signature: contextSignature,
|
|
1135
1127
|
ctx,
|
|
1136
1128
|
});
|
|
@@ -1145,7 +1137,7 @@ class MarketAdapterService {
|
|
|
1145
1137
|
return { ok: false, reason: 'ama disabled' };
|
|
1146
1138
|
}
|
|
1147
1139
|
const lookbackBars = normalizeAmaSlopeLookbackBars(cfg.amaSlope?.lookbackBars);
|
|
1148
|
-
const filePath = deps.candleFileForBot(bot.botKey, cfg.intervalSeconds);
|
|
1140
|
+
const filePath = deps.candleFileForBot(bot.botKey, Number(cfg.intervalSeconds));
|
|
1149
1141
|
// mtime-validated read cache: the previous cycle serialized this very
|
|
1150
1142
|
// file, so re-parsing ~250 KiB of JSON per bot per hour is pure waste.
|
|
1151
1143
|
// The cache decides on the file's stat alone — an unstattable file (or a
|
|
@@ -1161,7 +1153,7 @@ class MarketAdapterService {
|
|
|
1161
1153
|
// Retention targets, derived from the bot's own AMA parameters. Pure and
|
|
1162
1154
|
// local, so they are computed before the off-hour gate below (which
|
|
1163
1155
|
// needs the warmup target) and reused by the full path unchanged.
|
|
1164
|
-
const amaWarmupBars = getAmaWarmupBars(botAma.erPeriod, botAma.slowPeriod, lookbackBars, botAma.fastPeriod);
|
|
1156
|
+
const amaWarmupBars = getAmaWarmupBars(Number(botAma.erPeriod), Number(botAma.slowPeriod), lookbackBars, Number(botAma.fastPeriod));
|
|
1165
1157
|
const analysisKeepCount = amaWarmupBars + 1;
|
|
1166
1158
|
// Retain one extra raw candle so the closed-candle analysis window still keeps a
|
|
1167
1159
|
// full warmup/history set when the newest bucket is the current in-progress bar.
|
|
@@ -1184,9 +1176,9 @@ class MarketAdapterService {
|
|
|
1184
1176
|
// change — must still run. Only a bot that has demonstrably consumed
|
|
1185
1177
|
// that bucket and holds the data for it is skipped.
|
|
1186
1178
|
const persistedBotState = (state?.bots && typeof state.bots === 'object')
|
|
1187
|
-
? state.bots[bot.botKey]
|
|
1179
|
+
? state.bots[String(bot.botKey)]
|
|
1188
1180
|
: null;
|
|
1189
|
-
const offHourSkip = this.shouldSkipBotForClosedCandle(bot, persistedBotState, cfg.intervalSeconds, undefined, cfg);
|
|
1181
|
+
const offHourSkip = this.shouldSkipBotForClosedCandle(bot, persistedBotState, Number(cfg.intervalSeconds), undefined, cfg);
|
|
1190
1182
|
const offHourSkipCovered = !!offHourSkip && this.candleFileCoversClosedBucket(existingCandles, existingMeta, marketSource, offHourSkip.latestClosedBucketStartMs, rawKeepCount);
|
|
1191
1183
|
if (offHourSkip && offHourSkipCovered) {
|
|
1192
1184
|
const skipNowIso = new Date().toISOString();
|
|
@@ -1202,7 +1194,7 @@ class MarketAdapterService {
|
|
|
1202
1194
|
pendingClosedCandle: true,
|
|
1203
1195
|
lastTriggerSuppressedReason: 'waiting_for_new_closed_candle',
|
|
1204
1196
|
};
|
|
1205
|
-
state.bots[bot.botKey] = skippedState;
|
|
1197
|
+
state.bots[String(bot.botKey)] = skippedState;
|
|
1206
1198
|
return this.buildDefaultResult(bot, {
|
|
1207
1199
|
dryRunMessages,
|
|
1208
1200
|
source: 'off-hour-skip',
|
|
@@ -1214,8 +1206,8 @@ class MarketAdapterService {
|
|
|
1214
1206
|
pendingClosedCandle: true,
|
|
1215
1207
|
});
|
|
1216
1208
|
}
|
|
1217
|
-
const kibanaRequestTimeoutMs = Number.isFinite(cfg.kibanaRequestTimeoutMs) && cfg.kibanaRequestTimeoutMs > 0
|
|
1218
|
-
? cfg.kibanaRequestTimeoutMs
|
|
1209
|
+
const kibanaRequestTimeoutMs = Number.isFinite(Number(cfg.kibanaRequestTimeoutMs)) && Number(cfg.kibanaRequestTimeoutMs) > 0
|
|
1210
|
+
? Number(cfg.kibanaRequestTimeoutMs)
|
|
1219
1211
|
: MARKET_ADAPTER.KIBANA_REQUEST_TIMEOUT_MS;
|
|
1220
1212
|
const fetchKibanaCandles = async (options = {}) => {
|
|
1221
1213
|
const kibanaOptions = {
|
|
@@ -1264,7 +1256,8 @@ class MarketAdapterService {
|
|
|
1264
1256
|
const tailEndTs = detected.sorted[detected.sorted.length - 1][0];
|
|
1265
1257
|
// Skip Kibana verification if this tail range was already confirmed flat
|
|
1266
1258
|
// on a previous cycle (the current tail is contained within a verified range).
|
|
1267
|
-
const
|
|
1259
|
+
const vStart = Number(verifiedRange.startTs);
|
|
1260
|
+
const vEnd = Number(verifiedRange.endTs);
|
|
1268
1261
|
if (Number.isFinite(vStart) && Number.isFinite(vEnd)
|
|
1269
1262
|
&& tailStartTs >= vStart && tailEndTs <= vEnd) {
|
|
1270
1263
|
return { candles, keptStaleTailStartTs: tailStartTs, keptStaleTailEndTs: tailEndTs };
|
|
@@ -1272,7 +1265,7 @@ class MarketAdapterService {
|
|
|
1272
1265
|
// Verify with Kibana: did the market actually trade during this period?
|
|
1273
1266
|
try {
|
|
1274
1267
|
const kibanaCandles = await deps.withRetries(() => fetchKibanaCandles({
|
|
1275
|
-
intervalSeconds: cfg.intervalSeconds,
|
|
1268
|
+
intervalSeconds: Number(cfg.intervalSeconds),
|
|
1276
1269
|
fillGapsToRequestedRange: false,
|
|
1277
1270
|
apiKey: null,
|
|
1278
1271
|
timeRange: {
|
|
@@ -1365,7 +1358,7 @@ class MarketAdapterService {
|
|
|
1365
1358
|
? deps.kibanaMarketSource && typeof deps.kibanaMarketSource.getMarketCandles === 'function'
|
|
1366
1359
|
: deps.kibanaSource && typeof deps.kibanaSource.getLpCandlesForPool === 'function';
|
|
1367
1360
|
const verifyAndFillLongSilence = async (candles, lastTs, latestClosedBucketTs, sourceLabel, incomingCandles = []) => {
|
|
1368
|
-
const bucketMs = Number(cfg.intervalSeconds) * 1000;
|
|
1361
|
+
const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
|
|
1369
1362
|
const silenceStartTs = Number(lastTs) + bucketMs;
|
|
1370
1363
|
const earliestIncomingTs = (Array.isArray(incomingCandles) ? incomingCandles : [])
|
|
1371
1364
|
.filter((c) => Array.isArray(c) && Number.isFinite(c[0]) && c[0] > lastTs)
|
|
@@ -1381,7 +1374,7 @@ class MarketAdapterService {
|
|
|
1381
1374
|
}
|
|
1382
1375
|
try {
|
|
1383
1376
|
const kibanaSilenceCandles = await deps.withRetries(() => fetchKibanaCandles({
|
|
1384
|
-
intervalSeconds: cfg.intervalSeconds,
|
|
1377
|
+
intervalSeconds: Number(cfg.intervalSeconds),
|
|
1385
1378
|
fillGapsToRequestedRange: false,
|
|
1386
1379
|
apiKey: null,
|
|
1387
1380
|
timeRange: {
|
|
@@ -1402,7 +1395,7 @@ class MarketAdapterService {
|
|
|
1402
1395
|
.filter((c) => Array.isArray(c) && c[0] === lastTs)
|
|
1403
1396
|
.slice(-1)[0];
|
|
1404
1397
|
const filledSilence = previousCandle
|
|
1405
|
-
? deps.fillCandleGaps([previousCandle, ...(Array.isArray(incomingCandles) ? incomingCandles : [])], cfg.intervalSeconds, lastTs, silenceEndTs)
|
|
1398
|
+
? deps.fillCandleGaps([previousCandle, ...(Array.isArray(incomingCandles) ? incomingCandles : [])], Number(cfg.intervalSeconds), lastTs, silenceEndTs)
|
|
1406
1399
|
.filter((c) => Array.isArray(c) && c[0] > lastTs)
|
|
1407
1400
|
: [];
|
|
1408
1401
|
if (filledSilence.length === 0)
|
|
@@ -1431,34 +1424,49 @@ class MarketAdapterService {
|
|
|
1431
1424
|
}
|
|
1432
1425
|
};
|
|
1433
1426
|
const fillBoundedTrailingClosedGap = (candles, latestClosedBucketTs, nowMs, maxNativeGapFill) => {
|
|
1434
|
-
const bucketMs = Number(cfg.intervalSeconds) * 1000;
|
|
1427
|
+
const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
|
|
1435
1428
|
const latestKnownTs = Array.isArray(candles) && candles.length > 0
|
|
1436
1429
|
? candles[candles.length - 1]?.[0]
|
|
1437
1430
|
: null;
|
|
1438
1431
|
const trailingGapBuckets = Number.isFinite(bucketMs) && bucketMs > 0
|
|
1439
|
-
&& Number.isFinite(latestClosedBucketTs) && Number.isFinite(latestKnownTs)
|
|
1432
|
+
&& Number.isFinite(latestClosedBucketTs) && latestKnownTs != null && Number.isFinite(latestKnownTs)
|
|
1440
1433
|
&& latestClosedBucketTs > latestKnownTs
|
|
1441
1434
|
? Math.round((latestClosedBucketTs - latestKnownTs) / bucketMs)
|
|
1442
1435
|
: 0;
|
|
1443
1436
|
if (trailingGapBuckets <= 0 || trailingGapBuckets > maxNativeGapFill) {
|
|
1444
1437
|
return candles;
|
|
1445
1438
|
}
|
|
1446
|
-
return this.fillNativeIncrementalClosedGaps(candles, latestKnownTs, cfg.intervalSeconds, nowMs);
|
|
1439
|
+
return this.fillNativeIncrementalClosedGaps(candles, latestKnownTs, Number(cfg.intervalSeconds), nowMs);
|
|
1447
1440
|
};
|
|
1448
1441
|
if (isBookSource) {
|
|
1449
1442
|
nativeRecentTradeSequences = [];
|
|
1450
1443
|
nativeLastTradeTs = null;
|
|
1451
1444
|
nativeOverlapCount = null;
|
|
1452
1445
|
nativePagesFetched = null;
|
|
1453
|
-
const bucketMs = Number(cfg.intervalSeconds) * 1000;
|
|
1446
|
+
const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
|
|
1454
1447
|
const nowMs = this.getNowMs();
|
|
1448
|
+
// Native order-book history fetch shared by the bootstrap
|
|
1449
|
+
// fallback and the incremental path. Returns [] on failure
|
|
1450
|
+
// (after the same warn the inline blocks used to emit).
|
|
1451
|
+
const fetchNativeHistory = async (startMs, failureLabel) => {
|
|
1452
|
+
try {
|
|
1453
|
+
if (typeof deps.fetchNativeMarketHistorySince === 'function') {
|
|
1454
|
+
return await deps.withRetries(() => deps.fetchNativeMarketHistorySince(ctx.assetA, ctx.assetB, startMs, nowMs, Number(cfg.intervalSeconds), { fillCandleGaps: deps.fillCandleGaps }), cfg.sourceRetries, cfg.retryDelayMs, failureLabel);
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
catch (_) {
|
|
1458
|
+
if (typeof deps.logger?.warn === 'function')
|
|
1459
|
+
deps.logger.warn(`[market_adapter] ${ctx.botKey}: ${failureLabel}`);
|
|
1460
|
+
}
|
|
1461
|
+
return [];
|
|
1462
|
+
};
|
|
1455
1463
|
if (needBootstrap) {
|
|
1456
1464
|
// Bootstrap: Kibana first (deep history), native as fallback
|
|
1457
1465
|
const kibanaLookbackHours = this.bootstrapKibanaLookbackHours(cfg, rawKeepCount);
|
|
1458
1466
|
let kibanaCandles = null;
|
|
1459
1467
|
try {
|
|
1460
1468
|
kibanaCandles = await deps.withRetries(() => fetchKibanaCandles({
|
|
1461
|
-
intervalSeconds: cfg.intervalSeconds,
|
|
1469
|
+
intervalSeconds: Number(cfg.intervalSeconds),
|
|
1462
1470
|
lookbackHours: kibanaLookbackHours,
|
|
1463
1471
|
fillGapsToRequestedRange: false,
|
|
1464
1472
|
apiKey: null,
|
|
@@ -1474,18 +1482,9 @@ class MarketAdapterService {
|
|
|
1474
1482
|
}
|
|
1475
1483
|
else {
|
|
1476
1484
|
// Fall back to native
|
|
1477
|
-
const nativeLookbackHours = Math.max(Number(cfg.bootstrapLookbackHours) || 0, Number(cfg.nativeBackfillHours) || 0, (analysisKeepCount * Math.max(Number(cfg.intervalSeconds) || 3600, 3600)) / 3600);
|
|
1485
|
+
const nativeLookbackHours = Math.max(Number(cfg.bootstrapLookbackHours) || 0, Number(Number(cfg.nativeBackfillHours)) || 0, (analysisKeepCount * Math.max(Number(Number(cfg.intervalSeconds)) || 3600, 3600)) / 3600);
|
|
1478
1486
|
const nativeStartMs = Math.max(0, nowMs - (nativeLookbackHours * 3600 * 1000));
|
|
1479
|
-
|
|
1480
|
-
try {
|
|
1481
|
-
if (typeof deps.fetchNativeMarketHistorySince === 'function') {
|
|
1482
|
-
nativeCandles = await deps.withRetries(() => deps.fetchNativeMarketHistorySince(ctx.assetA, ctx.assetB, nativeStartMs, nowMs, cfg.intervalSeconds, { fillCandleGaps: deps.fillCandleGaps }), cfg.sourceRetries, cfg.retryDelayMs, 'native market history bootstrap failed');
|
|
1483
|
-
}
|
|
1484
|
-
}
|
|
1485
|
-
catch (_) {
|
|
1486
|
-
if (typeof deps.logger?.warn === 'function')
|
|
1487
|
-
deps.logger.warn(`[market_adapter] ${ctx.botKey}: native market history bootstrap failed`);
|
|
1488
|
-
}
|
|
1487
|
+
const nativeCandles = await fetchNativeHistory(nativeStartMs, 'native market history bootstrap failed');
|
|
1489
1488
|
if (Array.isArray(nativeCandles) && nativeCandles.length > 0) {
|
|
1490
1489
|
nextCandles = nativeCandles;
|
|
1491
1490
|
sourceLabel = 'native-book-bootstrap';
|
|
@@ -1499,16 +1498,7 @@ class MarketAdapterService {
|
|
|
1499
1498
|
// Incremental: native fetch
|
|
1500
1499
|
const lastTs = nextCandles[nextCandles.length - 1]?.[0] || 0;
|
|
1501
1500
|
const nativeStartMs = Math.max(0, lastTs - bucketMs);
|
|
1502
|
-
|
|
1503
|
-
try {
|
|
1504
|
-
if (typeof deps.fetchNativeMarketHistorySince === 'function') {
|
|
1505
|
-
nativeCandles = await deps.withRetries(() => deps.fetchNativeMarketHistorySince(ctx.assetA, ctx.assetB, nativeStartMs, nowMs, cfg.intervalSeconds, { fillCandleGaps: deps.fillCandleGaps }), cfg.sourceRetries, cfg.retryDelayMs, 'native market history fetch failed');
|
|
1506
|
-
}
|
|
1507
|
-
}
|
|
1508
|
-
catch (_) {
|
|
1509
|
-
if (typeof deps.logger?.warn === 'function')
|
|
1510
|
-
deps.logger.warn(`[market_adapter] ${ctx.botKey}: native market history fetch failed`);
|
|
1511
|
-
}
|
|
1501
|
+
const nativeCandles = await fetchNativeHistory(nativeStartMs, 'native market history fetch failed');
|
|
1512
1502
|
if (Array.isArray(nativeCandles) && nativeCandles.length > 0) {
|
|
1513
1503
|
nextCandles = deps.mergeCandles(nextCandles, nativeCandles);
|
|
1514
1504
|
sourceLabel = 'native-book-history';
|
|
@@ -1519,14 +1509,14 @@ class MarketAdapterService {
|
|
|
1519
1509
|
const currentBucketStartMs = Math.floor(Number(nowMs) / bucketMs) * bucketMs;
|
|
1520
1510
|
const latestClosedBucketTs = currentBucketStartMs - bucketMs;
|
|
1521
1511
|
const earliestIncomingTs = nativeCandles.length > 0 ? nativeCandles[0][0] : null;
|
|
1522
|
-
const gapEndTs = Number.isFinite(earliestIncomingTs) && earliestIncomingTs > lastTs
|
|
1512
|
+
const gapEndTs = earliestIncomingTs != null && Number.isFinite(earliestIncomingTs) && earliestIncomingTs > lastTs
|
|
1523
1513
|
? earliestIncomingTs
|
|
1524
1514
|
: latestClosedBucketTs + bucketMs;
|
|
1525
1515
|
const gapBuckets = gapEndTs !== null && gapEndTs > lastTs
|
|
1526
1516
|
? Math.round((gapEndTs - lastTs) / bucketMs) - 1
|
|
1527
1517
|
: 0;
|
|
1528
|
-
const maxNativeGapFill = Number.isFinite(cfg.maxNativeGapFillCandles)
|
|
1529
|
-
? cfg.maxNativeGapFillCandles
|
|
1518
|
+
const maxNativeGapFill = Number.isFinite(Number(cfg.maxNativeGapFillCandles))
|
|
1519
|
+
? Number(cfg.maxNativeGapFillCandles)
|
|
1530
1520
|
: MARKET_ADAPTER.STALE_TAIL_THRESHOLD_CANDLES;
|
|
1531
1521
|
if (gapBuckets > maxNativeGapFill) {
|
|
1532
1522
|
const verifiedSilence = await verifyAndFillLongSilence(nextCandles, lastTs, latestClosedBucketTs, sourceLabel, nativeCandles);
|
|
@@ -1553,7 +1543,7 @@ class MarketAdapterService {
|
|
|
1553
1543
|
let kibanaCandles = null;
|
|
1554
1544
|
try {
|
|
1555
1545
|
kibanaCandles = await deps.withRetries(() => fetchKibanaCandles({
|
|
1556
|
-
intervalSeconds: cfg.intervalSeconds,
|
|
1546
|
+
intervalSeconds: Number(cfg.intervalSeconds),
|
|
1557
1547
|
lookbackHours,
|
|
1558
1548
|
fillGapsToRequestedRange: false,
|
|
1559
1549
|
apiKey: null,
|
|
@@ -1582,11 +1572,11 @@ class MarketAdapterService {
|
|
|
1582
1572
|
if (Number.isFinite(latestTradeTs))
|
|
1583
1573
|
nativeLastTradeTs = latestTradeTs;
|
|
1584
1574
|
}
|
|
1585
|
-
nativeCandles = deps.tradesToCandles(trades, ctx.assetA, ctx.assetB, cfg.intervalSeconds);
|
|
1575
|
+
nativeCandles = deps.tradesToCandles(trades, ctx.assetA, ctx.assetB, Number(cfg.intervalSeconds));
|
|
1586
1576
|
if (nativeCandles.length > 0 && typeof deps.fillCandleGaps === 'function') {
|
|
1587
1577
|
const eTs = nativeCandles[0][0];
|
|
1588
1578
|
const lTs = nativeCandles[nativeCandles.length - 1][0];
|
|
1589
|
-
nativeCandles = deps.fillCandleGaps(nativeCandles, cfg.intervalSeconds, eTs, lTs);
|
|
1579
|
+
nativeCandles = deps.fillCandleGaps(nativeCandles, Number(cfg.intervalSeconds), eTs, lTs);
|
|
1590
1580
|
}
|
|
1591
1581
|
}
|
|
1592
1582
|
catch (_) {
|
|
@@ -1602,7 +1592,7 @@ class MarketAdapterService {
|
|
|
1602
1592
|
if (stitched.length > 1 && typeof deps.fillCandleGaps === 'function') {
|
|
1603
1593
|
const sTs = stitched[0][0];
|
|
1604
1594
|
const eTs = stitched[stitched.length - 1][0];
|
|
1605
|
-
nextCandles = deps.fillCandleGaps(stitched, cfg.intervalSeconds, sTs, eTs);
|
|
1595
|
+
nextCandles = deps.fillCandleGaps(stitched, Number(cfg.intervalSeconds), sTs, eTs);
|
|
1606
1596
|
}
|
|
1607
1597
|
else {
|
|
1608
1598
|
nextCandles = stitched;
|
|
@@ -1660,13 +1650,13 @@ class MarketAdapterService {
|
|
|
1660
1650
|
}
|
|
1661
1651
|
}
|
|
1662
1652
|
if (!overlapUsed) {
|
|
1663
|
-
const sinceMs = lastTs - (cfg.nativeBackfillHours * 3600 * 1000);
|
|
1653
|
+
const sinceMs = lastTs - (Number(cfg.nativeBackfillHours) * 3600 * 1000);
|
|
1664
1654
|
const fetchResult = await deps.withRetries(() => deps.fetchNativeTradesSince(ctx.poolId, sinceMs, cfg.pageLimit, cfg.maxPages), cfg.sourceRetries, cfg.retryDelayMs, 'native incremental fetch failed');
|
|
1665
1655
|
fetchedTrades = Array.isArray(fetchResult?.trades) ? fetchResult.trades : [];
|
|
1666
1656
|
if (fetchResult?.truncated && typeof deps.logger?.warn === 'function') {
|
|
1667
1657
|
deps.logger.warn(`[market_adapter] ${bot.botKey}: native incremental history truncated (exhausted ${cfg.maxPages} pages)`);
|
|
1668
1658
|
}
|
|
1669
|
-
newTrades = this.filterTimeBasedNativeNewTrades(fetchedTrades, knownSequences, nativeLastTradeTs, lastTs, cfg.intervalSeconds);
|
|
1659
|
+
newTrades = this.filterTimeBasedNativeNewTrades(fetchedTrades, knownSequences, nativeLastTradeTs, lastTs, Number(cfg.intervalSeconds));
|
|
1670
1660
|
sourceLabel = 'native-incremental-time';
|
|
1671
1661
|
nativeOverlapCount = null;
|
|
1672
1662
|
nativePagesFetched = fetchResult?.pages || null;
|
|
@@ -1677,26 +1667,26 @@ class MarketAdapterService {
|
|
|
1677
1667
|
if (Number.isFinite(latestTradeTs))
|
|
1678
1668
|
nativeLastTradeTs = latestTradeTs;
|
|
1679
1669
|
}
|
|
1680
|
-
const incomingCandles = deps.tradesToCandles(newTrades, ctx.assetA, ctx.assetB, cfg.intervalSeconds);
|
|
1670
|
+
const incomingCandles = deps.tradesToCandles(newTrades, ctx.assetA, ctx.assetB, Number(cfg.intervalSeconds));
|
|
1681
1671
|
nextCandles = deps.mergeCandles(existingCandles, incomingCandles, {
|
|
1682
1672
|
onCollision: (existingCandle, incomingCandle) => this.buildIncrementalCandleCollision(existingCandle, incomingCandle),
|
|
1683
1673
|
});
|
|
1684
1674
|
// Fill bounded no-trade gaps from native incremental fetch. Ordinary LP
|
|
1685
1675
|
// inactivity should remain a continuous flat 1h series; very large gaps stay
|
|
1686
1676
|
// visible for Kibana repair/stale-tail handling instead of carrying stale prices.
|
|
1687
|
-
const bucketMs = Number(cfg.intervalSeconds) * 1000;
|
|
1677
|
+
const bucketMs = Number(Number(cfg.intervalSeconds)) * 1000;
|
|
1688
1678
|
const nowMs = this.getNowMs();
|
|
1689
1679
|
const currentBucketStartMs = Math.floor(Number(nowMs) / bucketMs) * bucketMs;
|
|
1690
1680
|
const latestClosedBucketTs = currentBucketStartMs - bucketMs;
|
|
1691
|
-
const earliestIncomingTs = incomingCandles.length > 0 ? incomingCandles[0][0] : null;
|
|
1692
|
-
const gapEndTs = Number.isFinite(earliestIncomingTs) && earliestIncomingTs > lastTs
|
|
1681
|
+
const earliestIncomingTs = incomingCandles.length > 0 ? Number(incomingCandles[0][0]) : null;
|
|
1682
|
+
const gapEndTs = (earliestIncomingTs != null && Number.isFinite(earliestIncomingTs) && earliestIncomingTs > lastTs)
|
|
1693
1683
|
? earliestIncomingTs
|
|
1694
1684
|
: latestClosedBucketTs + bucketMs;
|
|
1695
1685
|
const gapBuckets = Number.isFinite(gapEndTs) && gapEndTs > lastTs
|
|
1696
1686
|
? Math.round((gapEndTs - lastTs) / bucketMs) - 1
|
|
1697
1687
|
: 0;
|
|
1698
1688
|
if (gapBuckets <= trustedNoTradeGapThresholdCandles) {
|
|
1699
|
-
nextCandles = this.fillNativeIncrementalClosedGaps(nextCandles, lastTs, cfg.intervalSeconds);
|
|
1689
|
+
nextCandles = this.fillNativeIncrementalClosedGaps(nextCandles, lastTs, Number(cfg.intervalSeconds));
|
|
1700
1690
|
}
|
|
1701
1691
|
else {
|
|
1702
1692
|
const verifiedSilence = await verifyAndFillLongSilence(nextCandles, lastTs, latestClosedBucketTs, sourceLabel, incomingCandles);
|
|
@@ -1727,34 +1717,34 @@ class MarketAdapterService {
|
|
|
1727
1717
|
let kibanaGapRepairTimestamps = [];
|
|
1728
1718
|
let kibanaGapRepairAttempted = false;
|
|
1729
1719
|
let gapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
|
|
1730
|
-
? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
|
|
1720
|
+
? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
|
|
1731
1721
|
: { gapCount: 0, missingTimestamps: [] };
|
|
1732
1722
|
// Step 1: Fill gaps within the trusted no-trade threshold directly (no Kibana needed).
|
|
1733
1723
|
// The native incremental fetch already confirmed no trades for these timestamps.
|
|
1734
1724
|
if (gapAnalysis.gapCount > 0) {
|
|
1735
|
-
const filledNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, gapAnalysis.missingTimestamps, cfg.intervalSeconds, trustedNoTradeGapThresholdCandles);
|
|
1725
|
+
const filledNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, gapAnalysis.missingTimestamps, Number(Number(cfg.intervalSeconds)), trustedNoTradeGapThresholdCandles);
|
|
1736
1726
|
if (filledNoTrade.filledTimestamps.length > 0) {
|
|
1737
1727
|
nextCandles = filledNoTrade.candles;
|
|
1738
1728
|
kibanaGapRepairTimestamps = filledNoTrade.filledTimestamps.slice();
|
|
1739
1729
|
logGapRepairEvent(`[market_adapter] ${bot.botKey}: synthesized ${filledNoTrade.filledTimestamps.length} no-trade candle(s) within trusted threshold `
|
|
1740
|
-
+ `[${filledNoTrade.filledTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`);
|
|
1730
|
+
+ `[${filledNoTrade.filledTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`);
|
|
1741
1731
|
}
|
|
1742
1732
|
// Re-detect gaps — only beyond-threshold gaps remain
|
|
1743
1733
|
gapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
|
|
1744
|
-
? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
|
|
1734
|
+
? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
|
|
1745
1735
|
: { gapCount: 0, missingTimestamps: [] };
|
|
1746
1736
|
}
|
|
1747
1737
|
// Step 2: Only query Kibana for gaps beyond the trusted threshold
|
|
1748
1738
|
if (gapAnalysis.gapCount > 0 && hasKibanaSource) {
|
|
1749
|
-
const timeRange = this.buildGapRepairTimeRange(gapAnalysis.missingTimestamps, cfg.intervalSeconds, this.getGapRepairMaxHours(cfg));
|
|
1739
|
+
const timeRange = this.buildGapRepairTimeRange(gapAnalysis.missingTimestamps, Number(cfg.intervalSeconds), this.getGapRepairMaxHours(cfg));
|
|
1750
1740
|
if (timeRange) {
|
|
1751
1741
|
kibanaGapRepairAttempted = true;
|
|
1752
1742
|
logGapRepairEvent(`[market_adapter] ${bot.botKey}: ${gapAnalysis.gapCount} candle gap(s) beyond trusted threshold; `
|
|
1753
1743
|
+ `requesting Kibana repair for ${timeRange.gte} -> ${timeRange.lte} `
|
|
1754
|
-
+ `missing=[${gapAnalysis.missingTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`);
|
|
1744
|
+
+ `missing=[${gapAnalysis.missingTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`);
|
|
1755
1745
|
try {
|
|
1756
1746
|
const kibanaGapCandles = await deps.withRetries(() => fetchKibanaCandles({
|
|
1757
|
-
intervalSeconds: cfg.intervalSeconds,
|
|
1747
|
+
intervalSeconds: Number(cfg.intervalSeconds),
|
|
1758
1748
|
fillGapsToRequestedRange: false,
|
|
1759
1749
|
apiKey: null,
|
|
1760
1750
|
timeRange,
|
|
@@ -1770,19 +1760,19 @@ class MarketAdapterService {
|
|
|
1770
1760
|
kibanaGapRepairTimestamps = [...kibanaGapRepairTimestamps, ...kibanaPatchedTs];
|
|
1771
1761
|
logGapRepairEvent(`[market_adapter] ${bot.botKey}: Kibana gap repair patched ${kibanaPatchedTs.length}/${gapAnalysis.gapCount} gap(s)`
|
|
1772
1762
|
+ (kibanaPatchedTs.length > 0
|
|
1773
|
-
? ` [${kibanaPatchedTs.map((ts) => new Date(ts).toISOString()).join(', ')}]`
|
|
1763
|
+
? ` [${kibanaPatchedTs.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`
|
|
1774
1764
|
: ''));
|
|
1775
1765
|
}
|
|
1776
1766
|
else {
|
|
1777
1767
|
// Kibana returned no data — that IS verification: no trades happened.
|
|
1778
1768
|
// Synthesize no-trade candles for all gaps within the queried window.
|
|
1779
1769
|
const verifiedGapTimestamps = this.getMissingTimestampsWithinTimeRange(gapAnalysis.missingTimestamps, timeRange);
|
|
1780
|
-
const verifiedNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, verifiedGapTimestamps, cfg.intervalSeconds, verifiedGapTimestamps.length);
|
|
1770
|
+
const verifiedNoTrade = this.fillVerifiedInternalNoTradeGaps(nextCandles, verifiedGapTimestamps, Number(cfg.intervalSeconds), verifiedGapTimestamps.length);
|
|
1781
1771
|
if (verifiedNoTrade.filledTimestamps.length > 0) {
|
|
1782
1772
|
nextCandles = verifiedNoTrade.candles;
|
|
1783
1773
|
kibanaGapRepairTimestamps = [...kibanaGapRepairTimestamps, ...verifiedNoTrade.filledTimestamps];
|
|
1784
1774
|
logGapRepairEvent(`[market_adapter] ${bot.botKey}: synthesized ${verifiedNoTrade.filledTimestamps.length} no-trade candle(s) after empty Kibana repair `
|
|
1785
|
-
+ `[${verifiedNoTrade.filledTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`);
|
|
1775
|
+
+ `[${verifiedNoTrade.filledTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`);
|
|
1786
1776
|
}
|
|
1787
1777
|
else {
|
|
1788
1778
|
logGapRepairEvent(`[market_adapter] ${bot.botKey}: Kibana empty but could not synthesize gaps (missing neighbors)`, 'warn');
|
|
@@ -1794,11 +1784,11 @@ class MarketAdapterService {
|
|
|
1794
1784
|
}
|
|
1795
1785
|
}
|
|
1796
1786
|
gapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
|
|
1797
|
-
? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
|
|
1787
|
+
? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
|
|
1798
1788
|
: { gapCount: 0, missingTimestamps: [] };
|
|
1799
1789
|
if (gapAnalysis.gapCount > 0) {
|
|
1800
1790
|
logGapRepairEvent(`[market_adapter] ${bot.botKey}: ${gapAnalysis.gapCount} candle gap(s) still unresolved after Kibana repair `
|
|
1801
|
-
+ `[${gapAnalysis.missingTimestamps.map((ts) => new Date(ts).toISOString()).join(', ')}]`, 'warn');
|
|
1791
|
+
+ `[${gapAnalysis.missingTimestamps.map((ts) => new Date(Number(ts)).toISOString()).join(', ')}]`, 'warn');
|
|
1802
1792
|
}
|
|
1803
1793
|
}
|
|
1804
1794
|
// ── Historical backfill: if candle count is still insufficient for AMA warmup,
|
|
@@ -1809,13 +1799,13 @@ class MarketAdapterService {
|
|
|
1809
1799
|
const needsHistoricalBackfill = !kibanaGapRepairAttempted || gapAnalysis.gapCount > 0;
|
|
1810
1800
|
if (!kibanaBootstrapEmpty && needsHistoricalBackfill && candleShortfall > 0 && nextCandles.length > 0 && hasKibanaSource) {
|
|
1811
1801
|
const oldestTs = nextCandles[0][0];
|
|
1812
|
-
const shortfallMs = candleShortfall * cfg.intervalSeconds * 1000;
|
|
1802
|
+
const shortfallMs = candleShortfall * Number(cfg.intervalSeconds) * 1000;
|
|
1813
1803
|
const bufferMs = 24 * 3600 * 1000; // 24h buffer
|
|
1814
1804
|
const backfillStartMs = Math.max(0, oldestTs - shortfallMs - bufferMs);
|
|
1815
|
-
const backfillEndMs = oldestTs + cfg.intervalSeconds * 1000;
|
|
1805
|
+
const backfillEndMs = oldestTs + Number(cfg.intervalSeconds) * 1000;
|
|
1816
1806
|
try {
|
|
1817
1807
|
const historicalCandles = await deps.withRetries(() => fetchKibanaCandles({
|
|
1818
|
-
intervalSeconds: cfg.intervalSeconds,
|
|
1808
|
+
intervalSeconds: Number(cfg.intervalSeconds),
|
|
1819
1809
|
fillGapsToRequestedRange: false,
|
|
1820
1810
|
apiKey: null,
|
|
1821
1811
|
timeRange: {
|
|
@@ -1838,7 +1828,7 @@ class MarketAdapterService {
|
|
|
1838
1828
|
const retainedTimestamps = new Set(nextCandles.map((c) => c[0]));
|
|
1839
1829
|
const kibanaGapRepairCount = kibanaGapRepairTimestamps.filter((ts) => retainedTimestamps.has(ts)).length;
|
|
1840
1830
|
const retainedGapAnalysis = typeof deps.detectMissingCandleTimestamps === 'function'
|
|
1841
|
-
? deps.detectMissingCandleTimestamps(nextCandles, cfg.intervalSeconds)
|
|
1831
|
+
? deps.detectMissingCandleTimestamps(nextCandles, Number(cfg.intervalSeconds))
|
|
1842
1832
|
: { gapCount: 0, missingTimestamps: [] };
|
|
1843
1833
|
return {
|
|
1844
1834
|
nextCandles,
|
|
@@ -1878,16 +1868,16 @@ class MarketAdapterService {
|
|
|
1878
1868
|
kibanaBackfillCount = loadResult.kibanaBackfillCount || 0;
|
|
1879
1869
|
unresolvedGapCount = loadResult.unresolvedGapCount;
|
|
1880
1870
|
nativeRecentTradeSequences = Array.isArray(loadResult.nativeRecentTradeSequences) ? loadResult.nativeRecentTradeSequences : [];
|
|
1881
|
-
nativeLastTradeTs = Number.isFinite(loadResult.nativeLastTradeTs) ? loadResult.nativeLastTradeTs : null;
|
|
1882
|
-
nativeOverlapCount = Number.isFinite(loadResult.nativeOverlapCount) ? loadResult.nativeOverlapCount : null;
|
|
1883
|
-
nativePagesFetched = Number.isFinite(loadResult.nativePagesFetched) ? loadResult.nativePagesFetched : null;
|
|
1871
|
+
nativeLastTradeTs = Number.isFinite(loadResult.nativeLastTradeTs) ? Number(loadResult.nativeLastTradeTs) : null;
|
|
1872
|
+
nativeOverlapCount = Number.isFinite(loadResult.nativeOverlapCount) ? Number(loadResult.nativeOverlapCount) : null;
|
|
1873
|
+
nativePagesFetched = Number.isFinite(loadResult.nativePagesFetched) ? Number(loadResult.nativePagesFetched) : null;
|
|
1884
1874
|
const nowMs = this.getNowMs();
|
|
1885
|
-
({ closedCandles, currentBucketStartMs } = this.selectClosedCandles(nextCandles, cfg.intervalSeconds, nowMs));
|
|
1875
|
+
({ closedCandles, currentBucketStartMs } = this.selectClosedCandles(nextCandles, Number(cfg.intervalSeconds), nowMs));
|
|
1886
1876
|
rawLastCandle = nextCandles[nextCandles.length - 1] || [0, 0, 0, 0, 0];
|
|
1887
1877
|
rawLastCandleTs = rawLastCandle[0] || null;
|
|
1888
1878
|
latestClosedCandle = closedCandles[closedCandles.length - 1] || null;
|
|
1889
1879
|
lastClosedCandleTs = latestClosedCandle ? latestClosedCandle[0] : null;
|
|
1890
|
-
botState = this.normalizePersistedBotState(state.bots[bot.botKey], lookbackBars);
|
|
1880
|
+
botState = this.normalizePersistedBotState(state.bots[String(bot.botKey)], lookbackBars);
|
|
1891
1881
|
if (sourceMismatch) {
|
|
1892
1882
|
botState = {};
|
|
1893
1883
|
}
|
|
@@ -1941,6 +1931,26 @@ class MarketAdapterService {
|
|
|
1941
1931
|
? previousClosedCandleTs
|
|
1942
1932
|
: null;
|
|
1943
1933
|
hasNewClosedCandle = lastClosedCandleTs !== null && lastClosedCandleTs > previousClosedCandleTs;
|
|
1934
|
+
// Fields shared by the persisted bot state and the cycle result.
|
|
1935
|
+
// Built on demand so `consumedClosedCandleTs` is read after the
|
|
1936
|
+
// retry-baseline adjustment below, rather than frozen early.
|
|
1937
|
+
const buildCandleCycleFields = () => ({
|
|
1938
|
+
candleCount: nextCandles.length,
|
|
1939
|
+
analysisCandleCount: closedCandles.length,
|
|
1940
|
+
rawKeepCount,
|
|
1941
|
+
analysisKeepCount,
|
|
1942
|
+
amaWarmupBars,
|
|
1943
|
+
kibanaGapRepairCount,
|
|
1944
|
+
kibanaBackfillCount,
|
|
1945
|
+
unresolvedGapCount,
|
|
1946
|
+
nativeRecentTradeSequences,
|
|
1947
|
+
nativeLastTradeTs,
|
|
1948
|
+
nativeOverlapCount,
|
|
1949
|
+
nativePagesFetched,
|
|
1950
|
+
lastCandleTs: rawLastCandleTs,
|
|
1951
|
+
rawLastCandleTs,
|
|
1952
|
+
lastClosedCandleTs: consumedClosedCandleTs,
|
|
1953
|
+
});
|
|
1944
1954
|
const candlePayload = {
|
|
1945
1955
|
meta: {
|
|
1946
1956
|
updatedAt: nowIso,
|
|
@@ -1949,7 +1959,7 @@ class MarketAdapterService {
|
|
|
1949
1959
|
marketSource,
|
|
1950
1960
|
assetA: ctx.assetA,
|
|
1951
1961
|
assetB: ctx.assetB,
|
|
1952
|
-
intervalSeconds: cfg.intervalSeconds,
|
|
1962
|
+
intervalSeconds: Number(cfg.intervalSeconds),
|
|
1953
1963
|
candleCount: nextCandles.length,
|
|
1954
1964
|
analysisCandleCount: closedCandles.length,
|
|
1955
1965
|
rawKeepCount,
|
|
@@ -1983,28 +1993,14 @@ class MarketAdapterService {
|
|
|
1983
1993
|
const triggerSuppressedReason = staleData
|
|
1984
1994
|
? 'stale_candle_data'
|
|
1985
1995
|
: 'waiting_for_new_closed_candle';
|
|
1986
|
-
state.bots[bot.botKey] = {
|
|
1996
|
+
state.bots[String(bot.botKey)] = {
|
|
1987
1997
|
...botState,
|
|
1988
1998
|
botName: bot.name,
|
|
1989
1999
|
botKey: bot.botKey,
|
|
1990
2000
|
poolId: ctx.poolId,
|
|
1991
2001
|
marketSource,
|
|
1992
2002
|
candleFile: deps.path.relative(deps.root, filePath),
|
|
1993
|
-
|
|
1994
|
-
analysisCandleCount: closedCandles.length,
|
|
1995
|
-
rawKeepCount,
|
|
1996
|
-
analysisKeepCount,
|
|
1997
|
-
amaWarmupBars,
|
|
1998
|
-
kibanaGapRepairCount,
|
|
1999
|
-
kibanaBackfillCount,
|
|
2000
|
-
unresolvedGapCount,
|
|
2001
|
-
nativeRecentTradeSequences,
|
|
2002
|
-
nativeLastTradeTs,
|
|
2003
|
-
nativeOverlapCount,
|
|
2004
|
-
nativePagesFetched,
|
|
2005
|
-
lastCandleTs: rawLastCandleTs,
|
|
2006
|
-
rawLastCandleTs,
|
|
2007
|
-
lastClosedCandleTs: consumedClosedCandleTs,
|
|
2003
|
+
...buildCandleCycleFields(),
|
|
2008
2004
|
lastCycleSource: sourceLabel,
|
|
2009
2005
|
lastCycleAt: nowIso,
|
|
2010
2006
|
staleData,
|
|
@@ -2016,27 +2012,13 @@ class MarketAdapterService {
|
|
|
2016
2012
|
dryRunMessages,
|
|
2017
2013
|
source: sourceLabel,
|
|
2018
2014
|
marketSource,
|
|
2019
|
-
|
|
2020
|
-
analysisCandleCount: closedCandles.length,
|
|
2021
|
-
rawKeepCount,
|
|
2022
|
-
analysisKeepCount,
|
|
2023
|
-
amaWarmupBars,
|
|
2024
|
-
kibanaGapRepairCount,
|
|
2025
|
-
kibanaBackfillCount,
|
|
2026
|
-
unresolvedGapCount,
|
|
2027
|
-
nativeRecentTradeSequences,
|
|
2028
|
-
nativeLastTradeTs,
|
|
2029
|
-
nativeOverlapCount,
|
|
2030
|
-
nativePagesFetched,
|
|
2015
|
+
...buildCandleCycleFields(),
|
|
2031
2016
|
thresholdPercent: botThreshold,
|
|
2032
2017
|
staleData,
|
|
2033
2018
|
staleAgeHours,
|
|
2034
2019
|
triggerSuppressedReason,
|
|
2035
2020
|
poolId: ctx.poolId,
|
|
2036
2021
|
candleFile: deps.path.relative(deps.root, filePath),
|
|
2037
|
-
lastCandleTs: rawLastCandleTs,
|
|
2038
|
-
rawLastCandleTs,
|
|
2039
|
-
lastClosedCandleTs: consumedClosedCandleTs,
|
|
2040
2022
|
amaConfig: {
|
|
2041
2023
|
erPeriod: botAma.erPeriod,
|
|
2042
2024
|
fastPeriod: botAma.fastPeriod,
|
|
@@ -2105,10 +2087,10 @@ class MarketAdapterService {
|
|
|
2105
2087
|
closes,
|
|
2106
2088
|
amaValues,
|
|
2107
2089
|
lookbackBars,
|
|
2108
|
-
botAma,
|
|
2090
|
+
botAma: botAma,
|
|
2109
2091
|
weightVariance,
|
|
2110
2092
|
nowIso,
|
|
2111
|
-
cfg,
|
|
2093
|
+
cfg: cfg,
|
|
2112
2094
|
bot,
|
|
2113
2095
|
atrPeriod,
|
|
2114
2096
|
});
|
|
@@ -2117,7 +2099,7 @@ class MarketAdapterService {
|
|
|
2117
2099
|
weights = dwResult.weights;
|
|
2118
2100
|
dynamicWeightsPayload = dwResult.dynamicWeightsPayload;
|
|
2119
2101
|
}
|
|
2120
|
-
const amaSlopeResetDetails = this.buildAmaSlopeResetDetails(amaSlope, previousGridResetAmaSlope, cfg);
|
|
2102
|
+
const amaSlopeResetDetails = this.buildAmaSlopeResetDetails(amaSlope ?? {}, previousGridResetAmaSlope, cfg);
|
|
2121
2103
|
const amaSlopeDeltaPercent = amaSlopeResetDetails.deltaPercent;
|
|
2122
2104
|
const amaSlopeThresholdPercent = amaSlopeResetDetails.thresholdPercent;
|
|
2123
2105
|
// 4. Advisory collateral-ratio hint only; execution is owned by the debt runtime.
|
|
@@ -2172,13 +2154,6 @@ class MarketAdapterService {
|
|
|
2172
2154
|
// trigger/snapshot write happened on a stale-but-new cycle.
|
|
2173
2155
|
triggerSuppressedReason = 'stale_candle_data';
|
|
2174
2156
|
}
|
|
2175
|
-
// Slope-delta persistence gate (trigger B). Advances only on actionable
|
|
2176
|
-
// cycles; any successful reset clears it via advanceTriggeredBotState.
|
|
2177
|
-
const amaSlopePersistence = (!staleData && !hasUnresolvedCandleGaps)
|
|
2178
|
-
? this.advanceAmaSlopePersistence(amaSlopeResetDetails, cfg, botState)
|
|
2179
|
-
: { shouldTrigger: false, persistBars: this.resolveAmaSlopePersistBars(cfg) };
|
|
2180
|
-
const amaSlopeShouldTrigger = amaSlopePersistence.shouldTrigger;
|
|
2181
|
-
const amaSlopePersistBars = amaSlopePersistence.persistBars;
|
|
2182
2157
|
const buildDynamicGridOptions = (options = {}) => {
|
|
2183
2158
|
const payload = {
|
|
2184
2159
|
gridCenterPrice: options.gridCenterPrice ?? null, // explicit baseline if provided
|
|
@@ -2356,7 +2331,19 @@ class MarketAdapterService {
|
|
|
2356
2331
|
}
|
|
2357
2332
|
}
|
|
2358
2333
|
}
|
|
2359
|
-
|
|
2334
|
+
// Slope-delta persistence gate (trigger B). Advance only when this
|
|
2335
|
+
// cycle can actually act on it — after trigger A (price/Drift) and
|
|
2336
|
+
// bootstrap have had their chance, and only for whitelisted bots.
|
|
2337
|
+
// Mirrors grid_reset_sim, where the slope candidate is evaluated
|
|
2338
|
+
// only in the price trigger's `else` branch, and stops the counter
|
|
2339
|
+
// accumulating for bots that never use the slope trigger.
|
|
2340
|
+
const amaSlopeGateActive = !triggered && !triggerSuppressedReason && isGridRangeScalingWhitelisted;
|
|
2341
|
+
const amaSlopePersistence = amaSlopeGateActive
|
|
2342
|
+
? this.advanceAmaSlopePersistence(amaSlopeResetDetails, cfg, botState)
|
|
2343
|
+
: { shouldTrigger: false, persistBars: this.resolveAmaSlopePersistBars(cfg) };
|
|
2344
|
+
const amaSlopeShouldTrigger = amaSlopePersistence.shouldTrigger;
|
|
2345
|
+
const amaSlopePersistBars = amaSlopePersistence.persistBars;
|
|
2346
|
+
if (amaSlopeGateActive && amaSlopeShouldTrigger) {
|
|
2360
2347
|
const amaSlopePersisted = persistDynamicGridSnapshot(centerPrice);
|
|
2361
2348
|
if (!amaSlopePersisted) {
|
|
2362
2349
|
triggerSuppressedReason = 'ama_slope_persist_failed';
|
|
@@ -2453,28 +2440,14 @@ class MarketAdapterService {
|
|
|
2453
2440
|
? (botState.amaSlopeThresholdPercent ?? amaSlopeThresholdPercent ?? null)
|
|
2454
2441
|
: (amaSlopeThresholdPercent ?? botState.amaSlopeThresholdPercent ?? null);
|
|
2455
2442
|
const stateGridRangeScalingAmaSlope = botState.gridRangeScalingAmaSlope || previousGridResetAmaSlope || null;
|
|
2456
|
-
state.bots[bot.botKey] = {
|
|
2443
|
+
state.bots[String(bot.botKey)] = {
|
|
2457
2444
|
...botState,
|
|
2458
2445
|
botName: bot.name,
|
|
2459
2446
|
botKey: bot.botKey,
|
|
2460
2447
|
poolId: ctx.poolId,
|
|
2461
2448
|
marketSource,
|
|
2462
2449
|
candleFile: deps.path.relative(deps.root, filePath),
|
|
2463
|
-
|
|
2464
|
-
analysisCandleCount: analysisCandles.length,
|
|
2465
|
-
rawKeepCount,
|
|
2466
|
-
analysisKeepCount,
|
|
2467
|
-
amaWarmupBars,
|
|
2468
|
-
kibanaGapRepairCount,
|
|
2469
|
-
kibanaBackfillCount,
|
|
2470
|
-
unresolvedGapCount,
|
|
2471
|
-
nativeRecentTradeSequences,
|
|
2472
|
-
nativeLastTradeTs,
|
|
2473
|
-
nativeOverlapCount,
|
|
2474
|
-
nativePagesFetched,
|
|
2475
|
-
lastCandleTs: rawLastCandleTs,
|
|
2476
|
-
rawLastCandleTs,
|
|
2477
|
-
lastClosedCandleTs: consumedClosedCandleTs,
|
|
2450
|
+
...buildCandleCycleFields(),
|
|
2478
2451
|
lastAmaPrice: amaPrice,
|
|
2479
2452
|
amaCenterPrice: Number(botState.amaCenterPrice || 0) > 0
|
|
2480
2453
|
? Number(botState.amaCenterPrice)
|
|
@@ -2528,19 +2501,8 @@ class MarketAdapterService {
|
|
|
2528
2501
|
dryRunMessages,
|
|
2529
2502
|
source: sourceLabel,
|
|
2530
2503
|
marketSource,
|
|
2531
|
-
intervalSeconds: cfg.intervalSeconds,
|
|
2532
|
-
|
|
2533
|
-
analysisCandleCount: analysisCandles.length,
|
|
2534
|
-
rawKeepCount,
|
|
2535
|
-
analysisKeepCount,
|
|
2536
|
-
amaWarmupBars,
|
|
2537
|
-
kibanaGapRepairCount,
|
|
2538
|
-
kibanaBackfillCount,
|
|
2539
|
-
unresolvedGapCount,
|
|
2540
|
-
nativeRecentTradeSequences,
|
|
2541
|
-
nativeLastTradeTs,
|
|
2542
|
-
nativeOverlapCount,
|
|
2543
|
-
nativePagesFetched,
|
|
2504
|
+
intervalSeconds: Number(cfg.intervalSeconds),
|
|
2505
|
+
...buildCandleCycleFields(),
|
|
2544
2506
|
amaPrice,
|
|
2545
2507
|
previousCenterPrice,
|
|
2546
2508
|
deltaPercent,
|
|
@@ -2555,7 +2517,7 @@ class MarketAdapterService {
|
|
|
2555
2517
|
triggerSuppressedReason,
|
|
2556
2518
|
weights: canExposeDynamicWeights ? weights : null,
|
|
2557
2519
|
collateralRecommendation,
|
|
2558
|
-
amaSlope: amaSlope || botState.amaSlope || null,
|
|
2520
|
+
amaSlope: (amaSlope || botState.amaSlope || null),
|
|
2559
2521
|
amaSlopeDeltaPercent: Number.isFinite(amaSlopeDeltaPercent)
|
|
2560
2522
|
? amaSlopeDeltaPercent
|
|
2561
2523
|
: botState.amaSlopeDeltaPercent ?? null,
|
|
@@ -2568,9 +2530,6 @@ class MarketAdapterService {
|
|
|
2568
2530
|
hasExplicitBaseWeights,
|
|
2569
2531
|
poolId: ctx.poolId,
|
|
2570
2532
|
candleFile: deps.path.relative(deps.root, filePath),
|
|
2571
|
-
lastCandleTs: rawLastCandleTs,
|
|
2572
|
-
rawLastCandleTs,
|
|
2573
|
-
lastClosedCandleTs: consumedClosedCandleTs,
|
|
2574
2533
|
lastClosedCandleClose: Number(latestClosedCandle?.[4]),
|
|
2575
2534
|
centerPrice,
|
|
2576
2535
|
amaConfig: {
|