dexbot 1.6.7 → 1.6.9
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 +73 -1
- package/README.md +3 -3
- package/analysis/README.md +2 -3
- package/analysis/tradingview/README.md +78 -1
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
- 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/tradingview/analyze_tradingview.d.ts +4 -0
- package/dist/analysis/tradingview/analyze_tradingview.js +55 -0
- package/dist/analysis/tradingview/grid_reset_config.d.ts +61 -0
- package/dist/analysis/tradingview/grid_reset_config.js +235 -0
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +67 -0
- package/dist/analysis/tradingview/grid_reset_sim.js +307 -0
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +419 -3
- package/dist/dexbot.js +55 -16
- package/dist/market_adapter/core/market_adapter_service.d.ts +81 -1
- package/dist/market_adapter/core/market_adapter_service.js +239 -20
- package/dist/market_adapter/core/signals/hurst_analyzer.d.ts +10 -1
- package/dist/market_adapter/core/signals/hurst_analyzer.js +40 -18
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts +26 -2
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js +132 -29
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +8 -1
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +5 -1
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +61 -3
- package/dist/market_adapter/core/strategies/regime_gate.js +207 -7
- package/dist/market_adapter/inputs/window_cache.d.ts +97 -19
- package/dist/market_adapter/inputs/window_cache.js +302 -48
- package/dist/market_adapter/interval_utils.d.ts +18 -1
- package/dist/market_adapter/interval_utils.js +31 -1
- package/dist/market_adapter/market_adapter.d.ts +158 -2
- package/dist/market_adapter/market_adapter.js +399 -65
- package/dist/market_adapter/test_helpers.d.ts +2 -2
- package/dist/market_adapter/test_helpers.js +2 -2
- package/dist/market_adapter/utils/file_json_cache.d.ts +29 -0
- package/dist/market_adapter/utils/file_json_cache.js +106 -0
- package/dist/modules/account_bots.js +10 -0
- package/dist/modules/account_orders.d.ts +24 -2
- package/dist/modules/account_orders.js +41 -4
- package/dist/modules/bot_settings.js +10 -1
- package/dist/modules/config.d.ts +7 -0
- package/dist/modules/config.js +2 -0
- package/dist/modules/constants.d.ts +16 -4
- package/dist/modules/constants.js +144 -38
- package/dist/modules/dexbot_class.d.ts +6 -76
- package/dist/modules/dexbot_class.js +0 -32
- package/dist/modules/dexbot_cow_runtime.d.ts +3 -58
- package/dist/modules/dexbot_cow_runtime.js +4 -87
- package/dist/modules/dexbot_maintenance_runtime.d.ts +15 -1
- package/dist/modules/dexbot_maintenance_runtime.js +59 -11
- package/dist/modules/dexbot_startup_runtime.js +73 -20
- package/dist/modules/dexbot_state_recovery.d.ts +6 -0
- package/dist/modules/dexbot_state_recovery.js +21 -0
- package/dist/modules/order/async_lock.d.ts +8 -0
- package/dist/modules/order/async_lock.js +15 -0
- package/dist/modules/order/genesis_policy.d.ts +162 -0
- package/dist/modules/order/genesis_policy.js +267 -0
- package/dist/modules/order/grid.js +172 -160
- package/dist/modules/order/grid_reconcile.d.ts +9 -0
- package/dist/modules/order/grid_reconcile.js +13 -4
- package/dist/modules/order/grid_reconcile_internal.js +2 -2
- package/dist/modules/order/manager.d.ts +4 -0
- package/dist/modules/order/manager.js +14 -1
- package/dist/modules/order/sync_engine.d.ts +19 -0
- package/dist/modules/order/sync_engine.js +284 -344
- package/dist/modules/order/utils/math.d.ts +22 -1
- package/dist/modules/order/utils/math.js +64 -1
- package/dist/modules/order/utils/order.d.ts +43 -58
- package/dist/modules/order/utils/order.js +220 -197
- package/dist/modules/order/utils/system.js +8 -1
- package/dist/modules/paths.d.ts +1 -0
- package/dist/modules/paths.js +1 -0
- package/dist/modules/version_notice.d.ts +311 -0
- package/dist/modules/version_notice.js +709 -0
- package/dist/pm2.js +16 -0
- package/dist/unlock.js +28 -0
- package/docs/BITSHARES_ONBOARDING.md +8 -1
- package/docs/COW_INVARIANTS.md +3 -2
- package/docs/DEXBOT_COMPARISON.md +4 -4
- package/docs/EVOLUTION.md +22 -20
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_PRICE_INVARIANT.md +149 -31
- package/docs/GRID_RECALCULATION.md +18 -2
- package/docs/README.md +3 -1
- package/docs/WORKFLOW.md +16 -5
- package/market_adapter/README.md +29 -1
- package/modules/README.md +18 -1
- package/package.json +13 -5
- package/scripts/README.md +28 -2
- package/scripts/clear-all.sh +13 -4
- package/scripts/clear-logs.sh +13 -4
- package/scripts/clear-market-adapter.sh +6 -0
- package/scripts/clear-orders.sh +5 -0
- package/scripts/lib/dexbot-paths.sh +108 -0
- package/tests/README.md +11 -3
- package/analysis/account_resolver.ts +0 -161
- package/analysis/ama_fitting/analyze_ama_price_changes.ts +0 -155
- package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +0 -404
- package/analysis/ama_fitting/calibrate_convergence_er.ts +0 -201
- package/analysis/ama_fitting/fetch_lp_candles.ts +0 -184
- package/analysis/ama_fitting/generate_unified_comparison_chart.ts +0 -232
- package/analysis/ama_fitting/optimizer_high_resolution.ts +0 -802
- package/analysis/analyze_dynamic_weight.ts +0 -243
- package/analysis/analyze_kalman.ts +0 -157
- package/analysis/analyze_regime.ts +0 -158
- package/analysis/analyze_regime_windows.ts +0 -470
- package/analysis/analyze_risk_profile.ts +0 -199
- package/analysis/analyze_trade_heatmap.ts +0 -362
- package/analysis/analyze_volatility.ts +0 -182
- package/analysis/bot_fitting/backtest_ama_sweep.ts +0 -934
- package/analysis/bot_fitting/backtest_bot_fitting.ts +0 -861
- package/analysis/bot_fitting/shared_utils.ts +0 -52
- package/analysis/bot_key_utils.ts +0 -426
- package/analysis/bot_usage/discover_bot_accounts.ts +0 -635
- package/analysis/bot_usage/kibana_bot_queries.ts +0 -211
- package/analysis/chain_pool.ts +0 -47
- package/analysis/chart_css.ts +0 -62
- package/analysis/chart_ui.ts +0 -105
- package/analysis/chart_utils.ts +0 -210
- package/analysis/fills_source.ts +0 -228
- package/analysis/grid_correction_check.ts +0 -786
- package/analysis/math_utils.ts +0 -53
- package/analysis/price_sources.ts +0 -136
- package/analysis/resolve_bot_accounts.ts +0 -199
- package/analysis/resolve_source.ts +0 -99
- package/analysis/results/ama_sweep_results_lp_pool_133_1h.json +0 -2455
- package/analysis/results/bot_fitting_results_lp_pool_133_1h.json +0 -218
- package/analysis/trade_profitability.ts +0 -1335
- package/analysis/tradingview/analyze_tradingview.ts +0 -280
- package/analysis/tradingview/h-bts_tradingview.html +0 -1570
- package/analysis/tradingview/t-bts_tradingview.html +0 -1570
- package/analysis/tradingview/tradingview_uplot_chart_generator.ts +0 -3268
- package/analysis/trend_detection/dynamic_weight_chart_generator.ts +0 -1481
- package/analysis/trend_detection/hurst_analyzer.ts +0 -7
- package/analysis/trend_detection/kalman_chart_generator.ts +0 -398
- package/analysis/trend_detection/kalman_trend_analyzer.ts +0 -9
- package/analysis/trend_detection/kalman_velocity_smoothing.ts +0 -7
- package/analysis/trend_detection/package.json +0 -23
- package/analysis/trend_detection/permutation_entropy_analyzer.ts +0 -7
- package/analysis/trend_detection/regime_chart_generator.ts +0 -338
- package/analysis/trend_detection/tests/test_kalman_trend.ts +0 -153
- package/analysis/trend_detection/tests/test_kalman_velocity_smoothing.ts +0 -64
- package/analysis/trend_detection/volatility_chart_generator.ts +0 -654
- package/analysis/tsconfig.json +0 -29
- package/claw/tests/package.json +0 -3
- package/claw/tests/test_claw_bridge.ts +0 -570
- package/claw/tests/test_claw_catalog_and_credentials.ts +0 -156
- package/claw/tests/test_claw_chain_layer.ts +0 -739
- package/claw/tests/test_claw_data_flow.ts +0 -525
- package/claw/tests/test_claw_domain_logic.ts +0 -471
- package/claw/tests/test_claw_manifest_and_matrix.ts +0 -222
- package/claw/tests/test_claw_mcp_transport.ts +0 -243
- package/claw/tests/test_claw_regressions.ts +0 -711
- package/claw/tests/test_claw_skill_generation.ts +0 -103
- package/claw/tests/test_claw_state_store.ts +0 -44
- package/claw/tests/test_dexbot_profiles.ts +0 -654
- package/claw/tests/test_memu_bridge.ts +0 -189
- package/claw/tests/test_nullclaw_tmp_integration.ts +0 -57
- package/claw/tests/test_position_health.ts +0 -343
- package/claw/tests/test_position_manager.ts +0 -429
- package/claw/tests/test_position_manager_watch_health.ts +0 -100
- package/claw/tests/test_short_mpa_strategy.ts +0 -232
- package/dist/analysis/account_resolver.d.ts.map +0 -1
- package/dist/analysis/account_resolver.js.map +0 -1
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +0 -1
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +0 -1
- package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +0 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +0 -1
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +0 -1
- package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +0 -1
- package/dist/analysis/analyze_dynamic_weight.d.ts.map +0 -1
- package/dist/analysis/analyze_dynamic_weight.js.map +0 -1
- package/dist/analysis/analyze_kalman.d.ts.map +0 -1
- package/dist/analysis/analyze_kalman.js.map +0 -1
- package/dist/analysis/analyze_regime.d.ts.map +0 -1
- package/dist/analysis/analyze_regime.js.map +0 -1
- package/dist/analysis/analyze_regime_windows.d.ts.map +0 -1
- package/dist/analysis/analyze_regime_windows.js.map +0 -1
- package/dist/analysis/analyze_risk_profile.d.ts.map +0 -1
- package/dist/analysis/analyze_risk_profile.js.map +0 -1
- package/dist/analysis/analyze_trade_heatmap.d.ts.map +0 -1
- package/dist/analysis/analyze_trade_heatmap.js.map +0 -1
- package/dist/analysis/analyze_volatility.d.ts.map +0 -1
- package/dist/analysis/analyze_volatility.js.map +0 -1
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +0 -1
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +0 -1
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +0 -1
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +0 -1
- package/dist/analysis/bot_fitting/shared_utils.d.ts.map +0 -1
- package/dist/analysis/bot_fitting/shared_utils.js.map +0 -1
- package/dist/analysis/bot_key_utils.d.ts.map +0 -1
- package/dist/analysis/bot_key_utils.js.map +0 -1
- package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +0 -1
- package/dist/analysis/bot_usage/discover_bot_accounts.js.map +0 -1
- package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +0 -1
- package/dist/analysis/bot_usage/kibana_bot_queries.js.map +0 -1
- package/dist/analysis/chain_pool.d.ts.map +0 -1
- package/dist/analysis/chain_pool.js.map +0 -1
- package/dist/analysis/chart_css.d.ts.map +0 -1
- package/dist/analysis/chart_css.js.map +0 -1
- package/dist/analysis/chart_ui.d.ts.map +0 -1
- package/dist/analysis/chart_ui.js.map +0 -1
- package/dist/analysis/chart_utils.d.ts.map +0 -1
- package/dist/analysis/chart_utils.js.map +0 -1
- package/dist/analysis/fills_source.d.ts.map +0 -1
- package/dist/analysis/fills_source.js.map +0 -1
- package/dist/analysis/grid_correction_check.d.ts.map +0 -1
- package/dist/analysis/grid_correction_check.js.map +0 -1
- package/dist/analysis/math_utils.d.ts.map +0 -1
- package/dist/analysis/math_utils.js.map +0 -1
- package/dist/analysis/price_sources.d.ts.map +0 -1
- package/dist/analysis/price_sources.js.map +0 -1
- package/dist/analysis/resolve_bot_accounts.d.ts.map +0 -1
- package/dist/analysis/resolve_bot_accounts.js.map +0 -1
- package/dist/analysis/resolve_source.d.ts.map +0 -1
- package/dist/analysis/resolve_source.js.map +0 -1
- package/dist/analysis/trade_profitability.d.ts.map +0 -1
- package/dist/analysis/trade_profitability.js.map +0 -1
- package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +0 -1
- package/dist/analysis/tradingview/analyze_tradingview.js.map +0 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +0 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +0 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +0 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +0 -1
- package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +0 -1
- package/dist/analysis/trend_detection/hurst_analyzer.js.map +0 -1
- package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +0 -1
- package/dist/analysis/trend_detection/kalman_chart_generator.js.map +0 -1
- package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +0 -1
- package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +0 -1
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +0 -1
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +0 -1
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +0 -1
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +0 -1
- package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +0 -1
- package/dist/analysis/trend_detection/regime_chart_generator.js.map +0 -1
- package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +0 -2
- package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +0 -1
- package/dist/analysis/trend_detection/tests/test_kalman_trend.js +0 -128
- package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +0 -1
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +0 -2
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +0 -1
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +0 -37
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +0 -1
- package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +0 -1
- package/dist/analysis/trend_detection/volatility_chart_generator.js.map +0 -1
- package/dist/bot.d.ts.map +0 -1
- package/dist/bot.js.map +0 -1
- package/dist/credential-daemon.d.ts.map +0 -1
- package/dist/credential-daemon.js.map +0 -1
- package/dist/dexbot.d.ts.map +0 -1
- package/dist/dexbot.js.map +0 -1
- package/dist/market_adapter/ama_signal_runner.d.ts.map +0 -1
- package/dist/market_adapter/ama_signal_runner.js.map +0 -1
- package/dist/market_adapter/candle_utils.d.ts.map +0 -1
- package/dist/market_adapter/candle_utils.js.map +0 -1
- package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +0 -1
- package/dist/market_adapter/core/asymmetric_bounds.js.map +0 -1
- package/dist/market_adapter/core/config_normalizers.d.ts.map +0 -1
- package/dist/market_adapter/core/config_normalizers.js.map +0 -1
- package/dist/market_adapter/core/kibana_candles.d.ts.map +0 -1
- package/dist/market_adapter/core/kibana_candles.js.map +0 -1
- package/dist/market_adapter/core/kibana_client.d.ts.map +0 -1
- package/dist/market_adapter/core/kibana_client.js.map +0 -1
- package/dist/market_adapter/core/kibana_market_candles.d.ts.map +0 -1
- package/dist/market_adapter/core/kibana_market_candles.js.map +0 -1
- package/dist/market_adapter/core/market_adapter_service.d.ts.map +0 -1
- package/dist/market_adapter/core/market_adapter_service.js.map +0 -1
- package/dist/market_adapter/core/signals/hurst_analyzer.d.ts.map +0 -1
- package/dist/market_adapter/core/signals/hurst_analyzer.js.map +0 -1
- package/dist/market_adapter/core/signals/kalman_trend_analyzer.d.ts.map +0 -1
- package/dist/market_adapter/core/signals/kalman_trend_analyzer.js.map +0 -1
- package/dist/market_adapter/core/signals/kalman_velocity_smoothing.d.ts.map +0 -1
- package/dist/market_adapter/core/signals/kalman_velocity_smoothing.js.map +0 -1
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts.map +0 -1
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js.map +0 -1
- package/dist/market_adapter/core/strategies/ama.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/ama.js.map +0 -1
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/ama_slope_model.js.map +0 -1
- package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/atr/calculator.js.map +0 -1
- package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/collateral_manager.js.map +0 -1
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js.map +0 -1
- package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/regime_gate.js.map +0 -1
- package/dist/market_adapter/core/strategies/regime_interp.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/regime_interp.js.map +0 -1
- package/dist/market_adapter/core/strategies/volatility_shift.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/volatility_shift.js.map +0 -1
- package/dist/market_adapter/inputs/fetch_book_data.d.ts.map +0 -1
- package/dist/market_adapter/inputs/fetch_book_data.js.map +0 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +0 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +0 -1
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +0 -1
- package/dist/market_adapter/inputs/fetch_lp_data.js.map +0 -1
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts.map +0 -1
- package/dist/market_adapter/inputs/kibana_feed_source.js.map +0 -1
- package/dist/market_adapter/inputs/kibana_source.d.ts.map +0 -1
- package/dist/market_adapter/inputs/kibana_source.js.map +0 -1
- package/dist/market_adapter/inputs/window_cache.d.ts.map +0 -1
- package/dist/market_adapter/inputs/window_cache.js.map +0 -1
- package/dist/market_adapter/interval_utils.d.ts.map +0 -1
- package/dist/market_adapter/interval_utils.js.map +0 -1
- package/dist/market_adapter/log_format.d.ts.map +0 -1
- package/dist/market_adapter/log_format.js.map +0 -1
- package/dist/market_adapter/lp_chart_core.d.ts.map +0 -1
- package/dist/market_adapter/lp_chart_core.js.map +0 -1
- package/dist/market_adapter/lp_chart_runner.d.ts.map +0 -1
- package/dist/market_adapter/lp_chart_runner.js.map +0 -1
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +0 -1
- package/dist/market_adapter/lp_chart_strategy_loader.js.map +0 -1
- package/dist/market_adapter/market_adapter.d.ts.map +0 -1
- package/dist/market_adapter/market_adapter.js.map +0 -1
- package/dist/market_adapter/test_helpers.d.ts.map +0 -1
- package/dist/market_adapter/test_helpers.js.map +0 -1
- package/dist/market_adapter/utils/adapter_client.d.ts.map +0 -1
- package/dist/market_adapter/utils/adapter_client.js.map +0 -1
- package/dist/market_adapter/utils/atomic_write.d.ts.map +0 -1
- package/dist/market_adapter/utils/atomic_write.js.map +0 -1
- package/dist/market_adapter/utils/chain.d.ts.map +0 -1
- package/dist/market_adapter/utils/chain.js.map +0 -1
- package/dist/market_adapter/utils/data_discovery.d.ts.map +0 -1
- package/dist/market_adapter/utils/data_discovery.js.map +0 -1
- package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +0 -1
- package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +0 -1
- package/dist/market_adapter/utils/file_lock.d.ts.map +0 -1
- package/dist/market_adapter/utils/file_lock.js.map +0 -1
- package/dist/market_adapter/utils/native_history.d.ts.map +0 -1
- package/dist/market_adapter/utils/native_history.js.map +0 -1
- package/dist/modules/account_bots.d.ts.map +0 -1
- package/dist/modules/account_bots.js.map +0 -1
- package/dist/modules/account_orders.d.ts.map +0 -1
- package/dist/modules/account_orders.js.map +0 -1
- package/dist/modules/authority_resolver.d.ts.map +0 -1
- package/dist/modules/authority_resolver.js.map +0 -1
- package/dist/modules/bitshares-native/chain_client.d.ts.map +0 -1
- package/dist/modules/bitshares-native/chain_client.js.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc.js.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +0 -1
- package/dist/modules/bitshares-native/index.d.ts.map +0 -1
- package/dist/modules/bitshares-native/index.js.map +0 -1
- package/dist/modules/bitshares-native/lru_cache.d.ts.map +0 -1
- package/dist/modules/bitshares-native/lru_cache.js.map +0 -1
- package/dist/modules/bitshares-native/resolvers.d.ts.map +0 -1
- package/dist/modules/bitshares-native/resolvers.js.map +0 -1
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +0 -1
- package/dist/modules/bitshares-native/serial/chain_constants.js.map +0 -1
- package/dist/modules/bitshares-native/serial/index.d.ts.map +0 -1
- package/dist/modules/bitshares-native/serial/index.js.map +0 -1
- package/dist/modules/bitshares-native/serial/operations.d.ts.map +0 -1
- package/dist/modules/bitshares-native/serial/operations.js.map +0 -1
- package/dist/modules/bitshares-native/serial/serializer.d.ts.map +0 -1
- package/dist/modules/bitshares-native/serial/serializer.js.map +0 -1
- package/dist/modules/bitshares-native/serial/types.d.ts.map +0 -1
- package/dist/modules/bitshares-native/serial/types.js.map +0 -1
- package/dist/modules/bitshares-native/signing_client.d.ts.map +0 -1
- package/dist/modules/bitshares-native/signing_client.js.map +0 -1
- package/dist/modules/bitshares-native/subscriptions.d.ts.map +0 -1
- package/dist/modules/bitshares-native/subscriptions.js.map +0 -1
- package/dist/modules/bitshares-native/transport.d.ts.map +0 -1
- package/dist/modules/bitshares-native/transport.js.map +0 -1
- package/dist/modules/bitshares-native/tx/builder.d.ts.map +0 -1
- package/dist/modules/bitshares-native/tx/builder.js.map +0 -1
- package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +0 -1
- package/dist/modules/bitshares-native/tx/tx_cache.js.map +0 -1
- package/dist/modules/bitshares_client.d.ts.map +0 -1
- package/dist/modules/bitshares_client.js.map +0 -1
- package/dist/modules/bot_defaults.d.ts.map +0 -1
- package/dist/modules/bot_defaults.js.map +0 -1
- package/dist/modules/bot_settings.d.ts.map +0 -1
- package/dist/modules/bot_settings.js.map +0 -1
- package/dist/modules/bots_file_lock.d.ts.map +0 -1
- package/dist/modules/bots_file_lock.js.map +0 -1
- package/dist/modules/broadcast_failure.d.ts.map +0 -1
- package/dist/modules/broadcast_failure.js.map +0 -1
- package/dist/modules/chain_keys.d.ts.map +0 -1
- package/dist/modules/chain_keys.js.map +0 -1
- package/dist/modules/chain_orders.d.ts.map +0 -1
- package/dist/modules/chain_orders.js.map +0 -1
- package/dist/modules/cli_colors.d.ts.map +0 -1
- package/dist/modules/cli_colors.js.map +0 -1
- package/dist/modules/cli_start_onboarding.d.ts.map +0 -1
- package/dist/modules/cli_start_onboarding.js.map +0 -1
- package/dist/modules/cli_start_output.d.ts.map +0 -1
- package/dist/modules/cli_start_output.js.map +0 -1
- package/dist/modules/config.d.ts.map +0 -1
- package/dist/modules/config.js.map +0 -1
- package/dist/modules/constants.d.ts.map +0 -1
- package/dist/modules/constants.js.map +0 -1
- package/dist/modules/cr_planner.d.ts.map +0 -1
- package/dist/modules/cr_planner.js.map +0 -1
- package/dist/modules/credential_policy.d.ts.map +0 -1
- package/dist/modules/credential_policy.js.map +0 -1
- package/dist/modules/credential_runtime.d.ts.map +0 -1
- package/dist/modules/credential_runtime.js.map +0 -1
- package/dist/modules/credential_session_cache.d.ts.map +0 -1
- package/dist/modules/credential_session_cache.js.map +0 -1
- package/dist/modules/credit_pricing.d.ts.map +0 -1
- package/dist/modules/credit_pricing.js.map +0 -1
- package/dist/modules/credit_runtime.d.ts.map +0 -1
- package/dist/modules/credit_runtime.js.map +0 -1
- package/dist/modules/crypto/browser_provider.d.ts.map +0 -1
- package/dist/modules/crypto/browser_provider.js.map +0 -1
- package/dist/modules/crypto/index.d.ts.map +0 -1
- package/dist/modules/crypto/index.js.map +0 -1
- package/dist/modules/crypto/node_provider.d.ts.map +0 -1
- package/dist/modules/crypto/node_provider.js.map +0 -1
- package/dist/modules/crypto/provider.d.ts.map +0 -1
- package/dist/modules/crypto/provider.js.map +0 -1
- package/dist/modules/crypto/pure_ripemd160.d.ts.map +0 -1
- package/dist/modules/crypto/pure_ripemd160.js.map +0 -1
- package/dist/modules/crypto/pure_scrypt.d.ts.map +0 -1
- package/dist/modules/crypto/pure_scrypt.js.map +0 -1
- package/dist/modules/crypto/pure_secp256k1.d.ts.map +0 -1
- package/dist/modules/crypto/pure_secp256k1.js.map +0 -1
- package/dist/modules/crypto/sync.d.ts.map +0 -1
- package/dist/modules/crypto/sync.js.map +0 -1
- package/dist/modules/daemon_node_health.d.ts.map +0 -1
- package/dist/modules/daemon_node_health.js.map +0 -1
- package/dist/modules/dexbot_class.d.ts.map +0 -1
- package/dist/modules/dexbot_class.js.map +0 -1
- package/dist/modules/dexbot_cow_runtime.d.ts.map +0 -1
- package/dist/modules/dexbot_cow_runtime.js.map +0 -1
- package/dist/modules/dexbot_credential_client.d.ts.map +0 -1
- package/dist/modules/dexbot_credential_client.js.map +0 -1
- package/dist/modules/dexbot_fill_runtime.d.ts.map +0 -1
- package/dist/modules/dexbot_fill_runtime.js.map +0 -1
- package/dist/modules/dexbot_maintenance_runtime.d.ts.map +0 -1
- package/dist/modules/dexbot_maintenance_runtime.js.map +0 -1
- package/dist/modules/dexbot_startup_runtime.d.ts.map +0 -1
- package/dist/modules/dexbot_startup_runtime.js.map +0 -1
- package/dist/modules/dexbot_state_recovery.d.ts.map +0 -1
- package/dist/modules/dexbot_state_recovery.js.map +0 -1
- package/dist/modules/env.d.ts.map +0 -1
- package/dist/modules/env.js.map +0 -1
- package/dist/modules/fund_registry.d.ts.map +0 -1
- package/dist/modules/fund_registry.js.map +0 -1
- package/dist/modules/general_settings.d.ts.map +0 -1
- package/dist/modules/general_settings.js.map +0 -1
- package/dist/modules/graceful_shutdown.d.ts.map +0 -1
- package/dist/modules/graceful_shutdown.js.map +0 -1
- package/dist/modules/grid_price_source.d.ts.map +0 -1
- package/dist/modules/grid_price_source.js.map +0 -1
- package/dist/modules/key_store.d.ts.map +0 -1
- package/dist/modules/key_store.js.map +0 -1
- package/dist/modules/launcher/adapter_requirement.d.ts.map +0 -1
- package/dist/modules/launcher/adapter_requirement.js.map +0 -1
- package/dist/modules/launcher/bot_supervisor.d.ts.map +0 -1
- package/dist/modules/launcher/bot_supervisor.js.map +0 -1
- package/dist/modules/launcher/child_env.d.ts.map +0 -1
- package/dist/modules/launcher/child_env.js.map +0 -1
- package/dist/modules/launcher/credential_bootstrap.d.ts.map +0 -1
- package/dist/modules/launcher/credential_bootstrap.js.map +0 -1
- package/dist/modules/launcher/credential_daemon.d.ts.map +0 -1
- package/dist/modules/launcher/credential_daemon.js.map +0 -1
- package/dist/modules/launcher/credential_secret.d.ts.map +0 -1
- package/dist/modules/launcher/credential_secret.js.map +0 -1
- package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +0 -1
- package/dist/modules/launcher/foreign_cred_daemon.js.map +0 -1
- package/dist/modules/launcher/headless_password.d.ts.map +0 -1
- package/dist/modules/launcher/headless_password.js.map +0 -1
- package/dist/modules/launcher/launch_modes.d.ts.map +0 -1
- package/dist/modules/launcher/launch_modes.js.map +0 -1
- package/dist/modules/launcher/market_adapter_runtime.d.ts.map +0 -1
- package/dist/modules/launcher/market_adapter_runtime.js.map +0 -1
- package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +0 -1
- package/dist/modules/launcher/market_adapter_watchdog.js.map +0 -1
- package/dist/modules/launcher/monolithic_runtime.d.ts.map +0 -1
- package/dist/modules/launcher/monolithic_runtime.js.map +0 -1
- package/dist/modules/launcher/runtime_entry.d.ts.map +0 -1
- package/dist/modules/launcher/runtime_entry.js.map +0 -1
- package/dist/modules/launcher/status_reporting.d.ts.map +0 -1
- package/dist/modules/launcher/status_reporting.js.map +0 -1
- package/dist/modules/launcher/supervisor_control.d.ts.map +0 -1
- package/dist/modules/launcher/supervisor_control.js.map +0 -1
- package/dist/modules/market_adapter_whitelist.d.ts.map +0 -1
- package/dist/modules/market_adapter_whitelist.js.map +0 -1
- package/dist/modules/node_connect_policy.d.ts.map +0 -1
- package/dist/modules/node_connect_policy.js.map +0 -1
- package/dist/modules/node_failure_ledger.d.ts.map +0 -1
- package/dist/modules/node_failure_ledger.js.map +0 -1
- package/dist/modules/node_health_cache.d.ts.map +0 -1
- package/dist/modules/node_health_cache.js.map +0 -1
- package/dist/modules/node_manager.d.ts.map +0 -1
- package/dist/modules/node_manager.js.map +0 -1
- package/dist/modules/order/accounting.d.ts.map +0 -1
- package/dist/modules/order/accounting.js.map +0 -1
- package/dist/modules/order/async_lock.d.ts.map +0 -1
- package/dist/modules/order/async_lock.js.map +0 -1
- package/dist/modules/order/export.d.ts.map +0 -1
- package/dist/modules/order/export.js.map +0 -1
- package/dist/modules/order/format.d.ts.map +0 -1
- package/dist/modules/order/format.js.map +0 -1
- package/dist/modules/order/grid.d.ts.map +0 -1
- package/dist/modules/order/grid.js.map +0 -1
- package/dist/modules/order/grid_reconcile.d.ts.map +0 -1
- package/dist/modules/order/grid_reconcile.js.map +0 -1
- package/dist/modules/order/grid_reconcile_internal.d.ts.map +0 -1
- package/dist/modules/order/grid_reconcile_internal.js.map +0 -1
- package/dist/modules/order/index.d.ts.map +0 -1
- package/dist/modules/order/index.js.map +0 -1
- package/dist/modules/order/logger.d.ts.map +0 -1
- package/dist/modules/order/logger.js.map +0 -1
- package/dist/modules/order/logger_state.d.ts.map +0 -1
- package/dist/modules/order/logger_state.js.map +0 -1
- package/dist/modules/order/manager.d.ts.map +0 -1
- package/dist/modules/order/manager.js.map +0 -1
- package/dist/modules/order/processed_fill_store.d.ts.map +0 -1
- package/dist/modules/order/processed_fill_store.js.map +0 -1
- package/dist/modules/order/strategy.d.ts.map +0 -1
- package/dist/modules/order/strategy.js.map +0 -1
- package/dist/modules/order/sync_engine.d.ts.map +0 -1
- package/dist/modules/order/sync_engine.js.map +0 -1
- package/dist/modules/order/utils/math.d.ts.map +0 -1
- package/dist/modules/order/utils/math.js.map +0 -1
- package/dist/modules/order/utils/order.d.ts.map +0 -1
- package/dist/modules/order/utils/order.js.map +0 -1
- package/dist/modules/order/utils/slot.d.ts.map +0 -1
- package/dist/modules/order/utils/slot.js.map +0 -1
- package/dist/modules/order/utils/system.d.ts.map +0 -1
- package/dist/modules/order/utils/system.js.map +0 -1
- package/dist/modules/order/utils/timeout.d.ts.map +0 -1
- package/dist/modules/order/utils/timeout.js.map +0 -1
- package/dist/modules/order/utils/validate.d.ts.map +0 -1
- package/dist/modules/order/utils/validate.js.map +0 -1
- package/dist/modules/order/utils/withPoolRef.d.ts.map +0 -1
- package/dist/modules/order/utils/withPoolRef.js.map +0 -1
- package/dist/modules/order/working_grid.d.ts.map +0 -1
- package/dist/modules/order/working_grid.js.map +0 -1
- package/dist/modules/path_api.d.ts.map +0 -1
- package/dist/modules/path_api.js.map +0 -1
- package/dist/modules/paths.d.ts.map +0 -1
- package/dist/modules/paths.js.map +0 -1
- package/dist/modules/process_discovery.d.ts.map +0 -1
- package/dist/modules/process_discovery.js.map +0 -1
- package/dist/modules/runtime.d.ts.map +0 -1
- package/dist/modules/runtime.js.map +0 -1
- package/dist/modules/runtime_settings.d.ts.map +0 -1
- package/dist/modules/runtime_settings.js.map +0 -1
- package/dist/modules/settings_merge.d.ts.map +0 -1
- package/dist/modules/settings_merge.js.map +0 -1
- package/dist/modules/socket_json_client.d.ts.map +0 -1
- package/dist/modules/socket_json_client.js.map +0 -1
- package/dist/modules/storage/browser_adapter.d.ts.map +0 -1
- package/dist/modules/storage/browser_adapter.js.map +0 -1
- package/dist/modules/storage/index.d.ts.map +0 -1
- package/dist/modules/storage/index.js.map +0 -1
- package/dist/modules/storage/node_adapter.d.ts.map +0 -1
- package/dist/modules/storage/node_adapter.js.map +0 -1
- package/dist/modules/storage/types.d.ts.map +0 -1
- package/dist/modules/storage/types.js.map +0 -1
- package/dist/modules/types.d.ts.map +0 -1
- package/dist/modules/types.js.map +0 -1
- package/dist/modules/utils/base58check.d.ts.map +0 -1
- package/dist/modules/utils/base58check.js.map +0 -1
- package/dist/modules/utils/build_dir.d.ts.map +0 -1
- package/dist/modules/utils/build_dir.js.map +0 -1
- package/dist/modules/utils/chain_logs.d.ts.map +0 -1
- package/dist/modules/utils/chain_logs.js.map +0 -1
- package/dist/modules/utils/errors.d.ts.map +0 -1
- package/dist/modules/utils/errors.js.map +0 -1
- package/dist/modules/utils/sanitize_key.d.ts.map +0 -1
- package/dist/modules/utils/sanitize_key.js.map +0 -1
- package/dist/modules/utils/text_width.d.ts.map +0 -1
- package/dist/modules/utils/text_width.js.map +0 -1
- package/dist/modules/validate_profiles.d.ts.map +0 -1
- package/dist/modules/validate_profiles.js.map +0 -1
- package/dist/pm2.d.ts.map +0 -1
- package/dist/pm2.js.map +0 -1
- package/dist/scripts/analyze-credit.d.ts.map +0 -1
- package/dist/scripts/analyze-credit.js.map +0 -1
- package/dist/scripts/analyze-git.d.ts.map +0 -1
- package/dist/scripts/analyze-git.js.map +0 -1
- package/dist/scripts/analyze-orders.d.ts.map +0 -1
- package/dist/scripts/analyze-orders.js.map +0 -1
- package/dist/scripts/chart_command.d.ts.map +0 -1
- package/dist/scripts/chart_command.js.map +0 -1
- package/dist/scripts/diagnose-kibana-candles.d.ts.map +0 -1
- package/dist/scripts/diagnose-kibana-candles.js.map +0 -1
- package/dist/scripts/diagnose-pool-history.d.ts.map +0 -1
- package/dist/scripts/diagnose-pool-history.js.map +0 -1
- package/dist/scripts/divergence-calc.d.ts.map +0 -1
- package/dist/scripts/divergence-calc.js.map +0 -1
- package/dist/scripts/dw.d.ts.map +0 -1
- package/dist/scripts/dw.js.map +0 -1
- package/dist/scripts/generate_lp_chart.d.ts.map +0 -1
- package/dist/scripts/generate_lp_chart.js.map +0 -1
- package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +0 -1
- package/dist/scripts/generate_mainnet_corpus_report.js.map +0 -1
- package/dist/scripts/native_release_gates.d.ts.map +0 -1
- package/dist/scripts/native_release_gates.js.map +0 -1
- package/dist/scripts/print_grid.d.ts.map +0 -1
- package/dist/scripts/print_grid.js.map +0 -1
- package/dist/scripts/run-tests.d.ts.map +0 -1
- package/dist/scripts/run-tests.js.map +0 -1
- package/dist/scripts/runner.d.ts.map +0 -1
- package/dist/scripts/runner.js.map +0 -1
- package/dist/scripts/sync-version.d.ts.map +0 -1
- package/dist/scripts/sync-version.js.map +0 -1
- package/dist/scripts/test-credit-renewal.d.ts.map +0 -1
- package/dist/scripts/test-credit-renewal.js.map +0 -1
- package/dist/scripts/tv.d.ts.map +0 -1
- package/dist/scripts/tv.js.map +0 -1
- package/dist/scripts/update.d.ts.map +0 -1
- package/dist/scripts/update.js.map +0 -1
- package/dist/scripts/update_dist_freshness.d.ts.map +0 -1
- package/dist/scripts/update_dist_freshness.js.map +0 -1
- package/dist/scripts/validate_bots.d.ts.map +0 -1
- package/dist/scripts/validate_bots.js.map +0 -1
- package/dist/scripts/verify-browser-bundle.d.ts.map +0 -1
- package/dist/scripts/verify-browser-bundle.js.map +0 -1
- package/dist/unlock.d.ts.map +0 -1
- package/dist/unlock.js.map +0 -1
|
@@ -1,934 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import os from 'node:os';
|
|
5
|
-
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
6
|
-
import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
|
|
7
|
-
import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
|
|
8
|
-
import { computeAverageAmaSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
|
|
9
|
-
import { range } from '../math_utils.js';
|
|
10
|
-
import { parseListOrRange, loadLpData, fmt } from './shared_utils.js';
|
|
11
|
-
import { getStorage } from '../../modules/storage/index.js';
|
|
12
|
-
import { PATHS } from '../../modules/paths.js';
|
|
13
|
-
import { GRID_LIMITS, MARKET_ADAPTER } from '../../modules/constants.js';
|
|
14
|
-
// Production grid geometry + slope-ratio offset — shared with bot_fitting so
|
|
15
|
-
// both tools build byte-identical grids for identical params (#12).
|
|
16
|
-
import { buildProductionGrid, computeGridPriceOffsetPct } from './backtest_bot_fitting.js';
|
|
17
|
-
const { readJSON, writeJSON } = getStorage();
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* AMA SWEEP BACKTEST — persistent grid simulation
|
|
21
|
-
*
|
|
22
|
-
* Models the real bot mechanics:
|
|
23
|
-
* - Orders sit at FIXED chain prices until canceled or filled
|
|
24
|
-
* - Slot rotation: a filled buy re-offers its base ONE RAIL STEP UP; when
|
|
25
|
-
* that refill sells, one increment (minus fees) is booked and the freed
|
|
26
|
-
* quote re-bids one rail step down — anchor-&-refill cycling
|
|
27
|
-
* - Unlinked (initial-grid) sells execute only against held inventory;
|
|
28
|
-
* bought-and-held base carries across resets as a weighted-average-entry
|
|
29
|
-
* position whose final mark is reported informationally, not scored
|
|
30
|
-
* - Order sizing depends on capital, ratio (range width), and weight profile
|
|
31
|
-
* - Three weight profiles: valley, neutral, mountain (symmetric buy/sell)
|
|
32
|
-
*
|
|
33
|
-
* Usage:
|
|
34
|
-
* node dist/analysis/bot_fitting/backtest_ama_sweep.js --data <path-to-lp-candles.json>
|
|
35
|
-
* node dist/analysis/bot_fitting/backtest_ama_sweep.js --data <path-to-lp-candles.json> --spread 4:16:1 --increment 0.5:4:0.25
|
|
36
|
-
*/
|
|
37
|
-
|
|
38
|
-
const DEFAULT_MAX_ORDERS = 20; // weight-profile sizing cap per side (search abstraction)
|
|
39
|
-
const DEFAULT_FEE_ROUNDTRIP_PCT = 0.20;
|
|
40
|
-
// Canonical spread floor from production grid limits (modules/constants.ts).
|
|
41
|
-
const DEFAULT_MIN_SPREAD_FACTOR = GRID_LIMITS.MIN_SPREAD_FACTOR;
|
|
42
|
-
const DEFAULT_CAPITAL = 10000; // notional units per side
|
|
43
|
-
const DEFAULT_BTS_CREATE_FEE = 0.48260;
|
|
44
|
-
const DEFAULT_BTS_CANCEL_FEE = 0.00482;
|
|
45
|
-
const DEFAULT_BTS_MAKER_CREATE_FACTOR = 0.10;
|
|
46
|
-
const DEFAULT_TX_FEE_PRICE = 1.0;
|
|
47
|
-
|
|
48
|
-
// Weight profiles (symmetric for both sides)
|
|
49
|
-
// valley: heavier at edges (outer levels), lighter near center
|
|
50
|
-
// neutral: equal across all levels
|
|
51
|
-
// mountain: heavier near center, lighter at edges
|
|
52
|
-
const WEIGHT_PROFILES = {
|
|
53
|
-
valley: -0.8, // negative = invert decay → outer levels get more
|
|
54
|
-
neutral: 0, // flat = equal distribution
|
|
55
|
-
mountain: 1.5, // strong decay → inner levels get more
|
|
56
|
-
};
|
|
57
|
-
|
|
58
|
-
// Search grid defaults — centered around bot defaults (spread=2%, increment=0.5%)
|
|
59
|
-
// Spread = targetSpreadPercent for the gapSlots spread zone (production
|
|
60
|
-
// semantics, matching bot_fitting — the legacy half-spread dead zone is gone).
|
|
61
|
-
// Increment = geometric rail step between successive orders on the same side.
|
|
62
|
-
const DEFAULT_SPREAD_VALUES = [...range(0.5, 4, 0.25), ...range(5, 12, 1)];
|
|
63
|
-
const DEFAULT_INCREMENT_VALUES = [...range(0.2, 2, 0.1), ...range(2.5, 8, 0.5)];
|
|
64
|
-
const DEFAULT_RATIO_VALUES = [1.05, 1.1, 1.15, 1.2, 1.3, 1.5, 2, 3, 5, 10];
|
|
65
|
-
// Reposition threshold: production default (MARKET_ADAPTER
|
|
66
|
-
// AMA_DELTA_THRESHOLD_PERCENT = 1%); --reposition overrides.
|
|
67
|
-
const DEFAULT_REPOSITION_PCT = MARKET_ADAPTER.AMA_DELTA_THRESHOLD_PERCENT;
|
|
68
|
-
|
|
69
|
-
// Trigger B / grid-price offset (asymmetricBounds whitelist) — same constants
|
|
70
|
-
// as bot_fitting, shared semantics with the live adapter.
|
|
71
|
-
const SLOPE_TRIGGER_FACTOR = MARKET_ADAPTER.AMA_SLOPE_DELTA_THRESHOLD_PERCENT;
|
|
72
|
-
const SLOPE_MAX_PCT = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT;
|
|
73
|
-
const SLOPE_LOOKBACK_BARS = MARKET_ADAPTER.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS;
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
function parseArgs() {
|
|
77
|
-
const args = process.argv.slice(2);
|
|
78
|
-
const out: {
|
|
79
|
-
dataPath: string | null;
|
|
80
|
-
resultsPath: string | null;
|
|
81
|
-
spreadValues: number[];
|
|
82
|
-
incrementValues: number[];
|
|
83
|
-
ratioValues: number[];
|
|
84
|
-
maxOrders: number;
|
|
85
|
-
feeRoundtripPct: number;
|
|
86
|
-
minSpreadFactor: number;
|
|
87
|
-
capital: number;
|
|
88
|
-
repositionPct: number;
|
|
89
|
-
asymmetricBounds: boolean;
|
|
90
|
-
btsCreateFee: number;
|
|
91
|
-
btsCancelFee: number;
|
|
92
|
-
makerCreateFactor: number;
|
|
93
|
-
txFeePrice: number;
|
|
94
|
-
topN: number;
|
|
95
|
-
} = {
|
|
96
|
-
dataPath: null,
|
|
97
|
-
resultsPath: null,
|
|
98
|
-
spreadValues: DEFAULT_SPREAD_VALUES,
|
|
99
|
-
incrementValues: DEFAULT_INCREMENT_VALUES,
|
|
100
|
-
ratioValues: DEFAULT_RATIO_VALUES,
|
|
101
|
-
maxOrders: DEFAULT_MAX_ORDERS,
|
|
102
|
-
feeRoundtripPct: DEFAULT_FEE_ROUNDTRIP_PCT,
|
|
103
|
-
minSpreadFactor: DEFAULT_MIN_SPREAD_FACTOR,
|
|
104
|
-
capital: DEFAULT_CAPITAL,
|
|
105
|
-
repositionPct: DEFAULT_REPOSITION_PCT,
|
|
106
|
-
asymmetricBounds: false,
|
|
107
|
-
btsCreateFee: DEFAULT_BTS_CREATE_FEE,
|
|
108
|
-
btsCancelFee: DEFAULT_BTS_CANCEL_FEE,
|
|
109
|
-
makerCreateFactor: DEFAULT_BTS_MAKER_CREATE_FACTOR,
|
|
110
|
-
txFeePrice: DEFAULT_TX_FEE_PRICE,
|
|
111
|
-
topN: 15,
|
|
112
|
-
};
|
|
113
|
-
|
|
114
|
-
for (let i = 0; i < args.length; i++) {
|
|
115
|
-
const arg = args[i];
|
|
116
|
-
if (arg === '--asymmetric-bounds') { out.asymmetricBounds = true; continue; }
|
|
117
|
-
const val = args[i + 1];
|
|
118
|
-
if (arg === '--help' || arg === '-h') { printHelp(); process.exit(0); }
|
|
119
|
-
if (!val) continue;
|
|
120
|
-
switch (arg) {
|
|
121
|
-
case '--data': out.dataPath = path.resolve(val); i++; break;
|
|
122
|
-
case '--results': out.resultsPath = path.resolve(val); i++; break;
|
|
123
|
-
case '--spread': out.spreadValues = parseListOrRange(val, DEFAULT_SPREAD_VALUES); i++; break;
|
|
124
|
-
case '--increment': out.incrementValues = parseListOrRange(val, DEFAULT_INCREMENT_VALUES); i++; break;
|
|
125
|
-
case '--ratio': out.ratioValues = parseListOrRange(val, DEFAULT_RATIO_VALUES); i++; break;
|
|
126
|
-
case '--max-orders': out.maxOrders = Number(val); i++; break;
|
|
127
|
-
case '--fee': out.feeRoundtripPct = Number(val); i++; break;
|
|
128
|
-
case '--min-spread-factor': out.minSpreadFactor = Number(val); i++; break;
|
|
129
|
-
case '--capital': out.capital = Number(val); i++; break;
|
|
130
|
-
case '--reposition': out.repositionPct = Number(val); i++; break;
|
|
131
|
-
case '--bts-create-fee': out.btsCreateFee = Number(val); i++; break;
|
|
132
|
-
case '--bts-cancel-fee': out.btsCancelFee = Number(val); i++; break;
|
|
133
|
-
case '--maker-create-factor': out.makerCreateFactor = Number(val); i++; break;
|
|
134
|
-
case '--tx-fee-price': out.txFeePrice = Number(val); i++; break;
|
|
135
|
-
case '--top': out.topN = Number(val); i++; break;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
if (!out.dataPath) {
|
|
139
|
-
throw new Error('--data <path-to-lp-candles.json> is required');
|
|
140
|
-
}
|
|
141
|
-
if (!out.resultsPath) {
|
|
142
|
-
throw new Error('--results <path-to-optimization-results.json> is required');
|
|
143
|
-
}
|
|
144
|
-
return out;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
function printHelp() {
|
|
148
|
-
console.log('AMA Sweep Backtest — persistent grid simulation with weight profiles');
|
|
149
|
-
console.log('');
|
|
150
|
-
console.log('Usage:');
|
|
151
|
-
console.log(' node dist/analysis/bot_fitting/backtest_ama_sweep.js [options]');
|
|
152
|
-
console.log('');
|
|
153
|
-
console.log('Options:');
|
|
154
|
-
console.log(' --data <path> LP candle JSON');
|
|
155
|
-
console.log(' --results <path> AMA optimizer results JSON');
|
|
156
|
-
console.log(' --spread <spec> Target spread % (gapSlots zone): 1:10:0.5 or 2,4,8');
|
|
157
|
-
console.log(' --increment <spec> Increment values (%): 0.5:5:0.5 or 1,2,3');
|
|
158
|
-
console.log(' --ratio <spec> Max/min ratio: 1.5,2,3,5');
|
|
159
|
-
console.log(' --max-orders <n> Size cap per side (default: 20)');
|
|
160
|
-
console.log(' --fee <pct> Round-trip fee % (default: 0.20)');
|
|
161
|
-
console.log(' --min-spread-factor <n> Spread >= factor * increment (default: 2.1)');
|
|
162
|
-
console.log(' --capital <n> Notional capital per side (default: 10000)');
|
|
163
|
-
console.log(' --reposition <pct> AMA drift % to trigger re-center (default: 1.00, production)');
|
|
164
|
-
console.log(' --asymmetric-bounds Enable slope-delta reset (B) + grid price offset (whitelist semantics)');
|
|
165
|
-
console.log(' --bts-create-fee <n> BTS create fee (default: 0.48260)');
|
|
166
|
-
console.log(' --bts-cancel-fee <n> BTS cancel fee (default: 0.00482)');
|
|
167
|
-
console.log(' --maker-create-factor Maker share of create fee (default: 0.10)');
|
|
168
|
-
console.log(' --tx-fee-price <n> Convert BTS fees into backtest units (default: 1.0)');
|
|
169
|
-
console.log(' --top <n> Show top N results (default: 15)');
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
function loadAmaStrategies(resultsPath: string) {
|
|
173
|
-
const json = readJSON(resultsPath);
|
|
174
|
-
const amas = (json.meta as any)?.amas;
|
|
175
|
-
if (!amas) throw new Error('No meta.amas found in results file.');
|
|
176
|
-
|
|
177
|
-
const out: any[] = [];
|
|
178
|
-
for (const [key, val] of Object.entries(amas)) {
|
|
179
|
-
const v = val as any;
|
|
180
|
-
if (!v || !Number.isFinite(v.er)) continue;
|
|
181
|
-
out.push({ id: key, name: v.label || key, er: v.er, fast: v.fast, slow: v.slow });
|
|
182
|
-
}
|
|
183
|
-
out.sort((a, b) => a.id.localeCompare(b.id));
|
|
184
|
-
if (out.length === 0) throw new Error('No valid AMA strategies found');
|
|
185
|
-
return out;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
// ── Order sizing with weight profiles ────────────────────────────────────────
|
|
189
|
-
|
|
190
|
-
/**
|
|
191
|
-
* Allocate capital across N levels using weight profile.
|
|
192
|
-
* weight > 0: mountain (more near center, exponential decay outward)
|
|
193
|
-
* weight = 0: neutral (equal)
|
|
194
|
-
* weight < 0: valley (more at edges, inverted decay)
|
|
195
|
-
*
|
|
196
|
-
* @param {number} totalFunds Capital for this side
|
|
197
|
-
* @param {number} n Number of levels
|
|
198
|
-
* @param {number} weight Profile weight factor
|
|
199
|
-
* @param {number} incrementFactor Increment as fraction (e.g. 0.02 for 2%)
|
|
200
|
-
* @returns {number[]} Size per level, index 0 = closest to center
|
|
201
|
-
*/
|
|
202
|
-
function allocateFundsByWeights(totalFunds: number, n: number, weight: number, incrementFactor: number): number[] {
|
|
203
|
-
if (n <= 0) return [];
|
|
204
|
-
if (weight === 0) {
|
|
205
|
-
const sz = totalFunds / n;
|
|
206
|
-
return new Array(n).fill(sz);
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
const base = 1 - incrementFactor;
|
|
210
|
-
const absWeight = Math.abs(weight);
|
|
211
|
-
const raw = new Array(n);
|
|
212
|
-
for (let i = 0; i < n; i++) {
|
|
213
|
-
// i=0 is closest to center
|
|
214
|
-
raw[i] = Math.pow(base, i * absWeight);
|
|
215
|
-
}
|
|
216
|
-
if (weight < 0) {
|
|
217
|
-
// Valley: reverse so outer levels (high i) get the large weights
|
|
218
|
-
raw.reverse();
|
|
219
|
-
}
|
|
220
|
-
const total = raw.reduce((s, w) => s + w, 0) || 1;
|
|
221
|
-
return raw.map((w) => (w / total) * totalFunds);
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// ── Persistent grid simulation ───────────────────────────────────────────────
|
|
225
|
-
|
|
226
|
-
/**
|
|
227
|
-
* Build a fresh grid centered at `center` using the SHARED production
|
|
228
|
-
* geometry (buildProductionGrid from backtest_bot_fitting — createOrderGrid
|
|
229
|
-
* port): master rail at √(1±inc) offsets bounded by [center/ratio,
|
|
230
|
-
* center*ratio] with a calculateGapSlots spread zone. This guarantees the
|
|
231
|
-
* sweep and bot_fitting build byte-identical grids for identical params
|
|
232
|
-
* (#12). Weight-profile sizing is applied over the capped nearest-to-gap
|
|
233
|
-
* levels, index 0 = closest to the gap.
|
|
234
|
-
*
|
|
235
|
-
* Returns arrays of buy and sell order objects with fixed chain prices and sizes.
|
|
236
|
-
*/
|
|
237
|
-
function buildGrid(center: number, params: any, capitalPerSide: number, weightFactor: number) {
|
|
238
|
-
const { incrementPct, maxMinRatio, maxOrders, spreadPct } = params;
|
|
239
|
-
const built = buildProductionGrid(center, spreadPct, incrementPct, maxMinRatio, maxOrders);
|
|
240
|
-
|
|
241
|
-
const buySizes = allocateFundsByWeights(capitalPerSide, built.buys.length, weightFactor, incrementPct);
|
|
242
|
-
const sellSizes = allocateFundsByWeights(capitalPerSide, built.sells.length, weightFactor, incrementPct);
|
|
243
|
-
|
|
244
|
-
// Level k = k-th slot from the gap on each side. Each placed slot also
|
|
245
|
-
// carries its MASTER-RAIL index so rotation hops land on adjacent rail
|
|
246
|
-
// nodes (live anchor-&-refill hop) instead of a flat ×(1+inc).
|
|
247
|
-
const buys: any[] = built.buys.map((price: number, i: number) => {
|
|
248
|
-
const k = built.buys.length - i;
|
|
249
|
-
return { level: k, price, railIdx: built.buySliceStart + i, cooldownUntil: -1, size: buySizes[k - 1] || 0 };
|
|
250
|
-
});
|
|
251
|
-
const sells: any[] = built.sells.map((price: number, i: number) => ({
|
|
252
|
-
level: i + 1, price, railIdx: built.sellStartIdx + i, cooldownUntil: -1, size: sellSizes[i] || 0,
|
|
253
|
-
}));
|
|
254
|
-
return { buys, sells, rail: built.rail };
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* Mark the held inventory position to `markPrice` in capital units.
|
|
259
|
-
*
|
|
260
|
-
* Carried bags are a REAL risk the drawdown tracker should see bar-by-bar,
|
|
261
|
-
* but their mark is informational for scoring: realized rotation profit plus
|
|
262
|
-
* op fees drive netProfit, and the end-of-run position is reported separately
|
|
263
|
-
* instead of being dumped into totals.
|
|
264
|
-
*/
|
|
265
|
-
function markInventoryAtPrice(inventory: { units: number; cost: number }, exitPrice: number, feeRoundtripPct: number) {
|
|
266
|
-
if (!Number.isFinite(exitPrice) || exitPrice <= 0 || inventory.units <= 0) {
|
|
267
|
-
return { grossUnits: 0, profitUnits: 0 };
|
|
268
|
-
}
|
|
269
|
-
const avgEntry = inventory.cost / inventory.units;
|
|
270
|
-
const grossUnits = (exitPrice - avgEntry) * inventory.units;
|
|
271
|
-
const feeUnits = avgEntry * inventory.units * ((feeRoundtripPct / 2) / 100);
|
|
272
|
-
return { grossUnits, profitUnits: grossUnits - feeUnits };
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
function simulatePersistentGrid(candles: any[], amaValues: number[], params: any, weightName: string, weightFactor: number) {
|
|
276
|
-
const { spreadPct, incrementPct, maxMinRatio, feeRoundtripPct,
|
|
277
|
-
capital, repositionThreshold, asymmetricBounds, btsCreateFee, btsCancelFee,
|
|
278
|
-
makerCreateFactor, txFeePrice } = params;
|
|
279
|
-
// Warmup follows production AMA seeding/convergence (getAmaWarmupBars,
|
|
280
|
-
// passed via params.warmupBars from sweepOneAma) instead of an arbitrary
|
|
281
|
-
// fraction of the dataset. Direct callers that omit warmupBars fall back
|
|
282
|
-
// to the legacy 10% cut.
|
|
283
|
-
const warmupParam = Number.isFinite(params.warmupBars)
|
|
284
|
-
? params.warmupBars
|
|
285
|
-
: Math.max(20, Math.floor(candles.length * 0.1));
|
|
286
|
-
const skip = Math.min(warmupParam, Math.max(0, candles.length - 2));
|
|
287
|
-
const capitalPerSide = capital;
|
|
288
|
-
const makerCreateFeeBts = btsCreateFee * makerCreateFactor;
|
|
289
|
-
const slopeDeltaThresholdPct = (SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT;
|
|
290
|
-
|
|
291
|
-
// First tradable bar: need a finite positive AMA to anchor the grid.
|
|
292
|
-
let startIdx = Math.min(skip, candles.length - 1);
|
|
293
|
-
let gridCenter = Number.NaN;
|
|
294
|
-
for (let j = startIdx; j < candles.length; j++) {
|
|
295
|
-
const v = amaValues[j];
|
|
296
|
-
if (Number.isFinite(v) && v > 0) { gridCenter = v; startIdx = j; break; }
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// Production AMA slope series (%/bar averaged over the lookback window) —
|
|
300
|
-
// feeds trigger B and the grid price offset when asymmetricBounds is on.
|
|
301
|
-
const slopeAt: (number | null)[] = new Array(candles.length).fill(null);
|
|
302
|
-
for (let j = SLOPE_LOOKBACK_BARS; j < candles.length; j++) {
|
|
303
|
-
const s = computeAverageAmaSlopePct(amaValues[j], amaValues[j - SLOPE_LOOKBACK_BARS], SLOPE_LOOKBACK_BARS);
|
|
304
|
-
if (s != null && Number.isFinite(s)) slopeAt[j] = s;
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
// State — slot-rotation engine (mirrors simulateForParams in
|
|
308
|
-
// backtest_bot_fitting, with weight-profile sized orders):
|
|
309
|
-
// orders: id -> { side, price, size, linkedBuyPrice, linkedEntryBar,
|
|
310
|
-
// cooldownUntil }. linkedBuyPrice != null marks an armed
|
|
311
|
-
// refill sell created by a specific filled buy (one-increment rotation).
|
|
312
|
-
const orders = new Map<number, any>();
|
|
313
|
-
let nextOrderId = 0;
|
|
314
|
-
// Bought-and-held base across the whole run (weighted-average entry pool).
|
|
315
|
-
// Never negative — unfundable sells stay pending instead of shorting.
|
|
316
|
-
const inventory = { units: 0, cost: 0 };
|
|
317
|
-
const stepUpFrac = 1 + incrementPct; // one-rail-step rotation distance
|
|
318
|
-
|
|
319
|
-
let btsFeesBts = 0;
|
|
320
|
-
let offsetAppliedCount = 0;
|
|
321
|
-
// Master rail of the CURRENT epoch — rotation hops read adjacent nodes.
|
|
322
|
-
let activeRail: number[] = [];
|
|
323
|
-
|
|
324
|
-
const placeInitialGrid = (center: number, slopePct: number | null) => {
|
|
325
|
-
const offsetPct = (asymmetricBounds && slopePct != null)
|
|
326
|
-
? computeGridPriceOffsetPct(slopePct, spreadPct)
|
|
327
|
-
: 0;
|
|
328
|
-
if (offsetPct !== 0) offsetAppliedCount++;
|
|
329
|
-
const effCenter = center * (1 + offsetPct / 100);
|
|
330
|
-
const grid = buildGrid(effCenter, params, capitalPerSide, weightFactor);
|
|
331
|
-
activeRail = grid.rail;
|
|
332
|
-
orders.clear();
|
|
333
|
-
for (const o of grid.buys) {
|
|
334
|
-
orders.set(nextOrderId++, { side: 'buy', price: o.price, size: o.size, railIdx: o.railIdx, linkedBuyPrice: null, linkedEntryBar: -1, cooldownUntil: -1 });
|
|
335
|
-
}
|
|
336
|
-
for (const o of grid.sells) {
|
|
337
|
-
orders.set(nextOrderId++, { side: 'sell', price: o.price, size: o.size, railIdx: o.railIdx, linkedBuyPrice: null, linkedEntryBar: -1, cooldownUntil: -1 });
|
|
338
|
-
}
|
|
339
|
-
btsFeesBts += (grid.buys.length + grid.sells.length) * makerCreateFeeBts;
|
|
340
|
-
};
|
|
341
|
-
|
|
342
|
-
if (Number.isFinite(gridCenter)) placeInitialGrid(gridCenter, slopeAt[startIdx]);
|
|
343
|
-
let lastRepositionBar = startIdx;
|
|
344
|
-
|
|
345
|
-
let matchedPairs = 0;
|
|
346
|
-
let cyclesTotal = 0;
|
|
347
|
-
let rotationCount = 0; // linked ping-pong rotations (buy → refill sell)
|
|
348
|
-
let inventorySaleCount = 0; // unlinked sells executed against held bags
|
|
349
|
-
let totalProfitUnits = 0; // REALIZED profit in capital units (size * netPct)
|
|
350
|
-
let totalGrossUnits = 0;
|
|
351
|
-
let touchedOrders = 0;
|
|
352
|
-
let canceledOnReposition = 0;
|
|
353
|
-
let repositionCount = 0;
|
|
354
|
-
let driftTriggerCount = 0;
|
|
355
|
-
let slopeTriggerCount = 0;
|
|
356
|
-
let peakOpenOrders = 0;
|
|
357
|
-
let imbalanceSum = 0;
|
|
358
|
-
let imbalanceSamples = 0;
|
|
359
|
-
let matchedOpenDurationBars = 0;
|
|
360
|
-
let gridAgeSumBars = 0;
|
|
361
|
-
let maxGridAgeBars = 0;
|
|
362
|
-
let centerDriftSumPct = 0;
|
|
363
|
-
let maxCenterDriftPct = 0;
|
|
364
|
-
let nearThresholdBars = 0;
|
|
365
|
-
let triggerDriftSumPct = 0;
|
|
366
|
-
let runningProfit = 0;
|
|
367
|
-
let peakEquityProfit = 0;
|
|
368
|
-
let maxDrawdown = 0;
|
|
369
|
-
// Track inventory risk: bought-and-held base, carried across resets —
|
|
370
|
-
// resets never realize inventory (#4). Long-only (no unfunded shorts).
|
|
371
|
-
let inventoryExposure = 0; // held base units (long-only, ≥ 0)
|
|
372
|
-
let maxInventoryExposure = 0;
|
|
373
|
-
|
|
374
|
-
const invAvgEntry = () => (inventory.units > 0 ? inventory.cost / inventory.units : 0);
|
|
375
|
-
const liveBars = candles.length - startIdx - 1;
|
|
376
|
-
const ordersPerSide = [...orders.values()].filter((o) => o.side === 'buy').length;
|
|
377
|
-
|
|
378
|
-
// Slope-delta baseline: mirrors botState.gridRangeScalingAmaSlope —
|
|
379
|
-
// seeded at bootstrap and re-seeded on every reset.
|
|
380
|
-
let slopeBaseline: number | null = null;
|
|
381
|
-
for (let j = startIdx + 1; j < candles.length; j++) {
|
|
382
|
-
if (slopeAt[j] != null) { slopeBaseline = slopeAt[j]; break; }
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
for (let i = startIdx + 1; i < candles.length; i++) {
|
|
386
|
-
const ama = amaValues[i];
|
|
387
|
-
const hi = candles[i].high;
|
|
388
|
-
const lo = candles[i].low;
|
|
389
|
-
const gridAgeBars = i - lastRepositionBar;
|
|
390
|
-
|
|
391
|
-
// ── Reposition check: trigger A (AMA drift, ratchet) or trigger B
|
|
392
|
-
// (slope delta, only under the asymmetricBounds whitelist gate).
|
|
393
|
-
const drift = Math.abs(ama - gridCenter) / gridCenter;
|
|
394
|
-
const driftPct = drift * 100;
|
|
395
|
-
centerDriftSumPct += driftPct;
|
|
396
|
-
if (driftPct > maxCenterDriftPct) maxCenterDriftPct = driftPct;
|
|
397
|
-
gridAgeSumBars += gridAgeBars;
|
|
398
|
-
if (gridAgeBars > maxGridAgeBars) maxGridAgeBars = gridAgeBars;
|
|
399
|
-
if (drift >= repositionThreshold * 0.5) nearThresholdBars++;
|
|
400
|
-
|
|
401
|
-
let shouldReposition = drift >= repositionThreshold;
|
|
402
|
-
if (shouldReposition) { triggerDriftSumPct += driftPct; driftTriggerCount++; }
|
|
403
|
-
if (!shouldReposition && asymmetricBounds && slopeBaseline != null && slopeAt[i] != null) {
|
|
404
|
-
const slopeDeltaPct = Math.abs(slopeAt[i]! - slopeBaseline);
|
|
405
|
-
if (slopeDeltaPct >= slopeDeltaThresholdPct) { shouldReposition = true; slopeTriggerCount++; }
|
|
406
|
-
}
|
|
407
|
-
|
|
408
|
-
if (shouldReposition && Number.isFinite(ama) && ama > 0) {
|
|
409
|
-
canceledOnReposition += orders.size;
|
|
410
|
-
btsFeesBts += orders.size * btsCancelFee;
|
|
411
|
-
orders.clear(); // inventory survives — resync never market-sells
|
|
412
|
-
repositionCount++;
|
|
413
|
-
// Re-center grid
|
|
414
|
-
gridCenter = ama;
|
|
415
|
-
if (slopeAt[i] != null) slopeBaseline = slopeAt[i];
|
|
416
|
-
placeInitialGrid(gridCenter, slopeAt[i]);
|
|
417
|
-
lastRepositionBar = i;
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
// ── Track imbalance & peak ──────────────────────────────────────
|
|
421
|
-
const currentOpen = orders.size;
|
|
422
|
-
if (currentOpen > peakOpenOrders) peakOpenOrders = currentOpen;
|
|
423
|
-
let buyCountNow = 0;
|
|
424
|
-
for (const [, o] of orders) { if (o.side === 'buy') buyCountNow++; }
|
|
425
|
-
imbalanceSum += Math.abs(buyCountNow - (orders.size - buyCountNow));
|
|
426
|
-
imbalanceSamples++;
|
|
427
|
-
|
|
428
|
-
// ── Fill detection against FIXED chain prices ───────────────────
|
|
429
|
-
const filledBuysThisBar: { id: number; order: any }[] = [];
|
|
430
|
-
const filledSellsThisBar: { id: number; order: any }[] = [];
|
|
431
|
-
for (const [id, o] of orders) {
|
|
432
|
-
if (i < o.cooldownUntil || !(o.size > 0)) continue;
|
|
433
|
-
if (o.side === 'buy' && lo <= o.price) filledBuysThisBar.push({ id, order: o });
|
|
434
|
-
else if (o.side === 'sell' && hi >= o.price) filledSellsThisBar.push({ id, order: o });
|
|
435
|
-
}
|
|
436
|
-
touchedOrders += filledBuysThisBar.length + filledSellsThisBar.length;
|
|
437
|
-
// Base held BEFORE this bar's intakes — unlinked sells may only
|
|
438
|
-
// dispose against pre-existing funds (same-bar funding not assumed).
|
|
439
|
-
const disposablesAtBarStart = inventory.units;
|
|
440
|
-
|
|
441
|
-
// ── Buy intakes first: base enters the inventory pool, refill armed
|
|
442
|
-
// at the ADJACENT MASTER-RAIL NODE above (cooldown blocks same-bar).
|
|
443
|
-
for (const fb of filledBuysThisBar) {
|
|
444
|
-
orders.delete(fb.id);
|
|
445
|
-
inventory.units += fb.order.size;
|
|
446
|
-
inventory.cost += fb.order.price * fb.order.size;
|
|
447
|
-
const upIdx = (fb.order.railIdx ?? -1) + 1;
|
|
448
|
-
const refillPrice = activeRail[upIdx] ?? fb.order.price * stepUpFrac;
|
|
449
|
-
orders.set(nextOrderId++, {
|
|
450
|
-
side: 'sell',
|
|
451
|
-
price: refillPrice,
|
|
452
|
-
size: fb.order.size,
|
|
453
|
-
railIdx: upIdx,
|
|
454
|
-
linkedBuyPrice: fb.order.price,
|
|
455
|
-
linkedEntryBar: i,
|
|
456
|
-
cooldownUntil: i + 1,
|
|
457
|
-
});
|
|
458
|
-
btsFeesBts += makerCreateFeeBts;
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
// ── Sell disposals: linked refills book the one-rail-hop rotation;
|
|
462
|
-
// unlinked sells need held inventory. Linked resolve FIRST.
|
|
463
|
-
filledSellsThisBar.sort((a, b) => ((a.order.linkedBuyPrice != null ? 0 : 1) - (b.order.linkedBuyPrice != null ? 0 : 1)));
|
|
464
|
-
let disposables = disposablesAtBarStart;
|
|
465
|
-
for (const fs of filledSellsThisBar) {
|
|
466
|
-
const order = fs.order;
|
|
467
|
-
const size = order.size;
|
|
468
|
-
if (order.linkedBuyPrice != null) {
|
|
469
|
-
const grossPct = (order.price / order.linkedBuyPrice - 1) * 100;
|
|
470
|
-
const netPct = grossPct - feeRoundtripPct;
|
|
471
|
-
totalGrossUnits += size * (grossPct / 100);
|
|
472
|
-
totalProfitUnits += size * (netPct / 100);
|
|
473
|
-
runningProfit += size * (netPct / 100);
|
|
474
|
-
cyclesTotal++;
|
|
475
|
-
rotationCount++;
|
|
476
|
-
matchedPairs++;
|
|
477
|
-
matchedOpenDurationBars += Math.abs(i - order.linkedEntryBar);
|
|
478
|
-
// Dispose the base this rotation bought (at pool-average cost).
|
|
479
|
-
const applied = Math.min(size, inventory.units);
|
|
480
|
-
inventory.cost -= applied * invAvgEntry();
|
|
481
|
-
inventory.units -= applied;
|
|
482
|
-
// Its disposal also drains the pre-bar funding budget —
|
|
483
|
-
// otherwise later unlinked sales could overspend stock.
|
|
484
|
-
disposables -= applied;
|
|
485
|
-
// Freed quote re-bids the ADJACENT RAIL NODE below.
|
|
486
|
-
const downIdx = (order.railIdx ?? 0) - 1;
|
|
487
|
-
const rebidPrice = activeRail[downIdx] ?? order.price / stepUpFrac;
|
|
488
|
-
orders.delete(fs.id);
|
|
489
|
-
orders.set(nextOrderId++, {
|
|
490
|
-
side: 'buy',
|
|
491
|
-
price: rebidPrice,
|
|
492
|
-
size,
|
|
493
|
-
railIdx: downIdx,
|
|
494
|
-
linkedBuyPrice: null,
|
|
495
|
-
linkedEntryBar: -1,
|
|
496
|
-
cooldownUntil: i + 1,
|
|
497
|
-
});
|
|
498
|
-
btsFeesBts += makerCreateFeeBts;
|
|
499
|
-
} else if (disposables >= size - 1e-12) {
|
|
500
|
-
const avgEntry = invAvgEntry();
|
|
501
|
-
const grossPct = (order.price / avgEntry - 1) * 100;
|
|
502
|
-
const netPct = grossPct - feeRoundtripPct;
|
|
503
|
-
totalGrossUnits += size * (grossPct / 100);
|
|
504
|
-
totalProfitUnits += size * (netPct / 100);
|
|
505
|
-
runningProfit += size * (netPct / 100);
|
|
506
|
-
cyclesTotal++;
|
|
507
|
-
inventorySaleCount++;
|
|
508
|
-
matchedPairs++;
|
|
509
|
-
inventory.cost -= avgEntry * size;
|
|
510
|
-
inventory.units -= size;
|
|
511
|
-
disposables -= size;
|
|
512
|
-
orders.delete(fs.id); // sold bag is gone; slot not re-armed
|
|
513
|
-
} else {
|
|
514
|
-
// Unfundable (not enough base): stays open, retries next bar.
|
|
515
|
-
order.cooldownUntil = i + 1;
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
// Track max inventory exposure (long-only)
|
|
520
|
-
if (inventory.units > maxInventoryExposure) maxInventoryExposure = inventory.units;
|
|
521
|
-
|
|
522
|
-
// ── Drawdown tracking ───────────────────────────────────────────
|
|
523
|
-
// Realized equity only: carried bags are reported informationally and
|
|
524
|
-
// excluded from scoring, so their (unbounded, balance-free) marks must
|
|
525
|
-
// not distort the risk term either. Bag risk stays visible via
|
|
526
|
-
// finalInventoryUnits / finalInventoryMarkUnits.
|
|
527
|
-
const equityProfit = runningProfit;
|
|
528
|
-
if (equityProfit > peakEquityProfit) peakEquityProfit = equityProfit;
|
|
529
|
-
const dd = peakEquityProfit - equityProfit;
|
|
530
|
-
if (dd > maxDrawdown) maxDrawdown = dd;
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
// ── End-of-run inventory mark (informational, NOT in profit) ────────
|
|
534
|
-
// Bought-and-held base is real carried risk but unrealized bag marks are
|
|
535
|
-
// excluded from netProfit/scoring so trend combos can't dump phantom
|
|
536
|
-
// paper profit into the objective. Drawdown likewise tracks REALIZED
|
|
537
|
-
// equity only; bag risk stays visible through these info fields.
|
|
538
|
-
inventoryExposure = inventory.units;
|
|
539
|
-
const lastClose = candles.length > 0 ? candles[candles.length - 1].close : NaN;
|
|
540
|
-
const finalInventoryMark = markInventoryAtPrice(inventory, lastClose, feeRoundtripPct);
|
|
541
|
-
|
|
542
|
-
const fillEfficiency = touchedOrders > 0 ? (cyclesTotal / touchedOrders) * 100 : 0;
|
|
543
|
-
const pairsPerDay = liveBars > 0 ? matchedPairs / (liveBars / 24) : 0;
|
|
544
|
-
const avgOpenDurationBars = rotationCount > 0 ? matchedOpenDurationBars / rotationCount : 0;
|
|
545
|
-
const avgImbalance = imbalanceSamples > 0 ? imbalanceSum / imbalanceSamples : 0;
|
|
546
|
-
const avgProfitPerPair = matchedPairs > 0 ? totalProfitUnits / matchedPairs : 0;
|
|
547
|
-
const profitPerCapital = capital > 0 ? totalProfitUnits / (capital * 2) : 0; // total capital = 2 sides
|
|
548
|
-
const maxDrawdownPct = capital > 0 ? (maxDrawdown / (capital * 2)) * 100 : 0;
|
|
549
|
-
const avgGridAgeBars = liveBars > 0 ? gridAgeSumBars / liveBars : 0;
|
|
550
|
-
const avgCenterDriftPct = liveBars > 0 ? centerDriftSumPct / liveBars : 0;
|
|
551
|
-
const nearThresholdBarsPct = liveBars > 0 ? (nearThresholdBars / liveBars) * 100 : 0;
|
|
552
|
-
const avgTriggerDriftPct = repositionCount > 0 ? triggerDriftSumPct / repositionCount : 0;
|
|
553
|
-
const avgCancelOrdersPerReposition = repositionCount > 0 ? canceledOnReposition / repositionCount : 0;
|
|
554
|
-
// Exact BTS fee totals (creates + cancels + per-cycle refills), not an
|
|
555
|
-
// estimate — the live bot pays the same per-op fees.
|
|
556
|
-
const totalRepositionFeesBts = btsFeesBts;
|
|
557
|
-
const feePerDayBts = liveBars > 0 ? totalRepositionFeesBts / (liveBars / 24) : 0;
|
|
558
|
-
const estimatedFeePerRepositionBts = repositionCount > 0 ? totalRepositionFeesBts / repositionCount : 0;
|
|
559
|
-
const totalRepositionFeeUnits = totalRepositionFeesBts * txFeePrice;
|
|
560
|
-
const netProfitUnits = totalProfitUnits - totalRepositionFeeUnits;
|
|
561
|
-
const netProfitPerCapital = capital > 0 ? netProfitUnits / (capital * 2) : 0;
|
|
562
|
-
|
|
563
|
-
// Score: profit per capital scaled by activity (log pairs to avoid pure frequency chasing)
|
|
564
|
-
const activityBonus = matchedPairs > 0 ? Math.log10(matchedPairs) : null;
|
|
565
|
-
const grossScore = activityBonus == null ? -Infinity : (profitPerCapital * 100 * activityBonus - maxDrawdownPct * 0.5);
|
|
566
|
-
const netScore = activityBonus == null ? -Infinity : (netProfitPerCapital * 100 * activityBonus - maxDrawdownPct * 0.5);
|
|
567
|
-
const score = netScore;
|
|
568
|
-
|
|
569
|
-
return {
|
|
570
|
-
weightName,
|
|
571
|
-
spreadPct,
|
|
572
|
-
incrementPct: incrementPct * 100, // store as %
|
|
573
|
-
maxMinRatio,
|
|
574
|
-
matchedPairs,
|
|
575
|
-
cyclesTotal,
|
|
576
|
-
rotationCount,
|
|
577
|
-
inventorySaleCount,
|
|
578
|
-
touchedOrders,
|
|
579
|
-
fillEfficiency,
|
|
580
|
-
totalProfitUnits,
|
|
581
|
-
totalGrossUnits,
|
|
582
|
-
finalInventoryUnits: inventoryExposure,
|
|
583
|
-
finalInventoryAvgEntry: inventory.units > 0 ? inventory.cost / inventory.units : 0,
|
|
584
|
-
finalInventoryMarkUnits: finalInventoryMark.profitUnits, // informational
|
|
585
|
-
profitPerCapital,
|
|
586
|
-
pairsPerDay,
|
|
587
|
-
avgOpenDurationBars,
|
|
588
|
-
avgProfitPerPair,
|
|
589
|
-
peakOpenOrders,
|
|
590
|
-
avgImbalance,
|
|
591
|
-
canceledOnReposition,
|
|
592
|
-
repositionCount,
|
|
593
|
-
driftTriggerCount,
|
|
594
|
-
slopeTriggerCount,
|
|
595
|
-
maxDrawdown,
|
|
596
|
-
maxDrawdownPct,
|
|
597
|
-
maxInventoryExposure,
|
|
598
|
-
avgGridAgeBars,
|
|
599
|
-
maxGridAgeBars,
|
|
600
|
-
avgCenterDriftPct,
|
|
601
|
-
maxCenterDriftPct,
|
|
602
|
-
nearThresholdBarsPct,
|
|
603
|
-
avgTriggerDriftPct,
|
|
604
|
-
offsetAppliedCount,
|
|
605
|
-
makerCreateFeeBts,
|
|
606
|
-
btsCancelFee,
|
|
607
|
-
avgCancelOrdersPerReposition,
|
|
608
|
-
estimatedFeePerRepositionBts,
|
|
609
|
-
totalRepositionFeesBts,
|
|
610
|
-
feePerDayBts,
|
|
611
|
-
netProfitUnits,
|
|
612
|
-
netProfitPerCapital,
|
|
613
|
-
ordersPerSide,
|
|
614
|
-
grossScore,
|
|
615
|
-
netScore,
|
|
616
|
-
score,
|
|
617
|
-
};
|
|
618
|
-
}
|
|
619
|
-
|
|
620
|
-
// ── Per-AMA sweep logic (runs in main thread or worker) ─────────────────────
|
|
621
|
-
|
|
622
|
-
function sweepOneAma(strategy: any, candles: any[], closes: number[], weightEntries: [string, number][], cfg: any) {
|
|
623
|
-
const amaValues = calculateAMA(closes, { erPeriod: strategy.er, fastPeriod: strategy.fast, slowPeriod: strategy.slow });
|
|
624
|
-
// Production-aligned warmup: ER window + convergence (getAmaWarmupBars).
|
|
625
|
-
const warmupBars = getAmaWarmupBars(strategy.er, strategy.slow, 0, strategy.fast);
|
|
626
|
-
let best: any = null;
|
|
627
|
-
const top5: any[] = [];
|
|
628
|
-
const allSims: any[] = [];
|
|
629
|
-
let evaluated = 0;
|
|
630
|
-
const minSpreadFactor = Number.isFinite(cfg.minSpreadFactor) && cfg.minSpreadFactor > 0 ? cfg.minSpreadFactor : null;
|
|
631
|
-
|
|
632
|
-
for (const spreadPct of cfg.spreadValues) {
|
|
633
|
-
for (const incrementPctRaw of cfg.incrementValues) {
|
|
634
|
-
if (spreadPct < cfg.feeRoundtripPct + 0.01) continue;
|
|
635
|
-
if (minSpreadFactor != null && spreadPct < (incrementPctRaw * minSpreadFactor)) continue;
|
|
636
|
-
for (const maxMinRatio of cfg.ratioValues) {
|
|
637
|
-
for (const [weightName, weightFactor] of weightEntries) {
|
|
638
|
-
evaluated++;
|
|
639
|
-
const sim = simulatePersistentGrid(candles, amaValues, {
|
|
640
|
-
spreadPct,
|
|
641
|
-
incrementPct: incrementPctRaw / 100,
|
|
642
|
-
maxMinRatio,
|
|
643
|
-
maxOrders: cfg.maxOrders,
|
|
644
|
-
feeRoundtripPct: cfg.feeRoundtripPct,
|
|
645
|
-
capital: cfg.capital,
|
|
646
|
-
repositionThreshold: cfg.repositionPct / 100,
|
|
647
|
-
asymmetricBounds: cfg.asymmetricBounds,
|
|
648
|
-
btsCreateFee: cfg.btsCreateFee,
|
|
649
|
-
btsCancelFee: cfg.btsCancelFee,
|
|
650
|
-
makerCreateFactor: cfg.makerCreateFactor,
|
|
651
|
-
txFeePrice: cfg.txFeePrice,
|
|
652
|
-
warmupBars,
|
|
653
|
-
}, weightName, weightFactor);
|
|
654
|
-
|
|
655
|
-
if (!best || sim.score > best.score) best = sim;
|
|
656
|
-
|
|
657
|
-
if (sim.matchedPairs > 0) {
|
|
658
|
-
const t5key = `${sim.spreadPct}|${sim.incrementPct}|${sim.maxMinRatio}|${sim.weightName}`;
|
|
659
|
-
const existing = top5.findIndex((t) =>
|
|
660
|
-
`${t.spreadPct}|${t.incrementPct}|${t.maxMinRatio}|${t.weightName}` === t5key);
|
|
661
|
-
if (existing < 0) {
|
|
662
|
-
top5.push(sim);
|
|
663
|
-
top5.sort((a, b) => b.score - a.score);
|
|
664
|
-
if (top5.length > 5) top5.length = 5;
|
|
665
|
-
}
|
|
666
|
-
allSims.push(sim);
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
}
|
|
670
|
-
}
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
return { strategy, best, top5, allSims, evaluated };
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
// ── Worker thread handler ───────────────────────────────────────────────────
|
|
677
|
-
|
|
678
|
-
if (!isMainThread) {
|
|
679
|
-
const { strategy, candles, closes, weightEntries, cfg } = workerData;
|
|
680
|
-
const result = sweepOneAma(strategy, candles, closes, weightEntries, cfg);
|
|
681
|
-
parentPort!.postMessage(result);
|
|
682
|
-
// Exit naturally: an explicit process.exit(0) here can race the
|
|
683
|
-
// postMessage flush and silently drop the result (same pattern as
|
|
684
|
-
// optimizer_high_resolution.ts workers, which exit on their own).
|
|
685
|
-
}
|
|
686
|
-
|
|
687
|
-
// ── Parallel dispatch (main thread) ─────────────────────────────────────────
|
|
688
|
-
|
|
689
|
-
function runParallel(strategies: any[], candles: any[], closes: number[], weightEntries: [string, number][], cfg: any): Promise<any[]> {
|
|
690
|
-
const numCpus = Math.min(os.cpus().length, strategies.length);
|
|
691
|
-
console.log(` Workers: ${numCpus} threads (${os.cpus().length} CPUs available)\n`);
|
|
692
|
-
|
|
693
|
-
return Promise.all(strategies.map((strategy) => {
|
|
694
|
-
return new Promise((resolve, reject) => {
|
|
695
|
-
// ESM: resolve this module's path from import.meta.url
|
|
696
|
-
// (__filename is undefined in ES modules).
|
|
697
|
-
const worker = new Worker(fileURLToPath(import.meta.url), {
|
|
698
|
-
workerData: { strategy, candles, closes, weightEntries, cfg },
|
|
699
|
-
});
|
|
700
|
-
worker.on('message', resolve);
|
|
701
|
-
worker.on('error', reject);
|
|
702
|
-
worker.on('exit', (code) => {
|
|
703
|
-
if (code !== 0) reject(new Error(`Worker exited with code ${code}`));
|
|
704
|
-
});
|
|
705
|
-
});
|
|
706
|
-
}));
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
// ── Main ────────────────────────────────────────────────────────────────────
|
|
710
|
-
|
|
711
|
-
async function run() {
|
|
712
|
-
const cfg = parseArgs();
|
|
713
|
-
|
|
714
|
-
const loaded = loadLpData(cfg.dataPath!);
|
|
715
|
-
const candles = loaded.candles;
|
|
716
|
-
const closes = candles.map((c: any) => c.close);
|
|
717
|
-
const strategies = loadAmaStrategies(cfg.resultsPath!);
|
|
718
|
-
|
|
719
|
-
const weightEntries = Object.entries(WEIGHT_PROFILES);
|
|
720
|
-
const totalCombos = cfg.spreadValues.length * cfg.incrementValues.length *
|
|
721
|
-
cfg.ratioValues.length * weightEntries.length;
|
|
722
|
-
|
|
723
|
-
console.log('================================================================================');
|
|
724
|
-
console.log(' AMA SWEEP BACKTEST — persistent grid + weight profiles');
|
|
725
|
-
console.log('================================================================================');
|
|
726
|
-
console.log(` Data: ${path.basename(cfg.dataPath!)} (${candles.length} candles, ~${(candles.length / 24).toFixed(0)} days)`);
|
|
727
|
-
console.log(` AMAs: ${strategies.map((s) => s.id).join(', ')}`);
|
|
728
|
-
console.log(` Weights: ${weightEntries.map(([n, w]) => `${n}(${w})`).join(', ')}`);
|
|
729
|
-
console.log(` Spread: ${cfg.spreadValues[0]}..${cfg.spreadValues[cfg.spreadValues.length - 1]}% (${cfg.spreadValues.length})`);
|
|
730
|
-
console.log(` Increment: ${cfg.incrementValues[0]}..${cfg.incrementValues[cfg.incrementValues.length - 1]}% (${cfg.incrementValues.length})`);
|
|
731
|
-
console.log(` Ratio: ${cfg.ratioValues[0]}..${cfg.ratioValues[cfg.ratioValues.length - 1]} (${cfg.ratioValues.length})`);
|
|
732
|
-
console.log(` Max orders: ${cfg.maxOrders}/side (size cap) | Capital: ${cfg.capital}/side | Fee: ${cfg.feeRoundtripPct}%`);
|
|
733
|
-
console.log(` Spread floor: > fee (${cfg.feeRoundtripPct}%)`);
|
|
734
|
-
console.log(` Reset (A): ${cfg.repositionPct}% AMA drift from grid center (ratchet)`);
|
|
735
|
-
console.log(` Asym. bounds: ${cfg.asymmetricBounds ? 'ON — slope reset (B) + grid price offset enabled (whitelist semantics)' : 'OFF — typical non-whitelisted bot (production default)'}`);
|
|
736
|
-
console.log(` Reset (B): |slope - slope@lastReset| >= ${fmt((SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT, 4)}% (lookback ${SLOPE_LOOKBACK_BARS})${cfg.asymmetricBounds ? '' : ' [gated off]'}`);
|
|
737
|
-
console.log(` Tx model: create=${fmt(cfg.btsCreateFee, 5)} BTS, cancel=${fmt(cfg.btsCancelFee, 5)} BTS, maker=${fmt(cfg.makerCreateFactor * 100, 1)}%, 1 BTS=${fmt(cfg.txFeePrice, 2)} units`);
|
|
738
|
-
console.log(` Combos/AMA: ${totalCombos} | Total: ${totalCombos * strategies.length}\n`);
|
|
739
|
-
|
|
740
|
-
// ── Run AMA sweeps in parallel (one worker per AMA strategy) ──────
|
|
741
|
-
const byAma: any[] = [];
|
|
742
|
-
const allResults: any[] = [];
|
|
743
|
-
|
|
744
|
-
const workerResults = await runParallel(strategies, candles, closes, weightEntries, cfg);
|
|
745
|
-
|
|
746
|
-
for (const wr of workerResults) {
|
|
747
|
-
byAma.push(wr);
|
|
748
|
-
for (const sim of wr.allSims) {
|
|
749
|
-
allResults.push({ strategy: wr.strategy, sim });
|
|
750
|
-
}
|
|
751
|
-
const b = wr.best;
|
|
752
|
-
const bestLabel = b && b.matchedPairs > 0
|
|
753
|
-
? `score=${fmt(b.score, 1)} pairs=${b.matchedPairs} net/cap=${fmt(b.netProfitPerCapital * 100, 1)}% gross=${fmt(b.profitPerCapital * 100, 1)}%`
|
|
754
|
-
: 'no fills';
|
|
755
|
-
process.stdout.write(` ${wr.strategy.id} (ER=${wr.strategy.er}, F=${wr.strategy.fast}, S=${wr.strategy.slow}): ${wr.evaluated} combos, ${bestLabel}\n`);
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
// ── Per-AMA best ────────────────────────────────────────────────────────
|
|
759
|
-
console.log('\n================================================================================');
|
|
760
|
-
console.log(' BEST PARAMS PER AMA');
|
|
761
|
-
console.log('================================================================================');
|
|
762
|
-
console.log('AMA | wt | spr% | inc% | ratio | nOrd | pairs | net/cap | gross/cap | drift | fee/d | score');
|
|
763
|
-
console.log('------+-------+-------+-------+-------+------+--------+---------+-----------+-------+-------+------');
|
|
764
|
-
for (const row of byAma) {
|
|
765
|
-
const b = row.best;
|
|
766
|
-
if (!b || b.matchedPairs === 0) {
|
|
767
|
-
console.log(`${row.strategy.id.padEnd(5)} | (no fills)`);
|
|
768
|
-
continue;
|
|
769
|
-
}
|
|
770
|
-
console.log(
|
|
771
|
-
`${row.strategy.id.padEnd(5)} | ` +
|
|
772
|
-
`${b.weightName.padEnd(5)} | ` +
|
|
773
|
-
`${fmt(b.spreadPct, 1).padStart(5)} | ` +
|
|
774
|
-
`${fmt(b.incrementPct, 1).padStart(5)} | ` +
|
|
775
|
-
`${fmt(b.maxMinRatio, 2).padStart(5)} | ` +
|
|
776
|
-
`${String(b.ordersPerSide).padStart(4)} | ` +
|
|
777
|
-
`${String(b.matchedPairs).padStart(6)} | ` +
|
|
778
|
-
`${fmt(b.netProfitPerCapital * 100, 2).padStart(7)}% | ` +
|
|
779
|
-
`${fmt(b.profitPerCapital * 100, 2).padStart(10)}% | ` +
|
|
780
|
-
`${fmt(b.avgCenterDriftPct, 2).padStart(5)}% | ` +
|
|
781
|
-
`${fmt(b.feePerDayBts, 2).padStart(5)} | ` +
|
|
782
|
-
`${fmt(b.score, 1).padStart(6)}`
|
|
783
|
-
);
|
|
784
|
-
}
|
|
785
|
-
|
|
786
|
-
// ── Top 5 per AMA ───────────────────────────────────────────────────────
|
|
787
|
-
for (const row of byAma) {
|
|
788
|
-
if (row.top5.length === 0) continue;
|
|
789
|
-
console.log(`\n ${row.strategy.id} — Top 5:`);
|
|
790
|
-
console.log(' # | wt | spr% | inc% | ratio | nOrd | pairs | net/cap | drift | gAge | fee/d | score');
|
|
791
|
-
console.log(' --+-------+-------+-------+-------+------+--------+---------+-------+------+-------+------');
|
|
792
|
-
row.top5.forEach((b: any, idx: number) => {
|
|
793
|
-
console.log(
|
|
794
|
-
` ${idx + 1} | ` +
|
|
795
|
-
`${b.weightName.padEnd(5)} | ` +
|
|
796
|
-
`${fmt(b.spreadPct, 1).padStart(5)} | ` +
|
|
797
|
-
`${fmt(b.incrementPct, 1).padStart(5)} | ` +
|
|
798
|
-
`${fmt(b.maxMinRatio, 2).padStart(5)} | ` +
|
|
799
|
-
`${String(b.ordersPerSide).padStart(4)} | ` +
|
|
800
|
-
`${String(b.matchedPairs).padStart(6)} | ` +
|
|
801
|
-
`${fmt(b.netProfitPerCapital * 100, 2).padStart(7)}% | ` +
|
|
802
|
-
`${fmt(b.avgCenterDriftPct, 2).padStart(5)}% | ` +
|
|
803
|
-
`${fmt(b.avgGridAgeBars, 0).padStart(4)} | ` +
|
|
804
|
-
`${fmt(b.feePerDayBts, 2).padStart(5)} | ` +
|
|
805
|
-
`${fmt(b.score, 1).padStart(6)}`
|
|
806
|
-
);
|
|
807
|
-
});
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
// ── Global ranking (deduplicated) ───────────────────────────────────────
|
|
811
|
-
allResults.sort((a, b) => b.sim.score - a.sim.score);
|
|
812
|
-
const seen = new Set();
|
|
813
|
-
const deduped: any[] = [];
|
|
814
|
-
for (const r of allResults) {
|
|
815
|
-
const key = `${r.strategy.id}|${r.sim.spreadPct}|${r.sim.incrementPct}|${r.sim.maxMinRatio}|${r.sim.weightName}`;
|
|
816
|
-
if (seen.has(key)) continue;
|
|
817
|
-
seen.add(key);
|
|
818
|
-
deduped.push(r);
|
|
819
|
-
}
|
|
820
|
-
|
|
821
|
-
if (deduped.length === 0) {
|
|
822
|
-
console.log('\n NO CONFIGURATIONS PRODUCED ANY MATCHED PAIRS.');
|
|
823
|
-
return;
|
|
824
|
-
}
|
|
825
|
-
|
|
826
|
-
const topN = Math.min(cfg.topN, deduped.length);
|
|
827
|
-
console.log(`\n================================================================================`);
|
|
828
|
-
console.log(` GLOBAL TOP ${topN}`);
|
|
829
|
-
console.log('================================================================================');
|
|
830
|
-
console.log('# | AMA | wt | spr% | inc% | ratio | nOrd | pairs | net/cap | drift | fee/d | score');
|
|
831
|
-
console.log('---+-------+-------+-------+-------+-------+------+--------+---------+-------+-------+------');
|
|
832
|
-
for (let i = 0; i < topN; i++) {
|
|
833
|
-
const { strategy, sim } = deduped[i];
|
|
834
|
-
console.log(
|
|
835
|
-
`${String(i + 1).padStart(2)} | ` +
|
|
836
|
-
`${strategy.id.padEnd(5)} | ` +
|
|
837
|
-
`${sim.weightName.padEnd(5)} | ` +
|
|
838
|
-
`${fmt(sim.spreadPct, 1).padStart(5)} | ` +
|
|
839
|
-
`${fmt(sim.incrementPct, 1).padStart(5)} | ` +
|
|
840
|
-
`${fmt(sim.maxMinRatio, 2).padStart(5)} | ` +
|
|
841
|
-
`${String(sim.ordersPerSide).padStart(4)} | ` +
|
|
842
|
-
`${String(sim.matchedPairs).padStart(6)} | ` +
|
|
843
|
-
`${fmt(sim.netProfitPerCapital * 100, 2).padStart(7)}% | ` +
|
|
844
|
-
`${fmt(sim.avgCenterDriftPct, 2).padStart(5)}% | ` +
|
|
845
|
-
`${fmt(sim.feePerDayBts, 2).padStart(5)} | ` +
|
|
846
|
-
`${fmt(sim.score, 1).padStart(6)}`
|
|
847
|
-
);
|
|
848
|
-
}
|
|
849
|
-
|
|
850
|
-
// ── Winner ──────────────────────────────────────────────────────────────
|
|
851
|
-
const winner = deduped[0];
|
|
852
|
-
console.log(`\n================================================================================`);
|
|
853
|
-
console.log(` WINNER`);
|
|
854
|
-
console.log('================================================================================');
|
|
855
|
-
console.log(` AMA: ${winner.strategy.id} (ER=${winner.strategy.er}, Fast=${winner.strategy.fast}, Slow=${winner.strategy.slow})`);
|
|
856
|
-
console.log(` Weight: ${winner.sim.weightName} (${WEIGHT_PROFILES[winner.sim.weightName as keyof typeof WEIGHT_PROFILES]})`);
|
|
857
|
-
console.log(` Spread: ${fmt(winner.sim.spreadPct, 1)}%`);
|
|
858
|
-
console.log(` Increment: ${fmt(winner.sim.incrementPct, 1)}%`);
|
|
859
|
-
console.log(` Ratio: ${fmt(winner.sim.maxMinRatio, 1)}x`);
|
|
860
|
-
console.log(` Pairs: ${winner.sim.matchedPairs} (${fmt(winner.sim.pairsPerDay, 2)}/day)`);
|
|
861
|
-
console.log(` Fill eff: ${fmt(winner.sim.fillEfficiency, 1)}%`);
|
|
862
|
-
console.log(` Profit/cap: gross ${fmt(winner.sim.profitPerCapital * 100, 2)}% | net ${fmt(winner.sim.netProfitPerCapital * 100, 2)}%`);
|
|
863
|
-
console.log(` Net profit: ${fmt(winner.sim.netProfitUnits, 0)} units after ${fmt(winner.sim.totalRepositionFeesBts, 1)} BTS reposition fees`);
|
|
864
|
-
console.log(` Avg/pair: ${fmt(winner.sim.avgProfitPerPair, 2)} units`);
|
|
865
|
-
console.log(` Max DD: ${fmt(winner.sim.maxDrawdownPct, 2)}%`);
|
|
866
|
-
console.log(` Repositions: ${winner.sim.repositionCount}`);
|
|
867
|
-
console.log(` Grid age: avg ${fmt(winner.sim.avgGridAgeBars, 1)} bars | max ${fmt(winner.sim.maxGridAgeBars, 0)} bars`);
|
|
868
|
-
console.log(` Drift: avg ${fmt(winner.sim.avgCenterDriftPct, 2)}% | max ${fmt(winner.sim.maxCenterDriftPct, 2)}% | near-threshold ${fmt(winner.sim.nearThresholdBarsPct, 1)}%`);
|
|
869
|
-
console.log(` Tx burn: ${fmt(winner.sim.estimatedFeePerRepositionBts, 4)} BTS/reposition | ${fmt(winner.sim.feePerDayBts, 2)} BTS/day (exact per-op totals)`);
|
|
870
|
-
console.log(` Cycles: ${winner.sim.cyclesTotal} rotations (${winner.sim.rotationCount} rail-step + ${winner.sim.inventorySaleCount} inventory sales)`);
|
|
871
|
-
console.log(` Carried: ${fmt(winner.sim.finalInventoryUnits, 4)} base @ ${fmt(winner.sim.finalInventoryAvgEntry, 6)} avg (mark ${fmt(winner.sim.finalInventoryMarkUnits, 2)} units — info only, not scored)`);
|
|
872
|
-
console.log(` Score: ${fmt(winner.sim.score, 2)}`);
|
|
873
|
-
|
|
874
|
-
// ── Save JSON ───────────────────────────────────────────────────────────
|
|
875
|
-
const outName = `ama_sweep_results_${path.basename(cfg.dataPath!, '.json')}.json`;
|
|
876
|
-
const outPath = path.join(PATHS.ANALYSIS.RESULTS_DIR, outName);
|
|
877
|
-
writeJSON(outPath, {
|
|
878
|
-
meta: {
|
|
879
|
-
generatedAt: new Date().toISOString(),
|
|
880
|
-
dataPath: path.relative(process.cwd(), cfg.dataPath!),
|
|
881
|
-
resultsPath: path.relative(process.cwd(), cfg.resultsPath!),
|
|
882
|
-
candles: candles.length,
|
|
883
|
-
days: candles.length / 24,
|
|
884
|
-
maxOrders: cfg.maxOrders,
|
|
885
|
-
capitalPerSide: cfg.capital,
|
|
886
|
-
feeRoundtripPct: cfg.feeRoundtripPct,
|
|
887
|
-
repositionPct: cfg.repositionPct,
|
|
888
|
-
asymmetricBounds: cfg.asymmetricBounds,
|
|
889
|
-
btsCreateFee: cfg.btsCreateFee,
|
|
890
|
-
btsCancelFee: cfg.btsCancelFee,
|
|
891
|
-
makerCreateFactor: cfg.makerCreateFactor,
|
|
892
|
-
txFeePrice: cfg.txFeePrice,
|
|
893
|
-
weightProfiles: WEIGHT_PROFILES,
|
|
894
|
-
search: {
|
|
895
|
-
spreadValues: cfg.spreadValues,
|
|
896
|
-
incrementValues: cfg.incrementValues,
|
|
897
|
-
ratioValues: cfg.ratioValues,
|
|
898
|
-
minSpreadFactor: cfg.minSpreadFactor,
|
|
899
|
-
combosPerAma: totalCombos,
|
|
900
|
-
totalCombos: totalCombos * strategies.length,
|
|
901
|
-
},
|
|
902
|
-
scoring: 'netProfitPerCapital * 100 * log10(max(1, matchedPairs)) - maxDrawdownPct * 0.5',
|
|
903
|
-
gridModel: 'production createOrderGrid port (shared with bot_fitting): master rail sqrt(1±inc) + gapSlots spread zone; slot rotation (filled buy re-offers one rail step up, freed quote re-bids one step down, ~increment% per completed rotation); unlinked sells execute only against held inventory at weighted-average entry; bought base carries across resets and the end-of-run inventory mark is informational (excluded from scoring); exact per-op BTS fees',
|
|
904
|
-
},
|
|
905
|
-
strategies,
|
|
906
|
-
perAma: byAma.map((row) => ({
|
|
907
|
-
strategy: row.strategy,
|
|
908
|
-
evaluated: row.evaluated,
|
|
909
|
-
best: row.best,
|
|
910
|
-
top5: row.top5,
|
|
911
|
-
})),
|
|
912
|
-
globalTop: deduped.slice(0, Math.max(cfg.topN, 20)).map(({ strategy, sim }) => ({
|
|
913
|
-
ama: strategy.id,
|
|
914
|
-
amaParams: { er: strategy.er, fast: strategy.fast, slow: strategy.slow },
|
|
915
|
-
...sim,
|
|
916
|
-
})),
|
|
917
|
-
winner: {
|
|
918
|
-
ama: winner.strategy.id,
|
|
919
|
-
amaParams: { er: winner.strategy.er, fast: winner.strategy.fast, slow: winner.strategy.slow },
|
|
920
|
-
...winner.sim,
|
|
921
|
-
},
|
|
922
|
-
});
|
|
923
|
-
|
|
924
|
-
console.log(`\nSaved: ${path.relative(process.cwd(), outPath)}`);
|
|
925
|
-
}
|
|
926
|
-
|
|
927
|
-
// Main-thread only: workers inherit process.argv[1], so the entry guard alone
|
|
928
|
-
// would also match inside workers and re-run main() there.
|
|
929
|
-
if (isMainThread && process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
930
|
-
run().catch((err) => { console.error(err); process.exit(1); });
|
|
931
|
-
}
|
|
932
|
-
|
|
933
|
-
export { WEIGHT_PROFILES, allocateFundsByWeights, buildGrid, markInventoryAtPrice, simulatePersistentGrid, sweepOneAma }
|
|
934
|
-
|