dexbot 1.6.10 → 1.6.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +50 -3
- package/README.md +3 -1
- package/analysis/README.md +51 -11
- package/analysis/bot_fitting/README.md +12 -0
- package/analysis/tradingview/README.md +3 -3
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +11 -37
- package/analysis/trend_detection/README.md +31 -0
- package/claw/docs/DEXBOT2_TUNING_CHEAT_SHEET.md +4 -3
- package/claw/modules/chain_broadcast.ts +7 -1
- package/claw/modules/claw_launcher.ts +1 -1
- package/claw/modules/launcher_mode_detector.ts +9 -2
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/account_resolver.d.ts +1 -1
- package/dist/analysis/account_resolver.js +15 -2
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.js +3 -4
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js +2 -7
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js +0 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.js +4 -4
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts +20 -4
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js +9 -6
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js +16 -12
- package/dist/analysis/analyze_args.d.ts +31 -0
- package/dist/analysis/analyze_args.js +41 -0
- package/dist/analysis/analyze_dynamic_weight.js +7 -20
- package/dist/analysis/analyze_kalman.js +7 -17
- package/dist/analysis/analyze_regime.js +7 -17
- package/dist/analysis/analyze_regime_windows.js +8 -18
- package/dist/analysis/analyze_risk_profile.js +8 -18
- package/dist/analysis/analyze_trade_heatmap.js +7 -17
- package/dist/analysis/analyze_volatility.js +7 -17
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts +220 -12
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js +55 -10
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts +34 -4
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js +72 -66
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.d.ts +21 -0
- package/dist/analysis/bot_fitting/backtest_lookback_drawdown.js +315 -0
- package/dist/analysis/bot_fitting/shared_utils.d.ts +7 -7
- package/dist/analysis/bot_fitting/shared_utils.js +2 -2
- package/dist/analysis/bot_key_utils.d.ts +18 -10
- package/dist/analysis/bot_key_utils.js +10 -17
- package/dist/analysis/bot_usage/discover_bot_accounts.js +44 -47
- package/dist/analysis/bot_usage/kibana_bot_queries.d.ts +1 -21
- package/dist/analysis/chain_pool.d.ts +3 -1
- package/dist/analysis/chart_ui.d.ts +5 -2
- package/dist/analysis/chart_ui.js +6 -3
- package/dist/analysis/chart_utils.d.ts +5 -5
- package/dist/analysis/chart_utils.js +9 -0
- package/dist/analysis/fills_cache.d.ts +64 -0
- package/dist/analysis/fills_cache.js +254 -0
- package/dist/analysis/fills_source.d.ts +2 -2
- package/dist/analysis/fills_source.js +19 -14
- package/dist/analysis/grid_correction_check.d.ts +1 -1
- package/dist/analysis/grid_correction_check.js +12 -11
- package/dist/analysis/math_utils.d.ts +7 -6
- package/dist/analysis/math_utils.js +5 -8
- package/dist/analysis/pnl_report.d.ts +39 -0
- package/dist/analysis/pnl_report.js +325 -0
- package/dist/analysis/price_sources.d.ts +8 -8
- package/dist/analysis/price_sources.js +5 -4
- package/dist/analysis/resolve_bot_accounts.js +2 -2
- package/dist/analysis/resolve_source.d.ts +1 -2
- package/dist/analysis/trade_profitability.d.ts +32 -2
- package/dist/analysis/trade_profitability.js +232 -106
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +17 -6
- package/dist/analysis/tradingview/analyze_tradingview.js +9 -10
- package/dist/analysis/tradingview/grid_reset_config.d.ts +42 -31
- package/dist/analysis/tradingview/grid_reset_config.js +35 -6
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +75 -8
- package/dist/analysis/tradingview/grid_reset_sim.js +42 -5
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts +69 -4
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +20 -20
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.d.ts +102 -0
- package/dist/analysis/trend_detection/backtest_ama_slope_huber.js +725 -0
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts +63 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js +27 -112
- package/dist/analysis/trend_detection/huber_scale_variants.d.ts +40 -0
- package/dist/analysis/trend_detection/huber_scale_variants.js +176 -0
- package/dist/analysis/trend_detection/kalman_chart_generator.d.ts +30 -1
- package/dist/analysis/trend_detection/kalman_chart_generator.js +3 -3
- package/dist/analysis/trend_detection/regime_chart_generator.d.ts +31 -1
- package/dist/analysis/trend_detection/regime_chart_generator.js +2 -2
- package/dist/analysis/trend_detection/volatility_chart_generator.d.ts +33 -1
- package/dist/credential-daemon.js +34 -20
- package/dist/dexbot.js +17 -14
- package/dist/market_adapter/candle_utils.d.ts +22 -18
- package/dist/market_adapter/candle_utils.js +24 -20
- package/dist/market_adapter/core/asymmetric_bounds.d.ts +13 -4
- package/dist/market_adapter/core/config_normalizers.d.ts +3 -3
- package/dist/market_adapter/core/kibana_candles.d.ts +53 -18
- package/dist/market_adapter/core/kibana_candles.js +9 -7
- package/dist/market_adapter/core/kibana_client.d.ts +9 -1
- package/dist/market_adapter/core/kibana_client.js +8 -7
- package/dist/market_adapter/core/kibana_market_candles.d.ts +3 -2
- package/dist/market_adapter/core/market_adapter_service.d.ts +297 -115
- package/dist/market_adapter/core/market_adapter_service.js +184 -101
- package/dist/market_adapter/core/strategies/ama.d.ts +10 -2
- package/dist/market_adapter/core/strategies/ama.js +7 -32
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts +14 -1
- package/dist/market_adapter/core/strategies/ama_slope_model.js +12 -34
- package/dist/market_adapter/core/strategies/atr/calculator.d.ts +7 -2
- package/dist/market_adapter/core/strategies/atr/calculator.js +2 -34
- package/dist/market_adapter/core/strategies/collateral_manager.d.ts +7 -1
- package/dist/market_adapter/core/strategies/collateral_manager.js +0 -22
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +36 -8
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +9 -9
- package/dist/market_adapter/core/strategies/regime_gate.d.ts +24 -15
- package/dist/market_adapter/core/strategies/regime_gate.js +4 -31
- package/dist/market_adapter/core/strategies/regime_interp.d.ts +7 -1
- package/dist/market_adapter/core/strategies/regime_interp.js +14 -22
- package/dist/market_adapter/core/strategies/volatility_shift.d.ts +11 -1
- package/dist/market_adapter/core/strategies/volatility_shift.js +0 -13
- package/dist/market_adapter/inputs/cex_candle_parsing.d.ts +29 -0
- package/dist/market_adapter/inputs/cex_candle_parsing.js +52 -0
- package/dist/market_adapter/inputs/fetch_book_data.d.ts +20 -4
- package/dist/market_adapter/inputs/fetch_book_data.js +3 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js +97 -226
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts +42 -7
- package/dist/market_adapter/inputs/fetch_lp_data.js +22 -15
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts +74 -15
- package/dist/market_adapter/inputs/kibana_feed_source.js +29 -22
- package/dist/market_adapter/inputs/kibana_source.d.ts +25 -3
- package/dist/market_adapter/inputs/kibana_source.js +2 -2
- package/dist/market_adapter/inputs/window_cache.d.ts +99 -94
- package/dist/market_adapter/inputs/window_cache.js +8 -8
- package/dist/market_adapter/interval_utils.d.ts +4 -4
- package/dist/market_adapter/log_format.d.ts +6 -6
- package/dist/market_adapter/log_format.js +28 -22
- package/dist/market_adapter/lp_chart_core.d.ts +22 -1
- package/dist/market_adapter/lp_chart_core.js +26 -192
- package/dist/market_adapter/lp_chart_runner.d.ts +7 -7
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts +41 -6
- package/dist/market_adapter/lp_chart_strategy_loader.js +8 -7
- package/dist/market_adapter/market_adapter.d.ts +94 -33
- package/dist/market_adapter/market_adapter.js +69 -75
- package/dist/market_adapter/utils/adapter_client.d.ts +3 -3
- package/dist/market_adapter/utils/adapter_client.js +2 -2
- package/dist/market_adapter/utils/atomic_write.d.ts +8 -1
- package/dist/market_adapter/utils/chain.d.ts +50 -41
- package/dist/market_adapter/utils/chain.js +40 -46
- package/dist/market_adapter/utils/data_discovery.d.ts +4 -1
- package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts +12 -3
- package/dist/market_adapter/utils/file_json_cache.d.ts +2 -2
- package/dist/market_adapter/utils/file_lock.d.ts +28 -14
- package/dist/market_adapter/utils/file_lock.js +36 -32
- package/dist/market_adapter/utils/native_history.d.ts +9 -2
- package/dist/market_adapter/utils/native_history.js +35 -28
- package/dist/modules/account_bots.d.ts +577 -21
- package/dist/modules/account_bots.js +182 -158
- package/dist/modules/account_orders.d.ts +66 -30
- package/dist/modules/account_orders.js +22 -20
- package/dist/modules/authority_resolver.d.ts +12 -2
- package/dist/modules/authority_resolver.js +15 -8
- package/dist/modules/bitshares-native/chain_client.d.ts +38 -3
- package/dist/modules/bitshares-native/chain_client.js +45 -46
- package/dist/modules/bitshares-native/crypto/ecc.browser.js +11 -171
- package/dist/modules/bitshares-native/crypto/ecc.js +13 -176
- package/dist/modules/bitshares-native/crypto/ecc_core.d.ts +33 -0
- package/dist/modules/bitshares-native/crypto/ecc_core.js +213 -0
- package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts +2 -1
- package/dist/modules/bitshares-native/crypto/ecc_selector.js +1 -13
- package/dist/modules/bitshares-native/index.d.ts +1 -1
- package/dist/modules/bitshares-native/lru_cache.d.ts +7 -7
- package/dist/modules/bitshares-native/resolvers.d.ts +18 -6
- package/dist/modules/bitshares-native/serial/lazy_buffer.d.ts +4 -0
- package/dist/modules/bitshares-native/serial/lazy_buffer.js +21 -0
- package/dist/modules/bitshares-native/serial/operations.d.ts +1 -1
- package/dist/modules/bitshares-native/serial/serializer.d.ts +16 -12
- package/dist/modules/bitshares-native/serial/serializer.js +7 -13
- package/dist/modules/bitshares-native/serial/types.d.ts +25 -16
- package/dist/modules/bitshares-native/serial/types.js +55 -62
- package/dist/modules/bitshares-native/signing_client.d.ts +32 -2
- package/dist/modules/bitshares-native/signing_client.js +19 -14
- package/dist/modules/bitshares-native/subscriptions.d.ts +81 -1
- package/dist/modules/bitshares-native/subscriptions.js +12 -12
- package/dist/modules/bitshares-native/transport.d.ts +5 -4
- package/dist/modules/bitshares-native/transport.js +5 -4
- package/dist/modules/bitshares-native/tx/builder.d.ts +40 -5
- package/dist/modules/bitshares-native/tx/builder.js +4 -3
- package/dist/modules/bitshares-native/tx/tx_cache.d.ts +4 -4
- package/dist/modules/bitshares_client.d.ts +45 -13
- package/dist/modules/bitshares_client.js +28 -19
- package/dist/modules/bot_defaults.d.ts +6 -15
- package/dist/modules/bot_defaults.js +1 -5
- package/dist/modules/bot_settings.d.ts +44 -10
- package/dist/modules/bot_settings.js +11 -8
- package/dist/modules/bots_file_lock.d.ts +6 -6
- package/dist/modules/bots_file_lock.js +16 -12
- package/dist/modules/broadcast_failure.d.ts +2 -2
- package/dist/modules/broadcast_failure.js +5 -4
- package/dist/modules/chain_keys.d.ts +42 -40
- package/dist/modules/chain_keys.js +53 -45
- package/dist/modules/chain_orders.d.ts +93 -59
- package/dist/modules/chain_orders.js +31 -23
- package/dist/modules/constants.d.ts +530 -32
- package/dist/modules/constants.js +52 -60
- package/dist/modules/cr_planner.d.ts +40 -2
- package/dist/modules/credential_policy.d.ts +68 -8
- package/dist/modules/credential_policy.js +37 -31
- package/dist/modules/credential_session_cache.d.ts +2 -2
- package/dist/modules/credit_pricing.d.ts +42 -6
- package/dist/modules/credit_pricing.js +44 -30
- package/dist/modules/credit_runtime.d.ts +276 -118
- package/dist/modules/credit_runtime.js +462 -165
- package/dist/modules/crypto/browser_provider.js +6 -4
- package/dist/modules/crypto/node_provider.js +1 -1
- package/dist/modules/crypto/pure_scrypt.js +35 -4
- package/dist/modules/crypto/pure_secp256k1.js +72 -26
- package/dist/modules/crypto/sync.d.ts +9 -9
- package/dist/modules/crypto/sync.js +16 -9
- package/dist/modules/dexbot_class.d.ts +195 -139
- package/dist/modules/dexbot_class.js +78 -28
- package/dist/modules/dexbot_cow_runtime.d.ts +167 -87
- package/dist/modules/dexbot_cow_runtime.js +248 -206
- package/dist/modules/dexbot_credential_client.d.ts +19 -11
- package/dist/modules/dexbot_fill_runtime.d.ts +63 -48
- package/dist/modules/dexbot_fill_runtime.js +48 -41
- package/dist/modules/dexbot_maintenance_runtime.d.ts +109 -70
- package/dist/modules/dexbot_maintenance_runtime.js +117 -80
- package/dist/modules/dexbot_startup_runtime.d.ts +11 -10
- package/dist/modules/dexbot_startup_runtime.js +43 -43
- package/dist/modules/dexbot_state_recovery.d.ts +13 -12
- package/dist/modules/dexbot_state_recovery.js +18 -13
- package/dist/modules/fund_registry.d.ts +4 -2
- package/dist/modules/fund_registry.js +10 -10
- package/dist/modules/general_settings.d.ts +30 -4
- package/dist/modules/graceful_shutdown.d.ts +3 -3
- package/dist/modules/graceful_shutdown.js +2 -2
- package/dist/modules/grid_price_source.d.ts +1 -1
- package/dist/modules/key_store.d.ts +14 -8
- package/dist/modules/key_store.js +7 -6
- package/dist/modules/launcher/adapter_requirement.d.ts +11 -5
- package/dist/modules/launcher/adapter_requirement.js +5 -5
- package/dist/modules/launcher/bot_supervisor.d.ts +106 -24
- package/dist/modules/launcher/bot_supervisor.js +12 -11
- package/dist/modules/launcher/credential_bootstrap.d.ts +1 -1
- package/dist/modules/launcher/credential_bootstrap.js +1 -1
- package/dist/modules/launcher/credential_daemon.d.ts +4 -4
- package/dist/modules/launcher/credential_daemon.js +2 -2
- package/dist/modules/launcher/credential_secret.d.ts +1 -1
- package/dist/modules/launcher/foreign_cred_daemon.d.ts +2 -2
- package/dist/modules/launcher/market_adapter_runtime.d.ts +61 -6
- package/dist/modules/launcher/market_adapter_watchdog.d.ts +10 -2
- package/dist/modules/launcher/market_adapter_watchdog.js +4 -0
- package/dist/modules/launcher/monolithic_runtime.d.ts +18 -16
- package/dist/modules/launcher/status_reporting.d.ts +22 -14
- package/dist/modules/launcher/supervisor_control.d.ts +8 -1
- package/dist/modules/launcher/supervisor_control.js +4 -2
- package/dist/modules/market_adapter_whitelist.d.ts +9 -3
- package/dist/modules/market_adapter_whitelist.js +15 -3
- package/dist/modules/node_manager.d.ts +41 -11
- package/dist/modules/node_manager.js +5 -4
- package/dist/modules/order/accounting.d.ts +53 -24
- package/dist/modules/order/accounting.js +40 -14
- package/dist/modules/order/async_lock.d.ts +5 -2
- package/dist/modules/order/async_lock.js +1 -1
- package/dist/modules/order/export.d.ts +7 -6
- package/dist/modules/order/export.js +1 -7
- package/dist/modules/order/format.d.ts +39 -19
- package/dist/modules/order/format.js +62 -16
- package/dist/modules/order/genesis_policy.d.ts +21 -18
- package/dist/modules/order/genesis_policy.js +12 -8
- package/dist/modules/order/grid.d.ts +142 -36
- package/dist/modules/order/grid.js +148 -123
- package/dist/modules/order/grid_reconcile.d.ts +21 -20
- package/dist/modules/order/grid_reconcile.js +13 -12
- package/dist/modules/order/grid_reconcile_internal.d.ts +85 -72
- package/dist/modules/order/grid_reconcile_internal.js +28 -19
- package/dist/modules/order/index.d.ts +263 -1
- package/dist/modules/order/logger.d.ts +45 -11
- package/dist/modules/order/logger.js +38 -40
- package/dist/modules/order/logger_state.d.ts +4 -4
- package/dist/modules/order/manager.d.ts +226 -180
- package/dist/modules/order/manager.js +101 -83
- package/dist/modules/order/processed_fill_store.d.ts +18 -3
- package/dist/modules/order/processed_fill_store.js +16 -27
- package/dist/modules/order/strategy.d.ts +21 -13
- package/dist/modules/order/strategy.js +5 -6
- package/dist/modules/order/sync_engine.d.ts +91 -33
- package/dist/modules/order/sync_engine.js +99 -54
- package/dist/modules/order/utils/math.d.ts +157 -102
- package/dist/modules/order/utils/math.js +77 -38
- package/dist/modules/order/utils/order.d.ts +326 -106
- package/dist/modules/order/utils/order.js +200 -99
- package/dist/modules/order/utils/slot.d.ts +1 -1
- package/dist/modules/order/utils/system.d.ts +176 -26
- package/dist/modules/order/utils/system.js +86 -69
- package/dist/modules/order/utils/validate.d.ts +89 -41
- package/dist/modules/order/utils/validate.js +24 -22
- package/dist/modules/order/utils/withPoolRef.d.ts +4 -3
- package/dist/modules/order/utils/withPoolRef.js +18 -12
- package/dist/modules/order/working_grid.d.ts +14 -13
- package/dist/modules/paths.d.ts +3 -4
- package/dist/modules/paths.js +3 -27
- package/dist/modules/process_discovery.d.ts +1 -1
- package/dist/modules/process_discovery.js +2 -1
- package/dist/modules/runtime.d.ts +7 -3
- package/dist/modules/runtime.js +4 -3
- package/dist/modules/runtime_settings.d.ts +15 -10
- package/dist/modules/runtime_settings.js +30 -24
- package/dist/modules/settings_merge.d.ts +29 -3
- package/dist/modules/settings_merge.js +56 -78
- package/dist/modules/socket_json_client.d.ts +7 -4
- package/dist/modules/storage/browser_adapter.d.ts +38 -53
- package/dist/modules/storage/browser_adapter.js +7 -30
- package/dist/modules/storage/index.d.ts +1 -1
- package/dist/modules/storage/node_adapter.d.ts +45 -27
- package/dist/modules/storage/node_adapter.js +9 -9
- package/dist/modules/storage/types.d.ts +5 -4
- package/dist/modules/types.d.ts +1071 -2
- package/dist/modules/types.js +4 -1
- package/dist/modules/utils/asset_symbols.d.ts +2 -1
- package/dist/modules/utils/asset_symbols.js +2 -1
- package/dist/modules/utils/errors.d.ts +9 -0
- package/dist/modules/utils/errors.js +23 -1
- package/dist/modules/utils/time_range.d.ts +4 -0
- package/dist/modules/utils/time_range.js +18 -0
- package/dist/modules/validate_profiles.js +53 -43
- package/dist/modules/version_notice.d.ts +14 -3
- package/dist/modules/version_notice.js +6 -4
- package/dist/pm2.d.ts +29 -27
- package/dist/pm2.js +5 -5
- package/dist/scripts/analyze-credit.d.ts +2 -1
- package/dist/scripts/analyze-credit.js +23 -24
- package/dist/scripts/analyze-orders.d.ts +77 -9
- package/dist/scripts/analyze-orders.js +66 -84
- package/dist/scripts/chart_command.d.ts +27 -18
- package/dist/scripts/chart_command.js +16 -15
- package/dist/scripts/check_any.d.ts +18 -0
- package/dist/scripts/check_any.js +126 -0
- package/dist/scripts/diagnose-pool-history.js +12 -7
- package/dist/scripts/pnl.d.ts +3 -0
- package/dist/scripts/pnl.js +40 -0
- package/dist/scripts/print_grid.js +0 -1
- package/dist/scripts/run-tests.js +39 -7
- package/dist/scripts/runner.js +1 -1
- package/dist/scripts/test-credit-renewal.js +30 -21
- package/dist/scripts/update.d.ts +10 -5
- package/dist/scripts/update.js +168 -103
- package/dist/scripts/update_dist_freshness.js +1 -0
- package/dist/scripts/update_layout.d.ts +61 -0
- package/dist/scripts/update_layout.js +180 -0
- package/dist/scripts/validate_bots.js +2 -1
- package/dist/scripts/verify-browser-bundle.js +8 -0
- package/dist/unlock.d.ts +28 -3
- package/dist/unlock.js +72 -10
- package/docs/BITSHARES_ONBOARDING.md +2 -0
- package/docs/COPY_ON_WRITE_MASTER_PLAN.md +1 -1
- package/docs/COW_INVARIANTS.md +13 -6
- package/docs/DEXBOT_COMPARISON.md +8 -8
- package/docs/EVOLUTION.md +12 -10
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +5 -5
- package/docs/GRID_RECALCULATION.md +15 -16
- package/docs/GRID_RECONCILE.md +14 -3
- package/docs/LIFECYCLE.md +11 -11
- package/docs/MPA_CREDIT_USAGE.md +22 -3
- package/docs/README.md +15 -4
- package/docs/WORKFLOW.md +1 -0
- package/docs/architecture.md +12 -9
- package/docs/developer_guide.md +6 -6
- package/market_adapter/README.md +9 -26
- package/modules/README.md +4 -1
- package/package.json +4 -1
- package/scripts/README.md +14 -0
|
@@ -4,6 +4,7 @@ import path from 'node:path';
|
|
|
4
4
|
import { pathToFileURL } from 'node:url';
|
|
5
5
|
import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
|
|
6
6
|
import { computeHuberWindowSlopePct } from '../../market_adapter/core/strategies/ama_slope_model.js';
|
|
7
|
+
import { applyAsymmetricBounds } from '../../market_adapter/core/asymmetric_bounds.js';
|
|
7
8
|
import { range } from '../math_utils.js';
|
|
8
9
|
import { parseListOrRange, loadLpData, fmt } from './shared_utils.js';
|
|
9
10
|
import { getStorage } from '../../modules/storage/index.js';
|
|
@@ -218,19 +219,19 @@ function resolveAutoResultsPath(dataPath) {
|
|
|
218
219
|
}
|
|
219
220
|
function loadAmaStrategies(resultsPath) {
|
|
220
221
|
const json = readJSON(resultsPath);
|
|
221
|
-
const amas =
|
|
222
|
+
const amas = json.meta?.amas ?? {};
|
|
222
223
|
const labels = { AMA1: 'AMA1', AMA2: 'AMA2', AMA3: 'AMA3', AMA4: 'AMA4' };
|
|
223
224
|
const out = [];
|
|
224
225
|
for (const [key, val] of Object.entries(amas)) {
|
|
225
226
|
const a = val;
|
|
226
|
-
if (!a || !Number.isFinite(a.er) || !Number.isFinite(a.fast) || !Number.isFinite(a.slow))
|
|
227
|
+
if (!a || !Number.isFinite(Number(a.er)) || !Number.isFinite(Number(a.fast)) || !Number.isFinite(Number(a.slow)))
|
|
227
228
|
continue;
|
|
228
229
|
out.push({
|
|
229
230
|
id: key,
|
|
230
231
|
name: labels[key] ?? key,
|
|
231
|
-
er: a.er,
|
|
232
|
-
fast: a.fast,
|
|
233
|
-
slow: a.slow,
|
|
232
|
+
er: Number(a.er),
|
|
233
|
+
fast: Number(a.fast),
|
|
234
|
+
slow: Number(a.slow),
|
|
234
235
|
});
|
|
235
236
|
}
|
|
236
237
|
if (out.length !== 4) {
|
|
@@ -335,60 +336,6 @@ function buildProductionGrid(center, spreadPct, incrementPctFrac, maxMinRatio, a
|
|
|
335
336
|
sellStartIdx,
|
|
336
337
|
};
|
|
337
338
|
}
|
|
338
|
-
/**
|
|
339
|
-
* Slot-rotation simulation with FIXED chain prices, mirroring production
|
|
340
|
-
* anchor-&-refill (strategy.ts) on top of the createOrderGrid geometry:
|
|
341
|
-
*
|
|
342
|
-
* - Initial grid built once at the post-warmup AMA (createOrderGrid geometry
|
|
343
|
-
* via buildProductionGrid); order prices never follow AMA afterwards. When
|
|
344
|
-
* asymmetricBounds is enabled the placement center is shifted by the
|
|
345
|
-
* slope-ratio offset (#3) exactly like the live startPrice offset.
|
|
346
|
-
* - Rotation economics (#1/#2/#15): a FILLED BUY at rail node k instantly
|
|
347
|
-
* re-offers that base at the ADJACENT MASTER-RAIL NODE k+1; when that
|
|
348
|
-
* refill sells, the rotation books exactly one rail hop minus the
|
|
349
|
-
* round-trip fee, and the freed quote re-bids the node k-1 below. Slots
|
|
350
|
-
* cycle on small oscillations between resets — the earnings model of a
|
|
351
|
-
* refilled live slot, not a cross-gap differential.
|
|
352
|
-
* - Inventory-funded selling: an INITIAL (unlinked) sell can only execute
|
|
353
|
-
* against held inventory — it books its proceeds against the weighted
|
|
354
|
-
* average entry of the position (the live bot funds sells from real
|
|
355
|
-
* balances; unfundable sells stay open and retry, never shorting). Base
|
|
356
|
-
* bought in the SAME bar does not fund unlinked sales until the next bar
|
|
357
|
-
* (live balance updates propagate on the next maintenance tick).
|
|
358
|
-
* - Same-bar guard: newly armed/refill orders carry a one-bar cooldown, so
|
|
359
|
-
* a slot that just cycled cannot fill again inside the completion bar.
|
|
360
|
-
* - Grid reset fires on EITHER production trigger:
|
|
361
|
-
* (A) |AMA − recordedCenter| / recordedCenter ≥ repositionThresholdPct
|
|
362
|
-
* (ratchet: recordedCenter updates only when the trigger fires),
|
|
363
|
-
* (B) slope-delta reset, ONLY when asymmetricBounds (whitelist gate):
|
|
364
|
-
* |slopePct_now − slopeBaseline| ≥ slopeDeltaThresholdPct
|
|
365
|
-
* (= AMA_SLOPE_DELTA_THRESHOLD_PERCENT/100 ×
|
|
366
|
-
* DYNAMIC_WEIGHT_AMA_MAX_SLOPE_PCT), where slopePct is the
|
|
367
|
-
* DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS average-slope series and
|
|
368
|
-
* slopeBaseline mirrors botState.gridRangeScalingAmaSlope — seeded
|
|
369
|
-
* at start and re-seeded on every reset.
|
|
370
|
-
* On reset ALL unfilled orders are canceled (counted); bought-and-held
|
|
371
|
-
* base REMAINS as inventory (live resync never market-sells) and merges
|
|
372
|
-
* into the weighted-average-entry pool; a fresh grid is placed at the
|
|
373
|
-
* new center.
|
|
374
|
-
* - Scoring uses REALIZED rotations and op fees ONLY. The end-of-run
|
|
375
|
-
* inventory position (units × mark-vs-avg-entry) is reported as an
|
|
376
|
-
* informational field — it is real carried risk, but including unrealized
|
|
377
|
-
* bag marks in the ranking objective let trend-following combos dump
|
|
378
|
-
* phantom paper profit into the score.
|
|
379
|
-
* - BTS operation fees (#9): every order placement (initial grid + every
|
|
380
|
-
* armed refill/rebid) pays makerCreateFee × btsCreateFee, every reset
|
|
381
|
-
* cancel pays btsCancelFee; totals are converted to percentage points
|
|
382
|
-
* against the --bts-fee-capital reference and deducted from net capture.
|
|
383
|
-
*
|
|
384
|
-
* Differences from production (by design, documented):
|
|
385
|
-
* #6 bar-granularity triggers and reset-vs-fill ordering (OHLC sim);
|
|
386
|
-
* #7 all-or-nothing fills on raw hi/lo touch (no partial fills/dust/queue);
|
|
387
|
-
* #8 unit sizes / percentage-point accounting instead of capital-weighted
|
|
388
|
-
* dynamic sizing;
|
|
389
|
-
* #10 pool-price fills (no book depth/slippage);
|
|
390
|
-
* #11 no consolidation/dust-cancel/COW/collision mechanics.
|
|
391
|
-
*/
|
|
392
339
|
function simulateForParams(candles, amaValues, params) {
|
|
393
340
|
const { spreadPct, incrementPct, maxMinRatio, activeOrders, feeRoundtripPct, repositionThresholdPct, asymmetricBounds, risk, btsCreateFee, btsCancelFee, makerCreateFactor, txFeePrice, btsFeeCapital } = params;
|
|
394
341
|
// Warmup follows production AMA seeding/convergence (getAmaWarmupBars)
|
|
@@ -399,6 +346,22 @@ function simulateForParams(candles, amaValues, params) {
|
|
|
399
346
|
const slopeDeltaThresholdPct = (SLOPE_TRIGGER_FACTOR / 100) * SLOPE_MAX_PCT;
|
|
400
347
|
const makerCreateFeeBts = btsCreateFee * makerCreateFactor;
|
|
401
348
|
const stepUpFrac = 1 + incrementPct; // one-rail-step rotation distance
|
|
349
|
+
// Optional gate/band overrides. `slopePersistBars` follows the production
|
|
350
|
+
// default (constants) unless the caller pins a value, so the fill model's
|
|
351
|
+
// reset path matches live whenever asymmetricBounds enables trigger B.
|
|
352
|
+
// slopePersistBars persistence gate on trigger B
|
|
353
|
+
// bandTilt apply applyAsymmetricBounds to the built band
|
|
354
|
+
const slopeLookbackRaw = Number(params.slopeLookbackBars);
|
|
355
|
+
const slopeLookbackBars = Number.isFinite(slopeLookbackRaw) && slopeLookbackRaw >= 2
|
|
356
|
+
? Math.round(slopeLookbackRaw) : SLOPE_LOOKBACK_BARS;
|
|
357
|
+
const slopePersistRaw = Number(params.slopePersistBars);
|
|
358
|
+
const slopePersistBars = Number.isFinite(slopePersistRaw) && slopePersistRaw >= 1
|
|
359
|
+
? Math.round(slopePersistRaw)
|
|
360
|
+
: (MARKET_ADAPTER.AMA_SLOPE_PERSIST_ENABLED === true && Number(MARKET_ADAPTER.AMA_SLOPE_PERSIST_BARS) >= 1
|
|
361
|
+
? Math.round(Number(MARKET_ADAPTER.AMA_SLOPE_PERSIST_BARS)) : 1);
|
|
362
|
+
const bandTilt = params.bandTilt === true;
|
|
363
|
+
const maxAsymmetryFactor = Number.isFinite(params.maxAsymmetryFactor)
|
|
364
|
+
? Number(params.maxAsymmetryFactor) : MARKET_ADAPTER.ASYMMETRIC_BOUNDS_MAX_ASYMMETRY_FACTOR;
|
|
402
365
|
// First tradable bar: need a finite positive AMA to anchor the chain.
|
|
403
366
|
let startIdx = Math.min(skip, candles.length - 1);
|
|
404
367
|
let gridCenter = Number.NaN;
|
|
@@ -413,8 +376,8 @@ function simulateForParams(candles, amaValues, params) {
|
|
|
413
376
|
// Production AMA slope series (%/bar averaged over the lookback window).
|
|
414
377
|
// Evaluated over full history like the live adapter (only bar-index guards).
|
|
415
378
|
const slopeAt = new Array(candles.length).fill(null);
|
|
416
|
-
for (let j =
|
|
417
|
-
const s = computeHuberWindowSlopePct(amaValues, j,
|
|
379
|
+
for (let j = slopeLookbackBars; j < candles.length; j++) {
|
|
380
|
+
const s = computeHuberWindowSlopePct(amaValues, j, slopeLookbackBars);
|
|
418
381
|
if (s != null && Number.isFinite(s))
|
|
419
382
|
slopeAt[j] = s;
|
|
420
383
|
}
|
|
@@ -436,7 +399,26 @@ function simulateForParams(candles, amaValues, params) {
|
|
|
436
399
|
: 0;
|
|
437
400
|
if (offsetPct !== 0)
|
|
438
401
|
offsetAppliedCount++;
|
|
439
|
-
|
|
402
|
+
// applyAsymmetricBounds scales BOTH base bounds by one factor, so the
|
|
403
|
+
// tilted band is exactly a same-ratio band centred at center*scale
|
|
404
|
+
// (when the narrowing-side guard does not bind).
|
|
405
|
+
let scale = 1;
|
|
406
|
+
if (bandTilt && slopePct != null && Math.abs(slopePct) > SLOPE_NEUTRAL_ZONE_PCT) {
|
|
407
|
+
const trend = slopePct > 0 ? 'UP' : 'DOWN';
|
|
408
|
+
const tilt = applyAsymmetricBounds({
|
|
409
|
+
centerPrice: center,
|
|
410
|
+
minPrice: center / maxMinRatio,
|
|
411
|
+
maxPrice: center * maxMinRatio,
|
|
412
|
+
trend,
|
|
413
|
+
slopeOffset: Math.abs(slopePct),
|
|
414
|
+
maxSlopeOffset: SLOPE_MAX_PCT,
|
|
415
|
+
maxAsymmetryFactor,
|
|
416
|
+
});
|
|
417
|
+
const baseMax = center * maxMinRatio;
|
|
418
|
+
if (Number.isFinite(tilt.resolvedMaxPrice) && baseMax > 0)
|
|
419
|
+
scale = tilt.resolvedMaxPrice / baseMax;
|
|
420
|
+
}
|
|
421
|
+
const effCenter = center * scale * (1 + offsetPct / 100);
|
|
440
422
|
const built = buildProductionGrid(effCenter, spreadPct, incrementPct, maxMinRatio, activeOrders);
|
|
441
423
|
activeRail = built.rail;
|
|
442
424
|
orders.clear();
|
|
@@ -481,6 +463,9 @@ function simulateForParams(candles, amaValues, params) {
|
|
|
481
463
|
break;
|
|
482
464
|
}
|
|
483
465
|
}
|
|
466
|
+
// Persistence-gate state for trigger B.
|
|
467
|
+
let slopePersistCount = 0;
|
|
468
|
+
let slopePersistDir = 0;
|
|
484
469
|
for (let i = startIdx + 1; i < candles.length; i++) {
|
|
485
470
|
const ama = amaValues[i];
|
|
486
471
|
const hi = candles[i].high;
|
|
@@ -496,13 +481,34 @@ function simulateForParams(candles, amaValues, params) {
|
|
|
496
481
|
}
|
|
497
482
|
}
|
|
498
483
|
if (!shouldReset && asymmetricBounds && slopeBaseline != null && slopeAt[i] != null) {
|
|
499
|
-
const
|
|
500
|
-
if (
|
|
501
|
-
|
|
502
|
-
|
|
484
|
+
const crossed = Math.abs(slopeAt[i] - slopeBaseline) >= slopeDeltaThresholdPct;
|
|
485
|
+
if (slopePersistBars <= 1) {
|
|
486
|
+
if (crossed) {
|
|
487
|
+
shouldReset = true;
|
|
488
|
+
slopeTriggerCount++;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
else if (!crossed) {
|
|
492
|
+
slopePersistCount = 0;
|
|
493
|
+
slopePersistDir = 0;
|
|
494
|
+
}
|
|
495
|
+
else {
|
|
496
|
+
const dir = Math.sign(slopeAt[i] - slopeBaseline);
|
|
497
|
+
if (dir !== 0 && dir === slopePersistDir)
|
|
498
|
+
slopePersistCount++;
|
|
499
|
+
else {
|
|
500
|
+
slopePersistDir = dir;
|
|
501
|
+
slopePersistCount = 1;
|
|
502
|
+
}
|
|
503
|
+
if (slopePersistCount >= slopePersistBars) {
|
|
504
|
+
shouldReset = true;
|
|
505
|
+
slopeTriggerCount++;
|
|
506
|
+
}
|
|
503
507
|
}
|
|
504
508
|
}
|
|
505
509
|
if (shouldReset && Number.isFinite(ama) && ama > 0) {
|
|
510
|
+
slopePersistCount = 0;
|
|
511
|
+
slopePersistDir = 0;
|
|
506
512
|
canceledOnReposition += orders.size;
|
|
507
513
|
btsFeesBts += orders.size * btsCancelFee;
|
|
508
514
|
orders.clear(); // inventory survives — resync never market-sells
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
declare function parseArgs(): {
|
|
2
|
+
dataPath: string;
|
|
3
|
+
amaName: string;
|
|
4
|
+
lookbacks: number[];
|
|
5
|
+
spreads: number[];
|
|
6
|
+
increments: number[];
|
|
7
|
+
ratios: number[];
|
|
8
|
+
maxOrders: number;
|
|
9
|
+
feeRoundtripPct: number;
|
|
10
|
+
capital: number;
|
|
11
|
+
repositionPct: number;
|
|
12
|
+
asymmetricBounds: boolean;
|
|
13
|
+
btsCreateFee: number;
|
|
14
|
+
btsCancelFee: number;
|
|
15
|
+
makerCreateFactor: number;
|
|
16
|
+
txFeePrice: number;
|
|
17
|
+
outPath: string | null;
|
|
18
|
+
};
|
|
19
|
+
declare function run(): void;
|
|
20
|
+
export { run, parseArgs };
|
|
21
|
+
//# sourceMappingURL=backtest_lookback_drawdown.d.ts.map
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* LOOKBACK → FILL-MODEL DRAWDOWN BACKTEST
|
|
4
|
+
*
|
|
5
|
+
* Runs the persistent-grid simulation (`simulatePersistentGrid`, shared with
|
|
6
|
+
* `backtest_ama_sweep`) across a set of Huber slope lookbacks over ONE geometry
|
|
7
|
+
* grid, so the lookback's effect on realized drawdown / net capture / reset
|
|
8
|
+
* churn is compared with geometry held fixed. Every
|
|
9
|
+
* (spread, increment, ratio, weight) combo is run once per lookback and matched
|
|
10
|
+
* by key, so the comparison is PAIRED — the delta isolates the window, not the
|
|
11
|
+
* strategy shape.
|
|
12
|
+
*
|
|
13
|
+
* Why this exists (see docs/AMA_SLOPE_WINDOW.md): the signal-side window metrics
|
|
14
|
+
* (wobble / lag / wrong-way) are second-order, so the open question is whether
|
|
15
|
+
* the window moves the fill-model economics. It does, but the SIGN IS
|
|
16
|
+
* POOL-DEPENDENT — on a long-lived liquid pair a 16h window beat 12h on both
|
|
17
|
+
* drawdown and net capture across 100% of geometries, while on a shorter pair
|
|
18
|
+
* the ordering reversed. Treat the paired delta, never the absolute level (the
|
|
19
|
+
* realized-equity drawdown here is model-shaped and can exceed capital), and
|
|
20
|
+
* re-run per pool before drawing a conclusion.
|
|
21
|
+
*
|
|
22
|
+
* Trigger B (slope-delta reset) and the slope-ratio grid offset only act under
|
|
23
|
+
* the production asymmetricBounds whitelist, so the lookback has no effect
|
|
24
|
+
* unless `--asymmetric-bounds` is on — it defaults ON here, since a lookback
|
|
25
|
+
* comparison is the whole point. Pass `--no-asymmetric-bounds` for the
|
|
26
|
+
* non-whitelisted path (where the result collapses to lookback-independent).
|
|
27
|
+
*
|
|
28
|
+
* Usage:
|
|
29
|
+
* node dist/analysis/bot_fitting/backtest_lookback_drawdown.js \
|
|
30
|
+
* --data market_adapter/data/lp/<market-pair> --lookbacks 12,14,16,20
|
|
31
|
+
*/
|
|
32
|
+
import fs from 'node:fs';
|
|
33
|
+
import path from 'node:path';
|
|
34
|
+
import { pathToFileURL } from 'node:url';
|
|
35
|
+
import { calculateAMA, getAmaWarmupBars } from '../../market_adapter/core/strategies/ama.js';
|
|
36
|
+
import { loadCandles } from '../trend_detection/backtest_ama_slope_huber.js';
|
|
37
|
+
import { parseListOrRange } from './shared_utils.js';
|
|
38
|
+
import { simulatePersistentGrid, WEIGHT_PROFILES } from './backtest_ama_sweep.js';
|
|
39
|
+
import { getStorage } from '../../modules/storage/index.js';
|
|
40
|
+
import { PATHS } from '../../modules/paths.js';
|
|
41
|
+
import { MARKET_ADAPTER } from '../../modules/constants.js';
|
|
42
|
+
const { writeJSON } = getStorage();
|
|
43
|
+
const MA = MARKET_ADAPTER;
|
|
44
|
+
// A modest geometry grid — enough spread/increment/ratio variety to keep the
|
|
45
|
+
// paired comparison honest without the full sweep's cost. Override per run.
|
|
46
|
+
const DEFAULT_SPREADS = [1, 2, 3, 4];
|
|
47
|
+
const DEFAULT_INCREMENTS = [0.5, 1, 2];
|
|
48
|
+
const DEFAULT_RATIOS = [1.2, 2, 5];
|
|
49
|
+
const DEFAULT_LOOKBACKS = [12, 14, 16, 20];
|
|
50
|
+
// The shipped default window — the reference for the paired delta table.
|
|
51
|
+
const REFERENCE_LOOKBACK = MA.DYNAMIC_WEIGHT_AMA_LOOKBACK_BARS;
|
|
52
|
+
function parseArgs() {
|
|
53
|
+
const args = process.argv.slice(2);
|
|
54
|
+
const out = {
|
|
55
|
+
dataPath: '',
|
|
56
|
+
amaName: MA.DEFAULT_AMA_KEY,
|
|
57
|
+
lookbacks: [...DEFAULT_LOOKBACKS],
|
|
58
|
+
spreads: [...DEFAULT_SPREADS],
|
|
59
|
+
increments: [...DEFAULT_INCREMENTS],
|
|
60
|
+
ratios: [...DEFAULT_RATIOS],
|
|
61
|
+
maxOrders: 20,
|
|
62
|
+
feeRoundtripPct: 0.20,
|
|
63
|
+
capital: 10000,
|
|
64
|
+
repositionPct: MA.AMA_DELTA_THRESHOLD_PERCENT,
|
|
65
|
+
asymmetricBounds: true,
|
|
66
|
+
btsCreateFee: 0.4826,
|
|
67
|
+
btsCancelFee: 0.00482,
|
|
68
|
+
makerCreateFactor: 0.10,
|
|
69
|
+
txFeePrice: 1.0,
|
|
70
|
+
outPath: null,
|
|
71
|
+
};
|
|
72
|
+
for (let i = 0; i < args.length; i++) {
|
|
73
|
+
const arg = args[i];
|
|
74
|
+
if (arg === '--help' || arg === '-h') {
|
|
75
|
+
printHelp();
|
|
76
|
+
process.exit(0);
|
|
77
|
+
}
|
|
78
|
+
if (arg === '--asymmetric-bounds') {
|
|
79
|
+
out.asymmetricBounds = true;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (arg === '--no-asymmetric-bounds') {
|
|
83
|
+
out.asymmetricBounds = false;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const val = args[i + 1];
|
|
87
|
+
if (!val)
|
|
88
|
+
continue;
|
|
89
|
+
switch (arg) {
|
|
90
|
+
case '--data':
|
|
91
|
+
out.dataPath = val;
|
|
92
|
+
i++;
|
|
93
|
+
break;
|
|
94
|
+
case '--ama':
|
|
95
|
+
out.amaName = val;
|
|
96
|
+
i++;
|
|
97
|
+
break;
|
|
98
|
+
case '--lookbacks':
|
|
99
|
+
out.lookbacks = parseListOrRange(val, out.lookbacks).map((v) => Math.round(v));
|
|
100
|
+
i++;
|
|
101
|
+
break;
|
|
102
|
+
case '--spread':
|
|
103
|
+
out.spreads = parseListOrRange(val, out.spreads);
|
|
104
|
+
i++;
|
|
105
|
+
break;
|
|
106
|
+
case '--increment':
|
|
107
|
+
out.increments = parseListOrRange(val, out.increments);
|
|
108
|
+
i++;
|
|
109
|
+
break;
|
|
110
|
+
case '--ratio':
|
|
111
|
+
out.ratios = parseListOrRange(val, out.ratios);
|
|
112
|
+
i++;
|
|
113
|
+
break;
|
|
114
|
+
case '--max-orders':
|
|
115
|
+
out.maxOrders = Number(val);
|
|
116
|
+
i++;
|
|
117
|
+
break;
|
|
118
|
+
case '--fee':
|
|
119
|
+
out.feeRoundtripPct = Number(val);
|
|
120
|
+
i++;
|
|
121
|
+
break;
|
|
122
|
+
case '--capital':
|
|
123
|
+
out.capital = Number(val);
|
|
124
|
+
i++;
|
|
125
|
+
break;
|
|
126
|
+
case '--reposition':
|
|
127
|
+
out.repositionPct = Number(val);
|
|
128
|
+
i++;
|
|
129
|
+
break;
|
|
130
|
+
case '--bts-create-fee':
|
|
131
|
+
out.btsCreateFee = Number(val);
|
|
132
|
+
i++;
|
|
133
|
+
break;
|
|
134
|
+
case '--bts-cancel-fee':
|
|
135
|
+
out.btsCancelFee = Number(val);
|
|
136
|
+
i++;
|
|
137
|
+
break;
|
|
138
|
+
case '--maker-create-factor':
|
|
139
|
+
out.makerCreateFactor = Number(val);
|
|
140
|
+
i++;
|
|
141
|
+
break;
|
|
142
|
+
case '--tx-fee-price':
|
|
143
|
+
out.txFeePrice = Number(val);
|
|
144
|
+
i++;
|
|
145
|
+
break;
|
|
146
|
+
case '--out':
|
|
147
|
+
out.outPath = path.resolve(val);
|
|
148
|
+
i++;
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (!out.dataPath)
|
|
153
|
+
throw new Error('--data <path-to-lp-candles.json|dir> is required');
|
|
154
|
+
out.lookbacks = [...new Set(out.lookbacks)].filter((v) => Number.isFinite(v) && v >= 2).sort((a, b) => a - b);
|
|
155
|
+
if (out.lookbacks.length === 0)
|
|
156
|
+
throw new Error('--lookbacks must resolve to a non-empty list of bars >= 2');
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
function printHelp() {
|
|
160
|
+
console.log('Lookback -> fill-model drawdown backtest (paired persistent-grid simulation)');
|
|
161
|
+
console.log('');
|
|
162
|
+
console.log('Usage: node dist/analysis/bot_fitting/backtest_lookback_drawdown.js [options]');
|
|
163
|
+
console.log('');
|
|
164
|
+
console.log('Options:');
|
|
165
|
+
console.log(' --data <path> LP candle file or shard directory (required)');
|
|
166
|
+
console.log(` --ama <AMA1..AMA4> Built-in AMA preset (default: ${MA.DEFAULT_AMA_KEY})`);
|
|
167
|
+
console.log(` --lookbacks <spec> Lookbacks to compare: 12,14,16,20 (default: ${DEFAULT_LOOKBACKS.join(',')})`);
|
|
168
|
+
console.log(` --spread <spec> Spread grid (default: ${DEFAULT_SPREADS.join(',')})`);
|
|
169
|
+
console.log(` --increment <spec> Increment grid (default: ${DEFAULT_INCREMENTS.join(',')})`);
|
|
170
|
+
console.log(` --ratio <spec> Max/min ratio grid (default: ${DEFAULT_RATIOS.join(',')})`);
|
|
171
|
+
console.log(' --max-orders <n> Size cap per side (default: 20)');
|
|
172
|
+
console.log(' --fee <pct> Round-trip fee % (default: 0.20)');
|
|
173
|
+
console.log(' --capital <n> Notional capital per side (default: 10000)');
|
|
174
|
+
console.log(` --reposition <pct> AMA drift % to re-center (default: ${MA.AMA_DELTA_THRESHOLD_PERCENT})`);
|
|
175
|
+
console.log(' --no-asymmetric-bounds Disable trigger B + slope offset (default: enabled)');
|
|
176
|
+
console.log(' --out <path> JSON output path');
|
|
177
|
+
}
|
|
178
|
+
function resolveAma(name) {
|
|
179
|
+
const presets = MA.AMAS;
|
|
180
|
+
const preset = presets[name];
|
|
181
|
+
if (!preset)
|
|
182
|
+
throw new Error(`Unknown AMA preset '${name}' (expected ${Object.keys(presets).join(', ')})`);
|
|
183
|
+
return { name, er: preset.erPeriod, fast: preset.fastPeriod, slow: preset.slowPeriod };
|
|
184
|
+
}
|
|
185
|
+
function median(values) {
|
|
186
|
+
const s = values.slice().sort((a, b) => a - b);
|
|
187
|
+
const mid = s.length >> 1;
|
|
188
|
+
return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
|
|
189
|
+
}
|
|
190
|
+
function percentile(values, pct) {
|
|
191
|
+
const s = values.slice().sort((a, b) => a - b);
|
|
192
|
+
return s[Math.min(s.length - 1, Math.max(0, Math.floor((pct / 100) * (s.length - 1))))];
|
|
193
|
+
}
|
|
194
|
+
function fmt(x, d = 2) {
|
|
195
|
+
return Number.isFinite(Number(x)) ? Number(x).toFixed(d) : 'n/a';
|
|
196
|
+
}
|
|
197
|
+
function run() {
|
|
198
|
+
const cfg = parseArgs();
|
|
199
|
+
const amaDef = resolveAma(cfg.amaName);
|
|
200
|
+
const { candles, files } = loadCandles(cfg.dataPath);
|
|
201
|
+
const closes = candles.map((c) => c.close);
|
|
202
|
+
const amaValues = calculateAMA(closes, { erPeriod: amaDef.er, fastPeriod: amaDef.fast, slowPeriod: amaDef.slow });
|
|
203
|
+
const warmupBars = getAmaWarmupBars(amaDef.er, amaDef.slow, 0, amaDef.fast);
|
|
204
|
+
const weightEntries = Object.entries(WEIGHT_PROFILES);
|
|
205
|
+
const combos = [];
|
|
206
|
+
for (const spreadPct of cfg.spreads)
|
|
207
|
+
for (const incrementPct of cfg.increments)
|
|
208
|
+
for (const maxMinRatio of cfg.ratios)
|
|
209
|
+
for (const [weightName, weightFactor] of weightEntries)
|
|
210
|
+
combos.push({ spreadPct, incrementPct, maxMinRatio, weightName, weightFactor });
|
|
211
|
+
console.log('================================================================================');
|
|
212
|
+
console.log(' LOOKBACK -> FILL-MODEL DRAWDOWN (paired persistent-grid simulation)');
|
|
213
|
+
console.log('================================================================================');
|
|
214
|
+
console.log(` Data: ${path.resolve(cfg.dataPath)} (${files} file(s), ${candles.length} candles)`);
|
|
215
|
+
console.log(` AMA: ${amaDef.name} (er=${amaDef.er}, fast=${amaDef.fast}, slow=${amaDef.slow}), warmup ${warmupBars} bars`);
|
|
216
|
+
console.log(` Lookbacks: ${cfg.lookbacks.join(', ')} bars | geometries: ${combos.length}`);
|
|
217
|
+
console.log(` Bounds: asymmetricBounds ${cfg.asymmetricBounds ? 'ON (trigger B + slope offset active)' : 'OFF (lookback-independent)'}`);
|
|
218
|
+
console.log(` Reference: ${REFERENCE_LOOKBACK}h (shipped default) for the paired delta\n`);
|
|
219
|
+
const byLookback = {};
|
|
220
|
+
for (const lb of cfg.lookbacks) {
|
|
221
|
+
const perGeom = {};
|
|
222
|
+
for (const c of combos) {
|
|
223
|
+
const sim = simulatePersistentGrid(candles, amaValues, {
|
|
224
|
+
spreadPct: c.spreadPct,
|
|
225
|
+
incrementPct: c.incrementPct / 100,
|
|
226
|
+
maxMinRatio: c.maxMinRatio,
|
|
227
|
+
maxOrders: cfg.maxOrders,
|
|
228
|
+
feeRoundtripPct: cfg.feeRoundtripPct,
|
|
229
|
+
capital: cfg.capital,
|
|
230
|
+
repositionThreshold: cfg.repositionPct / 100,
|
|
231
|
+
asymmetricBounds: cfg.asymmetricBounds,
|
|
232
|
+
btsCreateFee: cfg.btsCreateFee,
|
|
233
|
+
btsCancelFee: cfg.btsCancelFee,
|
|
234
|
+
makerCreateFactor: cfg.makerCreateFactor,
|
|
235
|
+
txFeePrice: cfg.txFeePrice,
|
|
236
|
+
warmupBars,
|
|
237
|
+
lookbackBars: lb,
|
|
238
|
+
}, c.weightName, c.weightFactor);
|
|
239
|
+
perGeom[`${c.spreadPct}|${c.incrementPct}|${c.maxMinRatio}|${c.weightName}`] = sim;
|
|
240
|
+
}
|
|
241
|
+
byLookback[lb] = perGeom;
|
|
242
|
+
process.stdout.write(` lb=${String(lb).padStart(2)} done (${combos.length} geometries)\n`);
|
|
243
|
+
}
|
|
244
|
+
// Paired keys: geometries with fills under EVERY lookback.
|
|
245
|
+
const ref = byLookback[REFERENCE_LOOKBACK] ?? byLookback[cfg.lookbacks[0]];
|
|
246
|
+
const keys = Object.keys(ref).filter((k) => cfg.lookbacks.every((lb) => byLookback[lb][k]?.matchedPairs > 0));
|
|
247
|
+
console.log('\n================================================================================');
|
|
248
|
+
console.log(' PER-LOOKBACK MEDIANS (over paired geometries)');
|
|
249
|
+
console.log('================================================================================');
|
|
250
|
+
const fields = [
|
|
251
|
+
['maxDrawdown %', 'maxDrawdownPct', 1, 2],
|
|
252
|
+
['netProfit / capital %', 'netProfitPerCapital', 100, 2],
|
|
253
|
+
['pairs / day', 'pairsPerDay', 1, 2],
|
|
254
|
+
['repositions', 'repositionCount', 1, 0],
|
|
255
|
+
['slope-trigger resets', 'slopeTriggerCount', 1, 0],
|
|
256
|
+
['maxInventoryExposure', 'maxInventoryExposure', 1, 0],
|
|
257
|
+
];
|
|
258
|
+
console.log(' lb |' + cfg.lookbacks.map((lb) => String(lb).padStart(12)).join(''));
|
|
259
|
+
console.log(' ---+' + cfg.lookbacks.map(() => '------------').join(''));
|
|
260
|
+
for (const [label, field, mul, d] of fields) {
|
|
261
|
+
let row = ` ${label.padEnd(20).slice(0, 20)} |`;
|
|
262
|
+
for (const lb of cfg.lookbacks) {
|
|
263
|
+
row += fmt(median(keys.map((k) => byLookback[lb][k][field] * mul)), d).padStart(12);
|
|
264
|
+
}
|
|
265
|
+
console.log(row);
|
|
266
|
+
}
|
|
267
|
+
console.log('\n================================================================================');
|
|
268
|
+
console.log(` PAIRED DELTA vs ${REFERENCE_LOOKBACK}h (max drawdown) — negative = lower DD than reference`);
|
|
269
|
+
console.log('================================================================================');
|
|
270
|
+
console.log(' lb | median delta | p25 .. p75 | lower-DD geometries');
|
|
271
|
+
for (const lb of cfg.lookbacks) {
|
|
272
|
+
const deltas = keys.map((k) => byLookback[lb][k].maxDrawdownPct - ref[k].maxDrawdownPct);
|
|
273
|
+
const lower = deltas.filter((d) => d < 0).length;
|
|
274
|
+
console.log(` ${String(lb).padStart(2)} | ` +
|
|
275
|
+
`${fmt(median(deltas)).padStart(12)} | ` +
|
|
276
|
+
`${fmt(percentile(deltas, 25))} .. ${fmt(percentile(deltas, 75))} | ` +
|
|
277
|
+
`${lower}/${deltas.length} (${fmt((100 * lower) / deltas.length, 0)}%)`);
|
|
278
|
+
}
|
|
279
|
+
console.log('\n Reminder: the sign is pool-dependent and the absolute level is model-shaped');
|
|
280
|
+
console.log(' (realized-equity DD, bags excluded) — compare within a pool, not across.');
|
|
281
|
+
const base = path.basename(path.resolve(cfg.dataPath)).replace(/\.json$/i, '');
|
|
282
|
+
const outPath = cfg.outPath ?? path.join(PATHS.ANALYSIS.RESULTS_DIR, `lookback_drawdown_${base}.json`);
|
|
283
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
284
|
+
writeJSON(outPath, {
|
|
285
|
+
meta: {
|
|
286
|
+
generatedAt: new Date().toISOString(),
|
|
287
|
+
dataPath: path.relative(process.cwd(), path.resolve(cfg.dataPath)),
|
|
288
|
+
files,
|
|
289
|
+
candles: candles.length,
|
|
290
|
+
ama: amaDef,
|
|
291
|
+
warmupBars,
|
|
292
|
+
lookbacks: cfg.lookbacks,
|
|
293
|
+
referenceLookback: REFERENCE_LOOKBACK,
|
|
294
|
+
geometries: combos.length,
|
|
295
|
+
asymmetricBounds: cfg.asymmetricBounds,
|
|
296
|
+
feeRoundtripPct: cfg.feeRoundtripPct,
|
|
297
|
+
capital: cfg.capital,
|
|
298
|
+
repositionPct: cfg.repositionPct,
|
|
299
|
+
note: 'Paired persistent-grid comparison: each geometry is simulated once per lookback so the delta isolates the window. Drawdown is realized-equity peak-to-trough (carried bags excluded); the sign of the lookback delta is pool-dependent.',
|
|
300
|
+
},
|
|
301
|
+
results: byLookback,
|
|
302
|
+
});
|
|
303
|
+
console.log(`\nSaved: ${path.relative(process.cwd(), outPath)}`);
|
|
304
|
+
}
|
|
305
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
306
|
+
try {
|
|
307
|
+
run();
|
|
308
|
+
}
|
|
309
|
+
catch (err) {
|
|
310
|
+
console.error(err);
|
|
311
|
+
process.exit(1);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
export { run, parseArgs };
|
|
315
|
+
//# sourceMappingURL=backtest_lookback_drawdown.js.map
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
declare function parseListOrRange(spec:
|
|
1
|
+
declare function parseListOrRange(spec: string | null | undefined, fallback: number[]): number[];
|
|
2
2
|
declare function loadLpData(filePath: string): {
|
|
3
3
|
candles: {
|
|
4
4
|
timestamp: number;
|
|
5
|
-
open:
|
|
6
|
-
high:
|
|
7
|
-
low:
|
|
8
|
-
close:
|
|
9
|
-
volume:
|
|
5
|
+
open: number;
|
|
6
|
+
high: number;
|
|
7
|
+
low: number;
|
|
8
|
+
close: number;
|
|
9
|
+
volume: number;
|
|
10
10
|
}[];
|
|
11
|
-
meta:
|
|
11
|
+
meta: {} | null;
|
|
12
12
|
};
|
|
13
13
|
declare function fmt(x: number, d?: number): string;
|
|
14
14
|
export { parseListOrRange, loadLpData, fmt };
|
|
@@ -10,7 +10,7 @@ function toCandles(arr) {
|
|
|
10
10
|
// instead of hand-rolled array indexing.
|
|
11
11
|
return arr
|
|
12
12
|
.map((c) => normalizeCandle(c))
|
|
13
|
-
.filter(
|
|
13
|
+
.filter((c) => c != null)
|
|
14
14
|
.map((c) => ({
|
|
15
15
|
timestamp: c.time * 1000,
|
|
16
16
|
open: c.open,
|
|
@@ -37,7 +37,7 @@ function parseListOrRange(spec, fallback) {
|
|
|
37
37
|
}
|
|
38
38
|
function loadLpData(filePath) {
|
|
39
39
|
const json = readJSON(filePath);
|
|
40
|
-
return { candles: toCandles(json.candles ?? json), meta: json.meta ?? null };
|
|
40
|
+
return { candles: toCandles((json.candles ?? json)), meta: json.meta ?? null };
|
|
41
41
|
}
|
|
42
42
|
function fmt(x, d = 2) {
|
|
43
43
|
if (!Number.isFinite(x))
|
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
import { sanitizeKey } from '../modules/utils/sanitize_key.js';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
type BotEntry = Record<string, unknown>;
|
|
3
|
+
interface AmaConfig {
|
|
4
|
+
erPeriod: number;
|
|
5
|
+
fastPeriod: number;
|
|
6
|
+
slowPeriod: number;
|
|
7
|
+
}
|
|
8
|
+
declare function loadBotSettings(filePath?: string): {
|
|
9
|
+
bots?: BotEntry[];
|
|
10
|
+
} | null;
|
|
11
|
+
declare function computeBotKey(bot: unknown, index: number): string;
|
|
12
|
+
declare function resolveBotKey(botName: unknown, filePath?: string): string | null;
|
|
5
13
|
declare function candleFileForBot(botKey: string, intervalLabel: string, dataDir?: string): string;
|
|
6
14
|
declare function resolveCandleFile(botKey: string, intervalLabel: string, dataDir?: string, botsFile?: string): string | null;
|
|
7
|
-
declare function loadBotMeta(botKey:
|
|
15
|
+
declare function loadBotMeta(botKey: unknown, filePath?: string): BotEntry | null;
|
|
8
16
|
/**
|
|
9
17
|
* Persist a resolved account name → ID mapping onto the bot entry in
|
|
10
18
|
* profiles/bots.json (`accountId` next to `preferredAccount`), so analysis
|
|
@@ -14,25 +22,25 @@ declare function loadBotMeta(botKey: any, filePath?: string): any;
|
|
|
14
22
|
* same atomic writeJSON serialization the bot editor uses. Returns true when
|
|
15
23
|
* the file was updated.
|
|
16
24
|
*/
|
|
17
|
-
declare function persistBotAccountId(botKey:
|
|
25
|
+
declare function persistBotAccountId(botKey: unknown, accountId: string, filePath?: string): boolean;
|
|
18
26
|
/**
|
|
19
27
|
* Return the stored chain account ID for a bot key, or null when none is
|
|
20
28
|
* stamped yet. When expectedRef is given, the stored ID is only returned if
|
|
21
29
|
* the entry's current preferredAccount still matches it — a rename must
|
|
22
30
|
* never silently reuse a stale ID.
|
|
23
31
|
*/
|
|
24
|
-
declare function getStoredBotAccountId(botKey:
|
|
32
|
+
declare function getStoredBotAccountId(botKey: unknown, expectedRef?: string | null, filePath?: string): string | null;
|
|
25
33
|
/**
|
|
26
34
|
* Find the bot entry whose preferredAccount matches a raw account reference
|
|
27
35
|
* (case-insensitive). Used by tools that accept a bare account name to locate
|
|
28
36
|
* the stored accountId and the persist target. Returns null for 1.2.x input
|
|
29
37
|
* or when no bot claims the name.
|
|
30
38
|
*/
|
|
31
|
-
declare function findBotKeyByAccountRef(ref:
|
|
39
|
+
declare function findBotKeyByAccountRef(ref: unknown, filePath?: string): {
|
|
32
40
|
botKey: string;
|
|
33
|
-
meta:
|
|
41
|
+
meta: BotEntry;
|
|
34
42
|
} | null;
|
|
35
|
-
declare function resolveAmaConfig(botKey:
|
|
36
|
-
declare function resolveAmaKey(botKey:
|
|
43
|
+
declare function resolveAmaConfig(botKey: unknown): AmaConfig;
|
|
44
|
+
declare function resolveAmaKey(botKey: unknown): string;
|
|
37
45
|
export { loadBotSettings, sanitizeKey, computeBotKey, resolveBotKey, candleFileForBot, resolveCandleFile, loadBotMeta, getStoredBotAccountId, findBotKeyByAccountRef, persistBotAccountId, resolveAmaConfig, resolveAmaKey };
|
|
38
46
|
//# sourceMappingURL=bot_key_utils.d.ts.map
|