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
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
'use strict';
|
|
3
3
|
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
4
5
|
import { pathToFileURL } from 'node:url';
|
|
5
6
|
import { resolveAccountRef } from './account_resolver.js';
|
|
6
|
-
import { BTS_ID, assetPrec as getPrec, assetSymbol,
|
|
7
|
+
import { BTS_ID, assetPrec as getPrec, assetSymbol, resolveAssetPrecisions, toReal, } from './fills_source.js';
|
|
8
|
+
import { writePnlReport } from './pnl_report.js';
|
|
9
|
+
import { fetchFillsCached } from './fills_cache.js';
|
|
10
|
+
import { toFileUrl } from './chart_utils.js';
|
|
11
|
+
import { PATHS } from '../modules/paths.js';
|
|
12
|
+
import { sanitizeKey } from '../modules/utils/sanitize_key.js';
|
|
13
|
+
import { monthsToHours } from '../modules/utils/time_range.js';
|
|
14
|
+
import { muteChainLogs } from '../modules/utils/chain_logs.js';
|
|
15
|
+
import { formatFundsValue } from '../modules/order/format.js';
|
|
7
16
|
/**
|
|
8
17
|
* TRADE PROFITABILITY ANALYZER
|
|
9
18
|
*
|
|
@@ -13,12 +22,12 @@ import { BTS_ID, assetPrec as getPrec, assetSymbol, fetchAllFills, resolveAssetP
|
|
|
13
22
|
*
|
|
14
23
|
* Usage:
|
|
15
24
|
* node dist/analysis/trade_profitability.js 1.2.3 --start 2025-01-01 --end 2025-06-01
|
|
16
|
-
* node dist/analysis/trade_profitability.js 1.2.3 --
|
|
25
|
+
* node dist/analysis/trade_profitability.js 1.2.3 --month 3
|
|
17
26
|
* node dist/analysis/trade_profitability.js 1.2.3 --start 2025-01-01T00:00:00Z --end 2025-06-01T00:00:00Z
|
|
18
27
|
* node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --asset 1.3.113
|
|
19
28
|
* node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --csv trades.csv
|
|
20
29
|
* node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --json results.json
|
|
21
|
-
* node dist/analysis/trade_profitability.js "account-name" --
|
|
30
|
+
* node dist/analysis/trade_profitability.js "account-name" --month 3
|
|
22
31
|
* node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --trades
|
|
23
32
|
* node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --match-mode fifo
|
|
24
33
|
*/
|
|
@@ -27,47 +36,53 @@ let BLOCKCHAIN_FEE_PER_FILL = 0.09652; // BTS — flat blockchain operation fee
|
|
|
27
36
|
// ─── CLI ──────────────────────────────────────────────────────────────────────
|
|
28
37
|
function printHelp() {
|
|
29
38
|
console.log(`\
|
|
30
|
-
Usage: node dist/analysis/trade_profitability.js <
|
|
39
|
+
Usage: node dist/analysis/trade_profitability.js <account|bot> [options]
|
|
31
40
|
|
|
32
41
|
Analyzes filled orders for a BitShares account, computing realized PnL
|
|
33
42
|
via FIFO or sequential (LIFO) inventory tracking.
|
|
34
43
|
|
|
35
44
|
Arguments:
|
|
36
|
-
|
|
45
|
+
account|bot Local bot profile name, BitShares account name, or 1.2.x id.
|
|
46
|
+
Local profiles are checked first, then the chain.
|
|
37
47
|
|
|
38
48
|
Options:
|
|
49
|
+
--month <n> Lookback months (730 h each; default 3; alias --months).
|
|
39
50
|
--start <iso> Start time (ISO 8601, e.g. 2025-01-01 or 2025-01-01T00:00:00Z)
|
|
40
51
|
--end <iso> End time (ISO 8601)
|
|
41
|
-
--hours <n> Lookback hours from now (alternative to --start/--end)
|
|
52
|
+
--hours <n> Lookback hours from now (alternative to --month/--start/--end)
|
|
53
|
+
--pair <BASE/QUOTE> Filter to one pair, by symbol or 1.3.x id (e.g. TOKENA/BTS)
|
|
42
54
|
--asset <assetId> Filter to one base asset (e.g. 1.3.113 for bitUSD)
|
|
43
|
-
--refresh-account Force re-resolution and
|
|
55
|
+
--refresh-account Force re-resolution and bypass the fills cache (re-query the range)
|
|
56
|
+
--html Write a self-contained HTML report instead of terminal tables
|
|
57
|
+
--report <file> Override the auto-named HTML report path (implies --html)
|
|
44
58
|
--csv <file> Export trade list as CSV
|
|
45
59
|
--json <file> Export full analysis as JSON
|
|
46
|
-
--trades Show per-order PnL detail (
|
|
60
|
+
--trades Show per-order PnL detail (terminal mode only)
|
|
47
61
|
--match-mode <mode> Matching mode: sequential (default, LIFO) or fifo
|
|
48
62
|
--fee-per-order <bts> Blockchain fee per limit_order_create op in BTS (default: 0.09652)
|
|
49
63
|
--verbose Print extra debug info
|
|
50
64
|
--help, -h Show this help
|
|
51
65
|
|
|
52
66
|
Examples:
|
|
67
|
+
dexbot pnl my-bot --month 3
|
|
68
|
+
dexbot pnl 1.2.123456 --month 6 --pair TOKENA/BTS
|
|
53
69
|
node dist/analysis/trade_profitability.js 1.2.123456 --hours 720
|
|
54
70
|
node dist/analysis/trade_profitability.js 1.2.123456 --start 2025-01-01 --end 2025-06-01
|
|
55
|
-
node dist/analysis/trade_profitability.js
|
|
56
|
-
node dist/analysis/trade_profitability.js 1.2.123456 --hours 720 --asset 1.3.113 --csv trades.csv
|
|
57
|
-
node dist/analysis/trade_profitability.js 1.2.123456 --hours 720 --match-mode sequential`);
|
|
71
|
+
node dist/analysis/trade_profitability.js 1.2.123456 --hours 720 --asset 1.3.113 --csv trades.csv`);
|
|
58
72
|
}
|
|
59
|
-
function parseArgs() {
|
|
60
|
-
|
|
61
|
-
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
73
|
+
function parseArgs(argv = process.argv.slice(2)) {
|
|
74
|
+
if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h') {
|
|
62
75
|
printHelp();
|
|
63
76
|
process.exit(0);
|
|
64
77
|
}
|
|
65
78
|
const opts = {
|
|
66
|
-
accountId:
|
|
79
|
+
accountId: argv[0],
|
|
67
80
|
hours: null,
|
|
81
|
+
months: null,
|
|
68
82
|
start: null,
|
|
69
83
|
end: null,
|
|
70
84
|
asset: null,
|
|
85
|
+
pair: null,
|
|
71
86
|
refreshAccount: false,
|
|
72
87
|
csv: null,
|
|
73
88
|
json: null,
|
|
@@ -75,55 +90,113 @@ function parseArgs() {
|
|
|
75
90
|
showPnlDetail: false,
|
|
76
91
|
verbose: false,
|
|
77
92
|
feePerOrder: null,
|
|
93
|
+
html: false,
|
|
94
|
+
report: null,
|
|
78
95
|
};
|
|
79
|
-
|
|
80
|
-
|
|
96
|
+
// Reject a missing flag value explicitly (e.g. `--pair` at end of argv)
|
|
97
|
+
// instead of silently letting `undefined` disable the option.
|
|
98
|
+
const requireValue = (name, raw) => {
|
|
99
|
+
const v = raw == null ? '' : String(raw);
|
|
100
|
+
if (!v || v.startsWith('--'))
|
|
101
|
+
throw new Error(`${name}: missing value`);
|
|
102
|
+
return v;
|
|
103
|
+
};
|
|
104
|
+
const setMonths = (raw) => {
|
|
105
|
+
const n = Number(raw);
|
|
106
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
107
|
+
throw new Error(`--month: invalid value "${raw}" (expected positive months, e.g. --month 6)`);
|
|
108
|
+
opts.months = n;
|
|
109
|
+
};
|
|
110
|
+
const setHours = (raw) => {
|
|
111
|
+
const n = Number(raw);
|
|
112
|
+
if (!Number.isFinite(n) || n <= 0)
|
|
113
|
+
throw new Error(`--hours: invalid value "${raw}" (expected positive hours)`);
|
|
114
|
+
opts.hours = n;
|
|
115
|
+
};
|
|
116
|
+
for (let i = 1; i < argv.length; i++) {
|
|
117
|
+
const arg = argv[i];
|
|
118
|
+
switch (arg) {
|
|
81
119
|
case '--hours':
|
|
82
|
-
|
|
120
|
+
setHours(requireValue('--hours', argv[++i]));
|
|
121
|
+
break;
|
|
122
|
+
case '--month':
|
|
123
|
+
case '--months':
|
|
124
|
+
setMonths(requireValue('--month', argv[++i]));
|
|
83
125
|
break;
|
|
84
126
|
case '--start':
|
|
85
|
-
opts.start =
|
|
127
|
+
opts.start = requireValue('--start', argv[++i]);
|
|
86
128
|
break;
|
|
87
129
|
case '--end':
|
|
88
|
-
opts.end =
|
|
130
|
+
opts.end = requireValue('--end', argv[++i]);
|
|
89
131
|
break;
|
|
90
132
|
case '--asset':
|
|
91
|
-
opts.asset =
|
|
133
|
+
opts.asset = requireValue('--asset', argv[++i]);
|
|
134
|
+
break;
|
|
135
|
+
case '--pair':
|
|
136
|
+
opts.pair = requireValue('--pair', argv[++i]);
|
|
92
137
|
break;
|
|
93
138
|
case '--refresh-account':
|
|
94
139
|
opts.refreshAccount = true;
|
|
95
140
|
break;
|
|
96
141
|
case '--csv':
|
|
97
|
-
opts.csv =
|
|
142
|
+
opts.csv = requireValue('--csv', argv[++i]);
|
|
98
143
|
break;
|
|
99
144
|
case '--json':
|
|
100
|
-
opts.json =
|
|
145
|
+
opts.json = requireValue('--json', argv[++i]);
|
|
101
146
|
break;
|
|
102
147
|
case '--trades':
|
|
103
148
|
opts.showPnlDetail = true;
|
|
104
149
|
break;
|
|
150
|
+
case '--html':
|
|
151
|
+
opts.html = true;
|
|
152
|
+
break;
|
|
153
|
+
case '--report':
|
|
154
|
+
opts.report = requireValue('--report', argv[++i]);
|
|
155
|
+
opts.html = true;
|
|
156
|
+
break;
|
|
105
157
|
case '--fee-per-order':
|
|
106
|
-
opts.feePerOrder = parseFloat(
|
|
158
|
+
opts.feePerOrder = parseFloat(requireValue('--fee-per-order', argv[++i]));
|
|
107
159
|
break;
|
|
108
160
|
case '--match-mode': {
|
|
109
|
-
const m =
|
|
110
|
-
if (m !== 'sequential' && m !== 'fifo')
|
|
111
|
-
|
|
112
|
-
process.exit(1);
|
|
113
|
-
}
|
|
161
|
+
const m = requireValue('--match-mode', argv[++i]);
|
|
162
|
+
if (m !== 'sequential' && m !== 'fifo')
|
|
163
|
+
throw new Error(`Invalid --match-mode: ${m} (expected: sequential | fifo)`);
|
|
114
164
|
opts.matchMode = m;
|
|
115
165
|
break;
|
|
116
166
|
}
|
|
117
167
|
case '--verbose':
|
|
118
168
|
opts.verbose = true;
|
|
119
169
|
break;
|
|
120
|
-
default:
|
|
121
|
-
|
|
122
|
-
|
|
170
|
+
default: {
|
|
171
|
+
// `--flag=value` spellings, same validation as the space form.
|
|
172
|
+
const eq = /^--(month|months|hours|start|end|asset|pair|csv|json|report)=(.*)$/.exec(arg);
|
|
173
|
+
if (eq) {
|
|
174
|
+
const [, name, rawValue] = eq;
|
|
175
|
+
if (name === 'month' || name === 'months')
|
|
176
|
+
setMonths(rawValue);
|
|
177
|
+
else if (name === 'hours')
|
|
178
|
+
setHours(rawValue);
|
|
179
|
+
else if (name === 'report') {
|
|
180
|
+
opts.report = requireValue('--report', rawValue);
|
|
181
|
+
opts.html = true;
|
|
182
|
+
}
|
|
183
|
+
else
|
|
184
|
+
opts[name] = requireValue(`--${name}`, rawValue);
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
throw new Error(`Unknown option: ${arg}`);
|
|
188
|
+
}
|
|
123
189
|
}
|
|
124
190
|
}
|
|
125
|
-
if (!opts.hours && !opts.start) {
|
|
126
|
-
opts.
|
|
191
|
+
if (!opts.hours && !opts.start && opts.months == null) {
|
|
192
|
+
opts.months = 3; // default: 3 months
|
|
193
|
+
}
|
|
194
|
+
if (opts.pair) {
|
|
195
|
+
const parts = String(opts.pair).split('/');
|
|
196
|
+
if (parts.length !== 2 || !parts[0].trim() || !parts[1].trim()) {
|
|
197
|
+
throw new Error(`--pair: expected BASE/QUOTE (e.g. --pair TOKENA/BTS), got "${opts.pair}"`);
|
|
198
|
+
}
|
|
199
|
+
opts.pair = { base: parts[0].trim(), quote: parts[1].trim() };
|
|
127
200
|
}
|
|
128
201
|
return opts;
|
|
129
202
|
}
|
|
@@ -137,7 +210,14 @@ function isValidFillAmounts(baseAmount, quoteAmount) {
|
|
|
137
210
|
return Number.isFinite(baseAmount) && Number.isFinite(quoteAmount)
|
|
138
211
|
&& baseAmount > 0 && quoteAmount > 0;
|
|
139
212
|
}
|
|
140
|
-
|
|
213
|
+
/** Match a user-supplied pair leg against a chain asset id or its symbol. */
|
|
214
|
+
function matchesAssetRef(ref, assetId) {
|
|
215
|
+
const want = String(ref).trim().toUpperCase();
|
|
216
|
+
if (!want)
|
|
217
|
+
return false;
|
|
218
|
+
return assetId.toUpperCase() === want || assetSymbol(assetId).toUpperCase() === want;
|
|
219
|
+
}
|
|
220
|
+
function classifyFills(fills, filterAsset, pairFilter = null) {
|
|
141
221
|
const trades = [];
|
|
142
222
|
const pairs = new Set();
|
|
143
223
|
let skipped = 0;
|
|
@@ -211,6 +291,8 @@ function classifyFills(fills, filterAsset) {
|
|
|
211
291
|
}
|
|
212
292
|
if (filterAsset && baseAsset !== filterAsset)
|
|
213
293
|
continue;
|
|
294
|
+
if (pairFilter && !(matchesAssetRef(pairFilter.base, baseAsset) && matchesAssetRef(pairFilter.quote, quoteAsset)))
|
|
295
|
+
continue;
|
|
214
296
|
// Validate market fee asset: fee is always deducted from receives
|
|
215
297
|
// (base for buys, quote for sells). Warn if unexpected.
|
|
216
298
|
if (marketFeeReal > 0 && marketFeeAsset !== '' && marketFeeAsset !== rAsset) {
|
|
@@ -393,10 +475,10 @@ function analyzePair(trades, matchMode = 'sequential') {
|
|
|
393
475
|
};
|
|
394
476
|
}
|
|
395
477
|
// ─── Output Helpers ──────────────────────────────────────────────────────────
|
|
396
|
-
function fmt(n
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
return
|
|
478
|
+
function fmt(n) {
|
|
479
|
+
// Shared 4-significant-figure formatter (see modules/order/format.ts) so
|
|
480
|
+
// terminal output matches the HTML report and `dexbot order`.
|
|
481
|
+
return Number.isFinite(n) ? formatFundsValue(n) : 'NaN';
|
|
400
482
|
}
|
|
401
483
|
function fmtPct(n) {
|
|
402
484
|
if (!Number.isFinite(n))
|
|
@@ -406,7 +488,18 @@ function fmtPct(n) {
|
|
|
406
488
|
function fmtAsset(id) {
|
|
407
489
|
return assetSymbol(id);
|
|
408
490
|
}
|
|
409
|
-
|
|
491
|
+
/** Group pairs by quote asset for the grand-total sections. */
|
|
492
|
+
function groupPairsByQuote(pairs) {
|
|
493
|
+
const quoteGroups = new Map();
|
|
494
|
+
for (const p of pairs) {
|
|
495
|
+
const q = p.quoteAsset;
|
|
496
|
+
if (!quoteGroups.has(q))
|
|
497
|
+
quoteGroups.set(q, []);
|
|
498
|
+
quoteGroups.get(q).push(p);
|
|
499
|
+
}
|
|
500
|
+
return quoteGroups;
|
|
501
|
+
}
|
|
502
|
+
function printSummary(pairs) {
|
|
410
503
|
console.log('');
|
|
411
504
|
for (const pair of pairs) {
|
|
412
505
|
const pairLabel = `${fmtAsset(pair.baseAsset)}/${fmtAsset(pair.quoteAsset)}`;
|
|
@@ -415,36 +508,30 @@ function printSummary(pairs, _accountId, _start, _end, _matchMode = 'sequential'
|
|
|
415
508
|
const avgBuy = pair.totalBuyBase > 0 ? pair.totalBuyQuote / pair.totalBuyBase : 0;
|
|
416
509
|
const avgSell = pair.totalSellBase > 0 ? pair.totalSellQuote / pair.totalSellBase : 0;
|
|
417
510
|
console.log(` ── ${pairLabel}`);
|
|
418
|
-
console.log(` Buys: ${fmt(totalBought
|
|
419
|
-
console.log(` Sells: ${fmt(totalSold
|
|
420
|
-
console.log(` Net
|
|
421
|
-
console.log(` Trades: ${pair.realizedPnls.length}
|
|
511
|
+
console.log(` Buys: ${fmt(totalBought)} @ ${fmt(avgBuy)} = ${fmt(pair.totalBuyQuote)} ${fmtAsset(pair.quoteAsset)}`);
|
|
512
|
+
console.log(` Sells: ${fmt(totalSold)} @ ${fmt(avgSell)} = ${fmt(pair.totalSellQuote)} ${fmtAsset(pair.quoteAsset)}`);
|
|
513
|
+
console.log(` Net inventory \u0394: ${fmt(pair.netPosition)} ${fmtAsset(pair.baseAsset)} (bought \u2212 sold in window)`);
|
|
514
|
+
console.log(` Trades: ${pair.realizedPnls.length} realized lots, ${pair.buys.length} buys, ${pair.sells.length} sells`);
|
|
422
515
|
if (pair.unmatchedSellBase > 0.0001) {
|
|
423
|
-
console.log(` Unmatched: ${fmt(pair.unmatchedSellBase
|
|
516
|
+
console.log(` Unmatched: ${fmt(pair.unmatchedSellBase)} ${fmtAsset(pair.baseAsset)} (sold without prior buy in window — expected if inventory predates window)`);
|
|
424
517
|
}
|
|
425
|
-
console.log(` Gross PnL: ${fmtAsset(pair.quoteAsset)} ${fmt(pair.totalRealizedPnl
|
|
518
|
+
console.log(` Gross PnL: ${fmtAsset(pair.quoteAsset)} ${fmt(pair.totalRealizedPnl)}`);
|
|
426
519
|
const mktFee = pair.totalMarketFees;
|
|
427
520
|
const blkFee = pair.totalBlockchainFees;
|
|
428
521
|
if (mktFee > 0.0001) {
|
|
429
|
-
console.log(` Market fees: ${fmtAsset(pair.quoteAsset)} ${fmt(-mktFee
|
|
522
|
+
console.log(` Market fees: ${fmtAsset(pair.quoteAsset)} ${fmt(-mktFee)}`);
|
|
430
523
|
}
|
|
431
524
|
if (blkFee > 0.0001) {
|
|
432
|
-
console.log(` Blockchain: BTS ${fmt(-blkFee
|
|
525
|
+
console.log(` Blockchain: BTS ${fmt(-blkFee)}`);
|
|
433
526
|
}
|
|
434
|
-
console.log(` Net PnL: ${fmtAsset(pair.quoteAsset)} ${fmt(pair.totalRealizedPnlNet
|
|
527
|
+
console.log(` Net PnL: ${fmtAsset(pair.quoteAsset)} ${fmt(pair.totalRealizedPnlNet)}`);
|
|
435
528
|
if (pair.quoteAsset !== BTS_ID) {
|
|
436
529
|
console.log(` ⚠ Non-BTS quote — PnL is in ${fmtAsset(pair.quoteAsset)}, not BTS`);
|
|
437
530
|
}
|
|
438
531
|
console.log('');
|
|
439
532
|
}
|
|
440
533
|
// Grand totals grouped by quote asset
|
|
441
|
-
const quoteGroups =
|
|
442
|
-
for (const p of pairs) {
|
|
443
|
-
const q = p.quoteAsset;
|
|
444
|
-
if (!quoteGroups.has(q))
|
|
445
|
-
quoteGroups.set(q, []);
|
|
446
|
-
quoteGroups.get(q).push(p);
|
|
447
|
-
}
|
|
534
|
+
const quoteGroups = groupPairsByQuote(pairs);
|
|
448
535
|
if (pairs.length > 1 && quoteGroups.size > 0) {
|
|
449
536
|
for (const [quoteAsset, group] of quoteGroups) {
|
|
450
537
|
const groupPnl = group.reduce((s, p) => s + p.totalRealizedPnl, 0);
|
|
@@ -454,15 +541,15 @@ function printSummary(pairs, _accountId, _start, _end, _matchMode = 'sequential'
|
|
|
454
541
|
const groupVol = group.reduce((s, p) => s + p.totalBuyQuote + p.totalSellQuote, 0);
|
|
455
542
|
const qSymbol = fmtAsset(quoteAsset);
|
|
456
543
|
console.log(` ── TOTAL (${qSymbol}) — ${group.length} pair(s)`);
|
|
457
|
-
console.log(` Gross PnL: ${fmtAsset(quoteAsset)} ${fmt(groupPnl
|
|
544
|
+
console.log(` Gross PnL: ${fmtAsset(quoteAsset)} ${fmt(groupPnl)}`);
|
|
458
545
|
if (groupMktFees > 0.0001) {
|
|
459
|
-
console.log(` Market fees: ${fmtAsset(quoteAsset)} ${fmt(-groupMktFees
|
|
546
|
+
console.log(` Market fees: ${fmtAsset(quoteAsset)} ${fmt(-groupMktFees)}`);
|
|
460
547
|
}
|
|
461
548
|
if (groupBlkFees > 0.0001) {
|
|
462
|
-
console.log(` Blockchain: BTS ${fmt(-groupBlkFees
|
|
549
|
+
console.log(` Blockchain: BTS ${fmt(-groupBlkFees)}`);
|
|
463
550
|
}
|
|
464
|
-
console.log(` Net PnL: ${fmtAsset(quoteAsset)} ${fmt(groupNet
|
|
465
|
-
console.log(` Volume: ${fmt(groupVol
|
|
551
|
+
console.log(` Net PnL: ${fmtAsset(quoteAsset)} ${fmt(groupNet)}`);
|
|
552
|
+
console.log(` Volume: ${fmt(groupVol)} ${qSymbol}`);
|
|
466
553
|
console.log('');
|
|
467
554
|
}
|
|
468
555
|
}
|
|
@@ -472,7 +559,7 @@ function printSummary(pairs, _accountId, _start, _end, _matchMode = 'sequential'
|
|
|
472
559
|
console.log(` fees are converted to quote asset. Buy lots are entered at net`);
|
|
473
560
|
console.log(` receives (gross minus buy-side market fee) so inventory matching`);
|
|
474
561
|
console.log(` reflects what the account actually held. If inventory predates the`);
|
|
475
|
-
console.log(` window or crosses asset pairs, the
|
|
562
|
+
console.log(` window or crosses asset pairs, the realized lots may not reflect`);
|
|
476
563
|
console.log(` true trade economics.`);
|
|
477
564
|
console.log('');
|
|
478
565
|
}
|
|
@@ -490,15 +577,15 @@ function printPnlDetail(pairs) {
|
|
|
490
577
|
for (let i = 0; i < pair.realizedPnls.length; i++) {
|
|
491
578
|
const r = pair.realizedPnls[i];
|
|
492
579
|
const idx = String(i + 1).padStart(2);
|
|
493
|
-
const bp = fmt(r.buyPrice
|
|
494
|
-
const ep = fmt(r.effPrice
|
|
495
|
-
const sp = fmt(r.sellPrice
|
|
496
|
-
const amt = fmt(r.amount
|
|
497
|
-
const pnlStr = fmt(r.pnl
|
|
580
|
+
const bp = fmt(r.buyPrice).padStart(11);
|
|
581
|
+
const ep = fmt(r.effPrice).padStart(11);
|
|
582
|
+
const sp = fmt(r.sellPrice).padStart(11);
|
|
583
|
+
const amt = fmt(r.amount).padStart(9);
|
|
584
|
+
const pnlStr = fmt(r.pnl).padStart(9);
|
|
498
585
|
const pctStr = fmtPct(r.pnlPct).padStart(8);
|
|
499
|
-
const mktFeeStr = fmt(r.marketFeeEntry + r.marketFeeExit
|
|
500
|
-
const feeStr = fmt(r.feeBts
|
|
501
|
-
const netStr = fmt(r.pnlNet
|
|
586
|
+
const mktFeeStr = fmt(r.marketFeeEntry + r.marketFeeExit).padStart(8);
|
|
587
|
+
const feeStr = fmt(r.feeBts).padStart(8);
|
|
588
|
+
const netStr = fmt(r.pnlNet).padStart(10);
|
|
502
589
|
const netPctStr = fmtPct(r.pnlNetPct).padStart(8);
|
|
503
590
|
const mk = (r.entryIsMaker ? 'M' : 'T') + '/' + (r.exitIsMaker ? 'M' : 'T') + ' ';
|
|
504
591
|
const et = (r.entryTime || '').slice(0, 22).padEnd(22);
|
|
@@ -539,6 +626,7 @@ function computeMetrics(pair, window) {
|
|
|
539
626
|
bestTradePct: 0, worstTradePct: 0,
|
|
540
627
|
mddPct: 0,
|
|
541
628
|
mddAbsBts: 0,
|
|
629
|
+
prePeakMinEquity: 0,
|
|
542
630
|
mddHadStablePeak: false,
|
|
543
631
|
isOngoingRecovery: false,
|
|
544
632
|
currentDrawdownDays: 0,
|
|
@@ -793,10 +881,12 @@ function computeMetrics(pair, window) {
|
|
|
793
881
|
}
|
|
794
882
|
if (hadStablePeak) {
|
|
795
883
|
mddPct *= 100;
|
|
884
|
+
prePeakMinEquity = 0;
|
|
796
885
|
}
|
|
797
886
|
else {
|
|
798
|
-
mddPct =
|
|
887
|
+
mddPct = 0;
|
|
799
888
|
mddAbsBts = 0;
|
|
889
|
+
prePeakMinEquity = hasPrePeakEquity ? prePeakMinEquity : 0;
|
|
800
890
|
}
|
|
801
891
|
// Payoff distribution stats
|
|
802
892
|
const pnlPcts = [...pnls.map(r => r.pnlPct)].sort((a, b) => a - b);
|
|
@@ -844,6 +934,7 @@ function computeMetrics(pair, window) {
|
|
|
844
934
|
worstTradePct,
|
|
845
935
|
mddPct,
|
|
846
936
|
mddAbsBts,
|
|
937
|
+
prePeakMinEquity,
|
|
847
938
|
mddHadStablePeak: hadStablePeak,
|
|
848
939
|
isOngoingRecovery,
|
|
849
940
|
currentDrawdownDays,
|
|
@@ -876,15 +967,15 @@ function printMetrics(pairs, window) {
|
|
|
876
967
|
// Edge
|
|
877
968
|
console.log(` Win Rate: ${(m.winRate * 100).toFixed(1)}%`);
|
|
878
969
|
console.log(` Profit Factor: ${m.profitFactor === Infinity ? '∞' : m.profitFactor.toFixed(2)}`);
|
|
879
|
-
const mktFeeStr = pair.totalMarketFees > 0.0001 ? ` (market ${fmt(pair.totalMarketFees
|
|
880
|
-
const blkFeeStr = pair.totalBlockchainFees > 0.0001 ? ` (op ${fmt(pair.totalBlockchainFees
|
|
970
|
+
const mktFeeStr = pair.totalMarketFees > 0.0001 ? ` (market ${fmt(pair.totalMarketFees)})` : '';
|
|
971
|
+
const blkFeeStr = pair.totalBlockchainFees > 0.0001 ? ` (op ${fmt(pair.totalBlockchainFees)} BTS)` : '';
|
|
881
972
|
console.log(` Fee Drag: ${m.feeDragPct > 0 ? m.feeDragPct.toFixed(2) + '% of gross profit' + mktFeeStr + blkFeeStr : '—'}`);
|
|
882
973
|
console.log(` Avg Win / Avg Loss: ${m.avgWinLossRatio === Infinity ? '∞' : m.avgWinLossRatio.toFixed(2)}`);
|
|
883
974
|
const qSymbol = fmtAsset(pair.quoteAsset);
|
|
884
|
-
console.log(` Expectancy (gross): ${fmt(m.expectancyBts
|
|
975
|
+
console.log(` Expectancy (gross): ${fmt(m.expectancyBts)} ${qSymbol} (${fmtPct(m.expectancyPct)}) per trade`);
|
|
885
976
|
const rDisplay = m.expectancyR === Infinity ? '∞' : m.expectancyR.toFixed(3) + 'R';
|
|
886
977
|
console.log(` Expectancy (R): ${rDisplay}`);
|
|
887
|
-
console.log(` Expectancy (net): ${fmt(m.netExpectancyBts
|
|
978
|
+
console.log(` Expectancy (net): ${fmt(m.netExpectancyBts)} ${qSymbol} per trade`);
|
|
888
979
|
console.log('');
|
|
889
980
|
// Edge quality
|
|
890
981
|
console.log(` Median R: ${m.medianR.toFixed(2)}`);
|
|
@@ -909,14 +1000,14 @@ function printMetrics(pairs, window) {
|
|
|
909
1000
|
const spanStr = m.scoredSpanDays < m.periodSpanDays - 1e-9
|
|
910
1001
|
? `${m.scoredSpanDays.toFixed(1)}d scored of ${m.periodSpanDays.toFixed(1)}d window`
|
|
911
1002
|
: `${m.periodSpanDays.toFixed(1)}d`;
|
|
912
|
-
console.log(` Projected net PnL: ${fmt(m.projectedNetPnlAnn
|
|
1003
|
+
console.log(` Projected net PnL: ${fmt(m.projectedNetPnlAnn)} ${qSymbol}/yr (${fmt(m.projectedNetPnlPerDay)}/day over ${spanStr})`);
|
|
913
1004
|
console.log('');
|
|
914
1005
|
// Tail risk
|
|
915
1006
|
if (m.mddHadStablePeak) {
|
|
916
|
-
console.log(` Max Drawdown: ${fmt(m.mddAbsBts
|
|
1007
|
+
console.log(` Max Drawdown: ${fmt(m.mddAbsBts)} ${qSymbol} (${fmtPct(m.mddPct)} of peak cumulative profit)`);
|
|
917
1008
|
}
|
|
918
1009
|
else {
|
|
919
|
-
console.log(` Min Equity: ${fmt(m.
|
|
1010
|
+
console.log(` Min Equity: ${fmt(m.prePeakMinEquity)} ${fmtAsset(pair.quoteAsset)}`);
|
|
920
1011
|
}
|
|
921
1012
|
const recLabel = m.maxRecoveryDays > 0 ? m.maxRecoveryDays.toFixed(1) + ' days' + (m.isOngoingRecovery ? ' (ongoing)' : '') : '—';
|
|
922
1013
|
console.log(` Max Recovery Time: ${recLabel}`);
|
|
@@ -935,17 +1026,11 @@ function printMetrics(pairs, window) {
|
|
|
935
1026
|
console.log(` Partial fills/order: ${m.fillsPerOrderMean.toFixed(2)} mean, ${m.fillsPerOrderMedian.toFixed(1)} med, ${m.fillsPerOrderMax} max`);
|
|
936
1027
|
console.log(` One-shot orders: ${(m.oneShotOrderRatio * 100).toFixed(0)}%`);
|
|
937
1028
|
console.log(` Fills/day: ${m.fillsPerDay.toFixed(2)}`);
|
|
938
|
-
console.log(` Avg vol/day: ${fmt(m.avgVolumePerDay
|
|
1029
|
+
console.log(` Avg vol/day: ${fmt(m.avgVolumePerDay)} ${fmtAsset(pair.quoteAsset)}`);
|
|
939
1030
|
console.log('');
|
|
940
1031
|
}
|
|
941
1032
|
// Grand totals grouped by quote asset
|
|
942
|
-
const quoteGroups =
|
|
943
|
-
for (const p of pairs) {
|
|
944
|
-
const q = p.quoteAsset;
|
|
945
|
-
if (!quoteGroups.has(q))
|
|
946
|
-
quoteGroups.set(q, []);
|
|
947
|
-
quoteGroups.get(q).push(p);
|
|
948
|
-
}
|
|
1033
|
+
const quoteGroups = groupPairsByQuote(pairs);
|
|
949
1034
|
if (pairs.length > 1 && quoteGroups.size > 0) {
|
|
950
1035
|
for (const [quoteAsset, group] of quoteGroups) {
|
|
951
1036
|
const totalLots = group.reduce((s, p) => s + p.realizedPnls.length, 0);
|
|
@@ -957,11 +1042,11 @@ function printMetrics(pairs, window) {
|
|
|
957
1042
|
console.log(` Lots: ${totalLots}`);
|
|
958
1043
|
const feeParts = [];
|
|
959
1044
|
if (totalMktFees > 0.0001)
|
|
960
|
-
feeParts.push(`market ${fmt(totalMktFees
|
|
1045
|
+
feeParts.push(`market ${fmt(totalMktFees)} ${qSymbol}`);
|
|
961
1046
|
if (totalBlkFees > 0.0001)
|
|
962
|
-
feeParts.push(`op ${fmt(totalBlkFees
|
|
1047
|
+
feeParts.push(`op ${fmt(totalBlkFees)} BTS`);
|
|
963
1048
|
const feeSuffix = feeParts.length > 0 ? ` (${feeParts.join(', ')})` : '';
|
|
964
|
-
console.log(` Net PnL: ${fmtAsset(quoteAsset)} ${fmt(totalNet
|
|
1049
|
+
console.log(` Net PnL: ${fmtAsset(quoteAsset)} ${fmt(totalNet)}${feeSuffix}`);
|
|
965
1050
|
console.log('');
|
|
966
1051
|
}
|
|
967
1052
|
}
|
|
@@ -1044,21 +1129,38 @@ function normalizeTimeBound(raw, isEnd) {
|
|
|
1044
1129
|
}
|
|
1045
1130
|
return new Date(ms).toISOString();
|
|
1046
1131
|
}
|
|
1047
|
-
|
|
1048
|
-
|
|
1132
|
+
/** Auto-named report file: bot/account + pair filter + requested range. */
|
|
1133
|
+
function reportFileName(opts, accountRef, botName) {
|
|
1134
|
+
const slugBase = botName ? sanitizeKey(botName) : sanitizeKey(accountRef);
|
|
1135
|
+
const pair = opts.pair;
|
|
1136
|
+
const pairSlug = pair ? `_${sanitizeKey(pair.base)}-${sanitizeKey(pair.quote)}` : '';
|
|
1137
|
+
let rangeSlug;
|
|
1138
|
+
if (opts.months != null)
|
|
1139
|
+
rangeSlug = `_${String(opts.months).replace('.', 'p')}m`;
|
|
1140
|
+
else if (opts.start)
|
|
1141
|
+
rangeSlug = `_${String(opts.start).slice(0, 10)}${opts.end ? '_' + String(opts.end).slice(0, 10) : ''}`;
|
|
1142
|
+
else
|
|
1143
|
+
rangeSlug = `_${opts.hours || 168}h`;
|
|
1144
|
+
return `pnl_${slugBase}${pairSlug}${rangeSlug}.html`;
|
|
1145
|
+
}
|
|
1146
|
+
async function run(argv = process.argv.slice(2)) {
|
|
1147
|
+
muteChainLogs();
|
|
1148
|
+
const opts = parseArgs(argv);
|
|
1049
1149
|
let accountId = opts.accountId;
|
|
1150
|
+
let resolvedBotName = null;
|
|
1050
1151
|
if (!/^1\.2\.\d+$/.test(String(accountId))) {
|
|
1051
1152
|
// The Kibana query below filters on the 1.2.x account_id field, so a
|
|
1052
1153
|
// name must always resolve first (a raw name would silently return
|
|
1053
|
-
// zero fills). Shared resolver:
|
|
1054
|
-
//
|
|
1055
|
-
// back onto the bot entry
|
|
1154
|
+
// zero fills). Shared resolver: a local bot profile is checked first
|
|
1155
|
+
// (no chain call), then a stored accountId, then a fresh lookup; the
|
|
1156
|
+
// result is stamped back onto the bot entry.
|
|
1056
1157
|
const resolved = await resolveAccountRef(accountId, { refresh: opts.refreshAccount });
|
|
1057
1158
|
if (!resolved.accountId) {
|
|
1058
1159
|
console.error(` Could not resolve "${accountId}" to an account ID`);
|
|
1059
1160
|
process.exit(1);
|
|
1060
1161
|
}
|
|
1061
1162
|
accountId = resolved.accountId;
|
|
1163
|
+
resolvedBotName = resolved.botMeta?.name ?? null;
|
|
1062
1164
|
}
|
|
1063
1165
|
// Build time range
|
|
1064
1166
|
const now = new Date();
|
|
@@ -1072,13 +1174,15 @@ async function run() {
|
|
|
1072
1174
|
lte = now.toISOString();
|
|
1073
1175
|
}
|
|
1074
1176
|
else {
|
|
1075
|
-
const hours = opts.hours || 168;
|
|
1177
|
+
const hours = opts.months != null ? monthsToHours(opts.months) : (opts.hours || 168);
|
|
1076
1178
|
const start = new Date(now.getTime() - hours * 3600 * 1000);
|
|
1077
1179
|
gte = start.toISOString();
|
|
1078
1180
|
lte = now.toISOString();
|
|
1079
1181
|
}
|
|
1080
1182
|
const KIBANA_CFG = { timeout: 60000 };
|
|
1081
|
-
|
|
1183
|
+
// Month-shard cache keyed by the resolved accountId; --refresh-account
|
|
1184
|
+
// bypasses coverage trust and re-queries the requested range.
|
|
1185
|
+
const fills = await fetchFillsCached(KIBANA_CFG, accountId, gte, lte, { refresh: opts.refreshAccount });
|
|
1082
1186
|
if (fills.length === 0) {
|
|
1083
1187
|
console.log(' No fills found in the specified time range.');
|
|
1084
1188
|
process.exit(0);
|
|
@@ -1086,12 +1190,12 @@ async function run() {
|
|
|
1086
1190
|
// Resolve unknown asset precisions from blockchain
|
|
1087
1191
|
await resolveAssetPrecisions(fills);
|
|
1088
1192
|
// Classify fills
|
|
1089
|
-
const { trades, pairs } = classifyFills(fills, opts.asset);
|
|
1193
|
+
const { trades, pairs } = classifyFills(fills, opts.asset, opts.pair);
|
|
1090
1194
|
if (trades.length === 0) {
|
|
1091
|
-
console.log(' No trades could be classified (check asset filter or time range).');
|
|
1195
|
+
console.log(' No trades could be classified (check pair/asset filter or time range).');
|
|
1092
1196
|
process.exit(0);
|
|
1093
1197
|
}
|
|
1094
|
-
console.log(`Account: ${accountId}`);
|
|
1198
|
+
console.log(`Account: ${accountId}${resolvedBotName ? ` (bot: ${resolvedBotName})` : ''}`);
|
|
1095
1199
|
console.log(`Period: ${gte.slice(0, 10)} → ${lte.slice(0, 10)}`);
|
|
1096
1200
|
console.log(`Pairs: ${pairs.size}, ${trades.length} classified trades`);
|
|
1097
1201
|
const hasCrossPair = [...pairs].some(p => p.split(':')[1] !== BTS_ID);
|
|
@@ -1122,17 +1226,39 @@ async function run() {
|
|
|
1122
1226
|
analyses.push(analysis);
|
|
1123
1227
|
if (opts.verbose) {
|
|
1124
1228
|
const [base, quote] = key.split(':');
|
|
1125
|
-
console.log(` ${fmtAsset(base)}/${fmtAsset(quote)}: ${pairTrades.filter(t => t.direction === 'buy').length} buys, ${pairTrades.filter(t => t.direction === 'sell').length} sells, ${analysis.realizedPnls.length}
|
|
1229
|
+
console.log(` ${fmtAsset(base)}/${fmtAsset(quote)}: ${pairTrades.filter(t => t.direction === 'buy').length} buys, ${pairTrades.filter(t => t.direction === 'sell').length} sells, ${analysis.realizedPnls.length} realized lots`);
|
|
1126
1230
|
}
|
|
1127
1231
|
}
|
|
1128
1232
|
// Sort pairs by volume (total quote)
|
|
1129
1233
|
analyses.sort((a, b) => (b.totalBuyQuote + b.totalSellQuote) - (a.totalBuyQuote + a.totalSellQuote));
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1234
|
+
const reportWindow = { startMs: Date.parse(gte), endMs: Date.parse(lte) };
|
|
1235
|
+
if (opts.html) {
|
|
1236
|
+
// HTML is the primary output of `dexbot pnl`: write the self-contained
|
|
1237
|
+
// report and print the file link, skipping the terminal tables.
|
|
1238
|
+
const reportPath = opts.report
|
|
1239
|
+
? path.resolve(String(opts.report))
|
|
1240
|
+
: path.join(PATHS.ANALYSIS.CHARTS_DIR, reportFileName(opts, String(opts.accountId), resolvedBotName));
|
|
1241
|
+
writePnlReport({
|
|
1242
|
+
accountRef: String(opts.accountId),
|
|
1243
|
+
accountId,
|
|
1244
|
+
botName: resolvedBotName,
|
|
1245
|
+
start: gte,
|
|
1246
|
+
end: lte,
|
|
1247
|
+
matchMode: opts.matchMode,
|
|
1248
|
+
pairFilter: opts.pair ? `${opts.pair.base}/${opts.pair.quote}` : null,
|
|
1249
|
+
assetFilter: opts.asset,
|
|
1250
|
+
pairs: analyses.map(pair => ({ pair, metrics: computeMetrics(pair, reportWindow) })),
|
|
1251
|
+
}, reportPath);
|
|
1252
|
+
console.log(`\n📄 PnL report saved. Open report: (${toFileUrl(reportPath)})`);
|
|
1253
|
+
}
|
|
1254
|
+
else {
|
|
1255
|
+
// Output: summaries → grand total → per-match detail
|
|
1256
|
+
printSummary(analyses);
|
|
1257
|
+
if (opts.showPnlDetail) {
|
|
1258
|
+
printPnlDetail(analyses);
|
|
1259
|
+
}
|
|
1260
|
+
printMetrics(analyses, reportWindow);
|
|
1134
1261
|
}
|
|
1135
|
-
printMetrics(analyses, { startMs: Date.parse(gte), endMs: Date.parse(lte) });
|
|
1136
1262
|
if (opts.csv) {
|
|
1137
1263
|
exportCsv(analyses, opts.csv);
|
|
1138
1264
|
}
|
|
@@ -1140,7 +1266,7 @@ async function run() {
|
|
|
1140
1266
|
exportJson(accountId, gte, lte, analyses, opts.json);
|
|
1141
1267
|
}
|
|
1142
1268
|
}
|
|
1143
|
-
export { analyzePair, classifyFills, computeMetrics };
|
|
1269
|
+
export { analyzePair, classifyFills, computeMetrics, parseArgs, run, reportFileName };
|
|
1144
1270
|
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
1145
1271
|
run().then(() => process.exit(0)).catch(e => {
|
|
1146
1272
|
console.error('\n[fatal]', e.message);
|