dexbot 1.6.6 → 1.6.8
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 +89 -1
- package/README.md +8 -5
- package/analysis/README.md +2 -3
- package/analysis/tradingview/README.md +78 -1
- package/analysis/trend_detection/DYNAMIC_WEIGHT_RESEARCH.md +1 -1
- package/claw/package.json +1 -1
- package/claw/runtimes/openclaw-plugin/openclaw.plugin.json +1 -1
- package/claw/runtimes/openclaw-plugin/package.json +1 -1
- package/dist/analysis/tradingview/analyze_tradingview.d.ts +4 -0
- package/dist/analysis/tradingview/analyze_tradingview.js +55 -0
- package/dist/analysis/tradingview/grid_reset_config.d.ts +61 -0
- package/dist/analysis/tradingview/grid_reset_config.js +235 -0
- package/dist/analysis/tradingview/grid_reset_sim.d.ts +67 -0
- package/dist/analysis/tradingview/grid_reset_sim.js +307 -0
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js +419 -3
- package/dist/dexbot.js +44 -15
- package/dist/market_adapter/core/market_adapter_service.js +14 -2
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts +8 -1
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js +5 -1
- package/dist/market_adapter/inputs/window_cache.d.ts +97 -19
- package/dist/market_adapter/inputs/window_cache.js +302 -48
- package/dist/market_adapter/market_adapter.d.ts +8 -1
- package/dist/market_adapter/market_adapter.js +22 -4
- package/dist/modules/account_bots.js +20 -9
- package/dist/modules/account_orders.d.ts +44 -4
- package/dist/modules/account_orders.js +104 -7
- package/dist/modules/bitshares-native/chain_client.d.ts +10 -0
- package/dist/modules/bitshares-native/chain_client.js +197 -28
- package/dist/modules/bitshares-native/subscriptions.js +312 -10
- package/dist/modules/bitshares-native/transport.d.ts +1 -0
- package/dist/modules/bitshares-native/transport.js +97 -3
- package/dist/modules/bitshares_client.d.ts +20 -0
- package/dist/modules/bitshares_client.js +29 -0
- package/dist/modules/bot_settings.js +10 -1
- package/dist/modules/chain_keys.d.ts +37 -22
- package/dist/modules/chain_keys.js +145 -44
- package/dist/modules/cli_start_onboarding.d.ts +10 -0
- package/dist/modules/cli_start_onboarding.js +15 -0
- package/dist/modules/cli_start_output.d.ts +6 -0
- package/dist/modules/cli_start_output.js +8 -0
- package/dist/modules/config.d.ts +1 -0
- package/dist/modules/config.js +1 -0
- package/dist/modules/constants.d.ts +23 -2
- package/dist/modules/constants.js +196 -15
- package/dist/modules/dexbot_class.d.ts +6 -76
- package/dist/modules/dexbot_class.js +0 -32
- package/dist/modules/dexbot_cow_runtime.d.ts +3 -58
- package/dist/modules/dexbot_cow_runtime.js +53 -96
- package/dist/modules/dexbot_fill_runtime.d.ts +6 -1
- package/dist/modules/dexbot_fill_runtime.js +22 -3
- package/dist/modules/dexbot_maintenance_runtime.d.ts +38 -1
- package/dist/modules/dexbot_maintenance_runtime.js +103 -11
- package/dist/modules/dexbot_startup_runtime.js +73 -20
- package/dist/modules/dexbot_state_recovery.d.ts +6 -0
- package/dist/modules/dexbot_state_recovery.js +34 -1
- package/dist/modules/order/async_lock.d.ts +8 -0
- package/dist/modules/order/async_lock.js +15 -0
- package/dist/modules/order/genesis_policy.d.ts +162 -0
- package/dist/modules/order/genesis_policy.js +267 -0
- package/dist/modules/order/grid.js +109 -135
- package/dist/modules/order/grid_reconcile.d.ts +9 -0
- package/dist/modules/order/grid_reconcile.js +13 -4
- package/dist/modules/order/grid_reconcile_internal.js +13 -2
- package/dist/modules/order/logger.d.ts +12 -2
- package/dist/modules/order/logger.js +29 -7
- package/dist/modules/order/manager.d.ts +53 -0
- package/dist/modules/order/manager.js +86 -25
- package/dist/modules/order/sync_engine.d.ts +19 -0
- package/dist/modules/order/sync_engine.js +284 -344
- package/dist/modules/order/utils/math.d.ts +22 -1
- package/dist/modules/order/utils/math.js +64 -1
- package/dist/modules/order/utils/order.d.ts +43 -58
- package/dist/modules/order/utils/order.js +302 -194
- package/dist/modules/order/utils/system.d.ts +97 -0
- package/dist/modules/order/utils/system.js +282 -3
- package/dist/modules/paths.d.ts +8 -1
- package/dist/modules/paths.js +11 -3
- package/dist/modules/utils/text_width.d.ts +19 -0
- package/dist/modules/utils/text_width.js +97 -0
- package/dist/modules/version_notice.d.ts +165 -0
- package/dist/modules/version_notice.js +364 -0
- package/dist/pm2.js +104 -18
- package/dist/scripts/update.js +62 -13
- package/dist/unlock.d.ts +14 -2
- package/dist/unlock.js +101 -4
- package/docs/BITSHARES_ONBOARDING.md +8 -1
- package/docs/COW_INVARIANTS.md +11 -2
- package/docs/CREDENTIAL_SECURITY.md +26 -0
- package/docs/DEXBOT_COMPARISON.md +4 -4
- package/docs/EVOLUTION.md +20 -18
- package/docs/FUND_MOVEMENT_AND_ACCOUNTING.md +1 -1
- package/docs/GRID_PRICE_INVARIANT.md +204 -31
- package/docs/GRID_RECALCULATION.md +12 -0
- package/docs/LOGGING.md +17 -2
- package/docs/ORDER_ENGINE_POST_1.0_RETROSPECTIVE.md +6 -7
- package/docs/README.md +3 -1
- package/docs/WORKFLOW.md +16 -5
- package/market_adapter/README.md +1 -1
- package/modules/README.md +18 -1
- package/package.json +14 -6
- package/scripts/README.md +28 -2
- package/scripts/clear-all.sh +13 -4
- package/scripts/clear-logs.sh +13 -4
- package/scripts/clear-market-adapter.sh +6 -0
- package/scripts/clear-orders.sh +5 -0
- package/scripts/lib/dexbot-paths.sh +108 -0
- package/tests/README.md +11 -3
- package/analysis/account_resolver.ts +0 -161
- package/analysis/ama_fitting/analyze_ama_price_changes.ts +0 -155
- package/analysis/ama_fitting/analyze_lambda_vs_slow.ts +0 -404
- package/analysis/ama_fitting/calibrate_convergence_er.ts +0 -201
- package/analysis/ama_fitting/fetch_lp_candles.ts +0 -184
- package/analysis/ama_fitting/generate_unified_comparison_chart.ts +0 -232
- package/analysis/ama_fitting/optimizer_high_resolution.ts +0 -802
- package/analysis/analyze_dynamic_weight.ts +0 -243
- package/analysis/analyze_kalman.ts +0 -157
- package/analysis/analyze_regime.ts +0 -158
- package/analysis/analyze_regime_windows.ts +0 -470
- package/analysis/analyze_risk_profile.ts +0 -199
- package/analysis/analyze_trade_heatmap.ts +0 -362
- package/analysis/analyze_volatility.ts +0 -182
- package/analysis/bot_fitting/backtest_ama_sweep.ts +0 -934
- package/analysis/bot_fitting/backtest_bot_fitting.ts +0 -861
- package/analysis/bot_fitting/shared_utils.ts +0 -52
- package/analysis/bot_key_utils.ts +0 -426
- package/analysis/bot_usage/discover_bot_accounts.ts +0 -635
- package/analysis/bot_usage/kibana_bot_queries.ts +0 -211
- package/analysis/chain_pool.ts +0 -47
- package/analysis/chart_css.ts +0 -62
- package/analysis/chart_ui.ts +0 -105
- package/analysis/chart_utils.ts +0 -210
- package/analysis/fills_source.ts +0 -228
- package/analysis/grid_correction_check.ts +0 -786
- package/analysis/math_utils.ts +0 -53
- package/analysis/price_sources.ts +0 -136
- package/analysis/resolve_bot_accounts.ts +0 -199
- package/analysis/resolve_source.ts +0 -99
- package/analysis/results/ama_sweep_results_lp_pool_133_1h.json +0 -2455
- package/analysis/results/bot_fitting_results_lp_pool_133_1h.json +0 -218
- package/analysis/trade_profitability.ts +0 -1335
- package/analysis/tradingview/analyze_tradingview.ts +0 -280
- package/analysis/tradingview/h-bts_tradingview.html +0 -1570
- package/analysis/tradingview/t-bts_tradingview.html +0 -1570
- package/analysis/tradingview/tradingview_uplot_chart_generator.ts +0 -3268
- package/analysis/trend_detection/dynamic_weight_chart_generator.ts +0 -1481
- package/analysis/trend_detection/hurst_analyzer.ts +0 -7
- package/analysis/trend_detection/kalman_chart_generator.ts +0 -398
- package/analysis/trend_detection/kalman_trend_analyzer.ts +0 -9
- package/analysis/trend_detection/kalman_velocity_smoothing.ts +0 -7
- package/analysis/trend_detection/package.json +0 -23
- package/analysis/trend_detection/permutation_entropy_analyzer.ts +0 -7
- package/analysis/trend_detection/regime_chart_generator.ts +0 -338
- package/analysis/trend_detection/tests/test_kalman_trend.ts +0 -153
- package/analysis/trend_detection/tests/test_kalman_velocity_smoothing.ts +0 -64
- package/analysis/trend_detection/volatility_chart_generator.ts +0 -654
- package/analysis/tsconfig.json +0 -29
- package/claw/tests/package.json +0 -3
- package/claw/tests/test_claw_bridge.ts +0 -570
- package/claw/tests/test_claw_catalog_and_credentials.ts +0 -156
- package/claw/tests/test_claw_chain_layer.ts +0 -739
- package/claw/tests/test_claw_data_flow.ts +0 -525
- package/claw/tests/test_claw_domain_logic.ts +0 -471
- package/claw/tests/test_claw_manifest_and_matrix.ts +0 -222
- package/claw/tests/test_claw_mcp_transport.ts +0 -243
- package/claw/tests/test_claw_regressions.ts +0 -711
- package/claw/tests/test_claw_skill_generation.ts +0 -103
- package/claw/tests/test_claw_state_store.ts +0 -44
- package/claw/tests/test_dexbot_profiles.ts +0 -654
- package/claw/tests/test_memu_bridge.ts +0 -189
- package/claw/tests/test_nullclaw_tmp_integration.ts +0 -57
- package/claw/tests/test_position_health.ts +0 -343
- package/claw/tests/test_position_manager.ts +0 -429
- package/claw/tests/test_position_manager_watch_health.ts +0 -100
- package/claw/tests/test_short_mpa_strategy.ts +0 -232
- package/dist/analysis/account_resolver.d.ts.map +0 -1
- package/dist/analysis/account_resolver.js.map +0 -1
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/analyze_ama_price_changes.js.map +0 -1
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/analyze_lambda_vs_slow.js.map +0 -1
- package/dist/analysis/ama_fitting/calibrate_convergence_er.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/calibrate_convergence_er.js.map +0 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/fetch_lp_candles.js.map +0 -1
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/generate_unified_comparison_chart.js.map +0 -1
- package/dist/analysis/ama_fitting/optimizer_high_resolution.d.ts.map +0 -1
- package/dist/analysis/ama_fitting/optimizer_high_resolution.js.map +0 -1
- package/dist/analysis/analyze_dynamic_weight.d.ts.map +0 -1
- package/dist/analysis/analyze_dynamic_weight.js.map +0 -1
- package/dist/analysis/analyze_kalman.d.ts.map +0 -1
- package/dist/analysis/analyze_kalman.js.map +0 -1
- package/dist/analysis/analyze_regime.d.ts.map +0 -1
- package/dist/analysis/analyze_regime.js.map +0 -1
- package/dist/analysis/analyze_regime_windows.d.ts.map +0 -1
- package/dist/analysis/analyze_regime_windows.js.map +0 -1
- package/dist/analysis/analyze_risk_profile.d.ts.map +0 -1
- package/dist/analysis/analyze_risk_profile.js.map +0 -1
- package/dist/analysis/analyze_trade_heatmap.d.ts.map +0 -1
- package/dist/analysis/analyze_trade_heatmap.js.map +0 -1
- package/dist/analysis/analyze_volatility.d.ts.map +0 -1
- package/dist/analysis/analyze_volatility.js.map +0 -1
- package/dist/analysis/bot_fitting/backtest_ama_sweep.d.ts.map +0 -1
- package/dist/analysis/bot_fitting/backtest_ama_sweep.js.map +0 -1
- package/dist/analysis/bot_fitting/backtest_bot_fitting.d.ts.map +0 -1
- package/dist/analysis/bot_fitting/backtest_bot_fitting.js.map +0 -1
- package/dist/analysis/bot_fitting/shared_utils.d.ts.map +0 -1
- package/dist/analysis/bot_fitting/shared_utils.js.map +0 -1
- package/dist/analysis/bot_key_utils.d.ts.map +0 -1
- package/dist/analysis/bot_key_utils.js.map +0 -1
- package/dist/analysis/bot_usage/discover_bot_accounts.d.ts.map +0 -1
- package/dist/analysis/bot_usage/discover_bot_accounts.js.map +0 -1
- package/dist/analysis/bot_usage/kibana_bot_queries.d.ts.map +0 -1
- package/dist/analysis/bot_usage/kibana_bot_queries.js.map +0 -1
- package/dist/analysis/chain_pool.d.ts.map +0 -1
- package/dist/analysis/chain_pool.js.map +0 -1
- package/dist/analysis/chart_css.d.ts.map +0 -1
- package/dist/analysis/chart_css.js.map +0 -1
- package/dist/analysis/chart_ui.d.ts.map +0 -1
- package/dist/analysis/chart_ui.js.map +0 -1
- package/dist/analysis/chart_utils.d.ts.map +0 -1
- package/dist/analysis/chart_utils.js.map +0 -1
- package/dist/analysis/fills_source.d.ts.map +0 -1
- package/dist/analysis/fills_source.js.map +0 -1
- package/dist/analysis/grid_correction_check.d.ts.map +0 -1
- package/dist/analysis/grid_correction_check.js.map +0 -1
- package/dist/analysis/math_utils.d.ts.map +0 -1
- package/dist/analysis/math_utils.js.map +0 -1
- package/dist/analysis/price_sources.d.ts.map +0 -1
- package/dist/analysis/price_sources.js.map +0 -1
- package/dist/analysis/resolve_bot_accounts.d.ts.map +0 -1
- package/dist/analysis/resolve_bot_accounts.js.map +0 -1
- package/dist/analysis/resolve_source.d.ts.map +0 -1
- package/dist/analysis/resolve_source.js.map +0 -1
- package/dist/analysis/trade_profitability.d.ts.map +0 -1
- package/dist/analysis/trade_profitability.js.map +0 -1
- package/dist/analysis/tradingview/analyze_tradingview.d.ts.map +0 -1
- package/dist/analysis/tradingview/analyze_tradingview.js.map +0 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.d.ts.map +0 -1
- package/dist/analysis/tradingview/tradingview_uplot_chart_generator.js.map +0 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.d.ts.map +0 -1
- package/dist/analysis/trend_detection/dynamic_weight_chart_generator.js.map +0 -1
- package/dist/analysis/trend_detection/hurst_analyzer.d.ts.map +0 -1
- package/dist/analysis/trend_detection/hurst_analyzer.js.map +0 -1
- package/dist/analysis/trend_detection/kalman_chart_generator.d.ts.map +0 -1
- package/dist/analysis/trend_detection/kalman_chart_generator.js.map +0 -1
- package/dist/analysis/trend_detection/kalman_trend_analyzer.d.ts.map +0 -1
- package/dist/analysis/trend_detection/kalman_trend_analyzer.js.map +0 -1
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.d.ts.map +0 -1
- package/dist/analysis/trend_detection/kalman_velocity_smoothing.js.map +0 -1
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.d.ts.map +0 -1
- package/dist/analysis/trend_detection/permutation_entropy_analyzer.js.map +0 -1
- package/dist/analysis/trend_detection/regime_chart_generator.d.ts.map +0 -1
- package/dist/analysis/trend_detection/regime_chart_generator.js.map +0 -1
- package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts +0 -2
- package/dist/analysis/trend_detection/tests/test_kalman_trend.d.ts.map +0 -1
- package/dist/analysis/trend_detection/tests/test_kalman_trend.js +0 -128
- package/dist/analysis/trend_detection/tests/test_kalman_trend.js.map +0 -1
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts +0 -2
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.d.ts.map +0 -1
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js +0 -37
- package/dist/analysis/trend_detection/tests/test_kalman_velocity_smoothing.js.map +0 -1
- package/dist/analysis/trend_detection/volatility_chart_generator.d.ts.map +0 -1
- package/dist/analysis/trend_detection/volatility_chart_generator.js.map +0 -1
- package/dist/bot.d.ts.map +0 -1
- package/dist/bot.js.map +0 -1
- package/dist/credential-daemon.d.ts.map +0 -1
- package/dist/credential-daemon.js.map +0 -1
- package/dist/dexbot.d.ts.map +0 -1
- package/dist/dexbot.js.map +0 -1
- package/dist/market_adapter/ama_signal_runner.d.ts.map +0 -1
- package/dist/market_adapter/ama_signal_runner.js.map +0 -1
- package/dist/market_adapter/candle_utils.d.ts.map +0 -1
- package/dist/market_adapter/candle_utils.js.map +0 -1
- package/dist/market_adapter/core/asymmetric_bounds.d.ts.map +0 -1
- package/dist/market_adapter/core/asymmetric_bounds.js.map +0 -1
- package/dist/market_adapter/core/config_normalizers.d.ts.map +0 -1
- package/dist/market_adapter/core/config_normalizers.js.map +0 -1
- package/dist/market_adapter/core/kibana_candles.d.ts.map +0 -1
- package/dist/market_adapter/core/kibana_candles.js.map +0 -1
- package/dist/market_adapter/core/kibana_client.d.ts.map +0 -1
- package/dist/market_adapter/core/kibana_client.js.map +0 -1
- package/dist/market_adapter/core/kibana_market_candles.d.ts.map +0 -1
- package/dist/market_adapter/core/kibana_market_candles.js.map +0 -1
- package/dist/market_adapter/core/market_adapter_service.d.ts.map +0 -1
- package/dist/market_adapter/core/market_adapter_service.js.map +0 -1
- package/dist/market_adapter/core/signals/hurst_analyzer.d.ts.map +0 -1
- package/dist/market_adapter/core/signals/hurst_analyzer.js.map +0 -1
- package/dist/market_adapter/core/signals/kalman_trend_analyzer.d.ts.map +0 -1
- package/dist/market_adapter/core/signals/kalman_trend_analyzer.js.map +0 -1
- package/dist/market_adapter/core/signals/kalman_velocity_smoothing.d.ts.map +0 -1
- package/dist/market_adapter/core/signals/kalman_velocity_smoothing.js.map +0 -1
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.d.ts.map +0 -1
- package/dist/market_adapter/core/signals/permutation_entropy_analyzer.js.map +0 -1
- package/dist/market_adapter/core/strategies/ama.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/ama.js.map +0 -1
- package/dist/market_adapter/core/strategies/ama_slope_model.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/ama_slope_model.js.map +0 -1
- package/dist/market_adapter/core/strategies/atr/calculator.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/atr/calculator.js.map +0 -1
- package/dist/market_adapter/core/strategies/collateral_manager.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/collateral_manager.js.map +0 -1
- package/dist/market_adapter/core/strategies/dynamic_weight_series.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/dynamic_weight_series.js.map +0 -1
- package/dist/market_adapter/core/strategies/regime_gate.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/regime_gate.js.map +0 -1
- package/dist/market_adapter/core/strategies/regime_interp.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/regime_interp.js.map +0 -1
- package/dist/market_adapter/core/strategies/volatility_shift.d.ts.map +0 -1
- package/dist/market_adapter/core/strategies/volatility_shift.js.map +0 -1
- package/dist/market_adapter/inputs/fetch_book_data.d.ts.map +0 -1
- package/dist/market_adapter/inputs/fetch_book_data.js.map +0 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.d.ts.map +0 -1
- package/dist/market_adapter/inputs/fetch_cex_synthetic_data.js.map +0 -1
- package/dist/market_adapter/inputs/fetch_lp_data.d.ts.map +0 -1
- package/dist/market_adapter/inputs/fetch_lp_data.js.map +0 -1
- package/dist/market_adapter/inputs/kibana_feed_source.d.ts.map +0 -1
- package/dist/market_adapter/inputs/kibana_feed_source.js.map +0 -1
- package/dist/market_adapter/inputs/kibana_source.d.ts.map +0 -1
- package/dist/market_adapter/inputs/kibana_source.js.map +0 -1
- package/dist/market_adapter/inputs/window_cache.d.ts.map +0 -1
- package/dist/market_adapter/inputs/window_cache.js.map +0 -1
- package/dist/market_adapter/interval_utils.d.ts.map +0 -1
- package/dist/market_adapter/interval_utils.js.map +0 -1
- package/dist/market_adapter/log_format.d.ts.map +0 -1
- package/dist/market_adapter/log_format.js.map +0 -1
- package/dist/market_adapter/lp_chart_core.d.ts.map +0 -1
- package/dist/market_adapter/lp_chart_core.js.map +0 -1
- package/dist/market_adapter/lp_chart_runner.d.ts.map +0 -1
- package/dist/market_adapter/lp_chart_runner.js.map +0 -1
- package/dist/market_adapter/lp_chart_strategy_loader.d.ts.map +0 -1
- package/dist/market_adapter/lp_chart_strategy_loader.js.map +0 -1
- package/dist/market_adapter/market_adapter.d.ts.map +0 -1
- package/dist/market_adapter/market_adapter.js.map +0 -1
- package/dist/market_adapter/test_helpers.d.ts.map +0 -1
- package/dist/market_adapter/test_helpers.js.map +0 -1
- package/dist/market_adapter/utils/adapter_client.d.ts.map +0 -1
- package/dist/market_adapter/utils/adapter_client.js.map +0 -1
- package/dist/market_adapter/utils/atomic_write.d.ts.map +0 -1
- package/dist/market_adapter/utils/atomic_write.js.map +0 -1
- package/dist/market_adapter/utils/chain.d.ts.map +0 -1
- package/dist/market_adapter/utils/chain.js.map +0 -1
- package/dist/market_adapter/utils/data_discovery.d.ts.map +0 -1
- package/dist/market_adapter/utils/data_discovery.js.map +0 -1
- package/dist/market_adapter/utils/dynamic_grid_snapshot.d.ts.map +0 -1
- package/dist/market_adapter/utils/dynamic_grid_snapshot.js.map +0 -1
- package/dist/market_adapter/utils/file_lock.d.ts.map +0 -1
- package/dist/market_adapter/utils/file_lock.js.map +0 -1
- package/dist/market_adapter/utils/native_history.d.ts.map +0 -1
- package/dist/market_adapter/utils/native_history.js.map +0 -1
- package/dist/modules/account_bots.d.ts.map +0 -1
- package/dist/modules/account_bots.js.map +0 -1
- package/dist/modules/account_orders.d.ts.map +0 -1
- package/dist/modules/account_orders.js.map +0 -1
- package/dist/modules/authority_resolver.d.ts.map +0 -1
- package/dist/modules/authority_resolver.js.map +0 -1
- package/dist/modules/bitshares-native/chain_client.d.ts.map +0 -1
- package/dist/modules/bitshares-native/chain_client.js.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc.browser.d.ts.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc.browser.js.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc.d.ts.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc.js.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc_selector.d.ts.map +0 -1
- package/dist/modules/bitshares-native/crypto/ecc_selector.js.map +0 -1
- package/dist/modules/bitshares-native/index.d.ts.map +0 -1
- package/dist/modules/bitshares-native/index.js.map +0 -1
- package/dist/modules/bitshares-native/lru_cache.d.ts.map +0 -1
- package/dist/modules/bitshares-native/lru_cache.js.map +0 -1
- package/dist/modules/bitshares-native/resolvers.d.ts.map +0 -1
- package/dist/modules/bitshares-native/resolvers.js.map +0 -1
- package/dist/modules/bitshares-native/serial/chain_constants.d.ts.map +0 -1
- package/dist/modules/bitshares-native/serial/chain_constants.js.map +0 -1
- package/dist/modules/bitshares-native/serial/index.d.ts.map +0 -1
- package/dist/modules/bitshares-native/serial/index.js.map +0 -1
- package/dist/modules/bitshares-native/serial/operations.d.ts.map +0 -1
- package/dist/modules/bitshares-native/serial/operations.js.map +0 -1
- package/dist/modules/bitshares-native/serial/serializer.d.ts.map +0 -1
- package/dist/modules/bitshares-native/serial/serializer.js.map +0 -1
- package/dist/modules/bitshares-native/serial/types.d.ts.map +0 -1
- package/dist/modules/bitshares-native/serial/types.js.map +0 -1
- package/dist/modules/bitshares-native/signing_client.d.ts.map +0 -1
- package/dist/modules/bitshares-native/signing_client.js.map +0 -1
- package/dist/modules/bitshares-native/subscriptions.d.ts.map +0 -1
- package/dist/modules/bitshares-native/subscriptions.js.map +0 -1
- package/dist/modules/bitshares-native/transport.d.ts.map +0 -1
- package/dist/modules/bitshares-native/transport.js.map +0 -1
- package/dist/modules/bitshares-native/tx/builder.d.ts.map +0 -1
- package/dist/modules/bitshares-native/tx/builder.js.map +0 -1
- package/dist/modules/bitshares-native/tx/tx_cache.d.ts.map +0 -1
- package/dist/modules/bitshares-native/tx/tx_cache.js.map +0 -1
- package/dist/modules/bitshares_client.d.ts.map +0 -1
- package/dist/modules/bitshares_client.js.map +0 -1
- package/dist/modules/bot_defaults.d.ts.map +0 -1
- package/dist/modules/bot_defaults.js.map +0 -1
- package/dist/modules/bot_settings.d.ts.map +0 -1
- package/dist/modules/bot_settings.js.map +0 -1
- package/dist/modules/bots_file_lock.d.ts.map +0 -1
- package/dist/modules/bots_file_lock.js.map +0 -1
- package/dist/modules/broadcast_failure.d.ts.map +0 -1
- package/dist/modules/broadcast_failure.js.map +0 -1
- package/dist/modules/chain_keys.d.ts.map +0 -1
- package/dist/modules/chain_keys.js.map +0 -1
- package/dist/modules/chain_orders.d.ts.map +0 -1
- package/dist/modules/chain_orders.js.map +0 -1
- package/dist/modules/cli_colors.d.ts.map +0 -1
- package/dist/modules/cli_colors.js.map +0 -1
- package/dist/modules/config.d.ts.map +0 -1
- package/dist/modules/config.js.map +0 -1
- package/dist/modules/constants.d.ts.map +0 -1
- package/dist/modules/constants.js.map +0 -1
- package/dist/modules/cr_planner.d.ts.map +0 -1
- package/dist/modules/cr_planner.js.map +0 -1
- package/dist/modules/credential_policy.d.ts.map +0 -1
- package/dist/modules/credential_policy.js.map +0 -1
- package/dist/modules/credential_runtime.d.ts.map +0 -1
- package/dist/modules/credential_runtime.js.map +0 -1
- package/dist/modules/credential_session_cache.d.ts.map +0 -1
- package/dist/modules/credential_session_cache.js.map +0 -1
- package/dist/modules/credit_pricing.d.ts.map +0 -1
- package/dist/modules/credit_pricing.js.map +0 -1
- package/dist/modules/credit_runtime.d.ts.map +0 -1
- package/dist/modules/credit_runtime.js.map +0 -1
- package/dist/modules/crypto/browser_provider.d.ts.map +0 -1
- package/dist/modules/crypto/browser_provider.js.map +0 -1
- package/dist/modules/crypto/index.d.ts.map +0 -1
- package/dist/modules/crypto/index.js.map +0 -1
- package/dist/modules/crypto/node_provider.d.ts.map +0 -1
- package/dist/modules/crypto/node_provider.js.map +0 -1
- package/dist/modules/crypto/provider.d.ts.map +0 -1
- package/dist/modules/crypto/provider.js.map +0 -1
- package/dist/modules/crypto/pure_ripemd160.d.ts.map +0 -1
- package/dist/modules/crypto/pure_ripemd160.js.map +0 -1
- package/dist/modules/crypto/pure_scrypt.d.ts.map +0 -1
- package/dist/modules/crypto/pure_scrypt.js.map +0 -1
- package/dist/modules/crypto/pure_secp256k1.d.ts.map +0 -1
- package/dist/modules/crypto/pure_secp256k1.js.map +0 -1
- package/dist/modules/crypto/sync.d.ts.map +0 -1
- package/dist/modules/crypto/sync.js.map +0 -1
- package/dist/modules/daemon_node_health.d.ts.map +0 -1
- package/dist/modules/daemon_node_health.js.map +0 -1
- package/dist/modules/dexbot_class.d.ts.map +0 -1
- package/dist/modules/dexbot_class.js.map +0 -1
- package/dist/modules/dexbot_cow_runtime.d.ts.map +0 -1
- package/dist/modules/dexbot_cow_runtime.js.map +0 -1
- package/dist/modules/dexbot_credential_client.d.ts.map +0 -1
- package/dist/modules/dexbot_credential_client.js.map +0 -1
- package/dist/modules/dexbot_fill_runtime.d.ts.map +0 -1
- package/dist/modules/dexbot_fill_runtime.js.map +0 -1
- package/dist/modules/dexbot_maintenance_runtime.d.ts.map +0 -1
- package/dist/modules/dexbot_maintenance_runtime.js.map +0 -1
- package/dist/modules/dexbot_startup_runtime.d.ts.map +0 -1
- package/dist/modules/dexbot_startup_runtime.js.map +0 -1
- package/dist/modules/dexbot_state_recovery.d.ts.map +0 -1
- package/dist/modules/dexbot_state_recovery.js.map +0 -1
- package/dist/modules/env.d.ts.map +0 -1
- package/dist/modules/env.js.map +0 -1
- package/dist/modules/fund_registry.d.ts.map +0 -1
- package/dist/modules/fund_registry.js.map +0 -1
- package/dist/modules/general_settings.d.ts.map +0 -1
- package/dist/modules/general_settings.js.map +0 -1
- package/dist/modules/graceful_shutdown.d.ts.map +0 -1
- package/dist/modules/graceful_shutdown.js.map +0 -1
- package/dist/modules/grid_price_source.d.ts.map +0 -1
- package/dist/modules/grid_price_source.js.map +0 -1
- package/dist/modules/key_store.d.ts.map +0 -1
- package/dist/modules/key_store.js.map +0 -1
- package/dist/modules/launcher/adapter_requirement.d.ts.map +0 -1
- package/dist/modules/launcher/adapter_requirement.js.map +0 -1
- package/dist/modules/launcher/bot_supervisor.d.ts.map +0 -1
- package/dist/modules/launcher/bot_supervisor.js.map +0 -1
- package/dist/modules/launcher/child_env.d.ts.map +0 -1
- package/dist/modules/launcher/child_env.js.map +0 -1
- package/dist/modules/launcher/credential_bootstrap.d.ts.map +0 -1
- package/dist/modules/launcher/credential_bootstrap.js.map +0 -1
- package/dist/modules/launcher/credential_daemon.d.ts.map +0 -1
- package/dist/modules/launcher/credential_daemon.js.map +0 -1
- package/dist/modules/launcher/credential_secret.d.ts.map +0 -1
- package/dist/modules/launcher/credential_secret.js.map +0 -1
- package/dist/modules/launcher/foreign_cred_daemon.d.ts.map +0 -1
- package/dist/modules/launcher/foreign_cred_daemon.js.map +0 -1
- package/dist/modules/launcher/headless_password.d.ts.map +0 -1
- package/dist/modules/launcher/headless_password.js.map +0 -1
- package/dist/modules/launcher/launch_modes.d.ts.map +0 -1
- package/dist/modules/launcher/launch_modes.js.map +0 -1
- package/dist/modules/launcher/market_adapter_runtime.d.ts.map +0 -1
- package/dist/modules/launcher/market_adapter_runtime.js.map +0 -1
- package/dist/modules/launcher/market_adapter_watchdog.d.ts.map +0 -1
- package/dist/modules/launcher/market_adapter_watchdog.js.map +0 -1
- package/dist/modules/launcher/monolithic_runtime.d.ts.map +0 -1
- package/dist/modules/launcher/monolithic_runtime.js.map +0 -1
- package/dist/modules/launcher/runtime_entry.d.ts.map +0 -1
- package/dist/modules/launcher/runtime_entry.js.map +0 -1
- package/dist/modules/launcher/status_reporting.d.ts.map +0 -1
- package/dist/modules/launcher/status_reporting.js.map +0 -1
- package/dist/modules/launcher/supervisor_control.d.ts.map +0 -1
- package/dist/modules/launcher/supervisor_control.js.map +0 -1
- package/dist/modules/market_adapter_whitelist.d.ts.map +0 -1
- package/dist/modules/market_adapter_whitelist.js.map +0 -1
- package/dist/modules/node_connect_policy.d.ts.map +0 -1
- package/dist/modules/node_connect_policy.js.map +0 -1
- package/dist/modules/node_failure_ledger.d.ts.map +0 -1
- package/dist/modules/node_failure_ledger.js.map +0 -1
- package/dist/modules/node_health_cache.d.ts.map +0 -1
- package/dist/modules/node_health_cache.js.map +0 -1
- package/dist/modules/node_manager.d.ts.map +0 -1
- package/dist/modules/node_manager.js.map +0 -1
- package/dist/modules/order/accounting.d.ts.map +0 -1
- package/dist/modules/order/accounting.js.map +0 -1
- package/dist/modules/order/async_lock.d.ts.map +0 -1
- package/dist/modules/order/async_lock.js.map +0 -1
- package/dist/modules/order/export.d.ts.map +0 -1
- package/dist/modules/order/export.js.map +0 -1
- package/dist/modules/order/format.d.ts.map +0 -1
- package/dist/modules/order/format.js.map +0 -1
- package/dist/modules/order/grid.d.ts.map +0 -1
- package/dist/modules/order/grid.js.map +0 -1
- package/dist/modules/order/grid_reconcile.d.ts.map +0 -1
- package/dist/modules/order/grid_reconcile.js.map +0 -1
- package/dist/modules/order/grid_reconcile_internal.d.ts.map +0 -1
- package/dist/modules/order/grid_reconcile_internal.js.map +0 -1
- package/dist/modules/order/index.d.ts.map +0 -1
- package/dist/modules/order/index.js.map +0 -1
- package/dist/modules/order/logger.d.ts.map +0 -1
- package/dist/modules/order/logger.js.map +0 -1
- package/dist/modules/order/logger_state.d.ts.map +0 -1
- package/dist/modules/order/logger_state.js.map +0 -1
- package/dist/modules/order/manager.d.ts.map +0 -1
- package/dist/modules/order/manager.js.map +0 -1
- package/dist/modules/order/processed_fill_store.d.ts.map +0 -1
- package/dist/modules/order/processed_fill_store.js.map +0 -1
- package/dist/modules/order/strategy.d.ts.map +0 -1
- package/dist/modules/order/strategy.js.map +0 -1
- package/dist/modules/order/sync_engine.d.ts.map +0 -1
- package/dist/modules/order/sync_engine.js.map +0 -1
- package/dist/modules/order/utils/math.d.ts.map +0 -1
- package/dist/modules/order/utils/math.js.map +0 -1
- package/dist/modules/order/utils/order.d.ts.map +0 -1
- package/dist/modules/order/utils/order.js.map +0 -1
- package/dist/modules/order/utils/slot.d.ts.map +0 -1
- package/dist/modules/order/utils/slot.js.map +0 -1
- package/dist/modules/order/utils/system.d.ts.map +0 -1
- package/dist/modules/order/utils/system.js.map +0 -1
- package/dist/modules/order/utils/timeout.d.ts.map +0 -1
- package/dist/modules/order/utils/timeout.js.map +0 -1
- package/dist/modules/order/utils/validate.d.ts.map +0 -1
- package/dist/modules/order/utils/validate.js.map +0 -1
- package/dist/modules/order/utils/withPoolRef.d.ts.map +0 -1
- package/dist/modules/order/utils/withPoolRef.js.map +0 -1
- package/dist/modules/order/working_grid.d.ts.map +0 -1
- package/dist/modules/order/working_grid.js.map +0 -1
- package/dist/modules/path_api.d.ts.map +0 -1
- package/dist/modules/path_api.js.map +0 -1
- package/dist/modules/paths.d.ts.map +0 -1
- package/dist/modules/paths.js.map +0 -1
- package/dist/modules/process_discovery.d.ts.map +0 -1
- package/dist/modules/process_discovery.js.map +0 -1
- package/dist/modules/runtime.d.ts.map +0 -1
- package/dist/modules/runtime.js.map +0 -1
- package/dist/modules/runtime_settings.d.ts.map +0 -1
- package/dist/modules/runtime_settings.js.map +0 -1
- package/dist/modules/settings_merge.d.ts.map +0 -1
- package/dist/modules/settings_merge.js.map +0 -1
- package/dist/modules/socket_json_client.d.ts.map +0 -1
- package/dist/modules/socket_json_client.js.map +0 -1
- package/dist/modules/storage/browser_adapter.d.ts.map +0 -1
- package/dist/modules/storage/browser_adapter.js.map +0 -1
- package/dist/modules/storage/index.d.ts.map +0 -1
- package/dist/modules/storage/index.js.map +0 -1
- package/dist/modules/storage/node_adapter.d.ts.map +0 -1
- package/dist/modules/storage/node_adapter.js.map +0 -1
- package/dist/modules/storage/types.d.ts.map +0 -1
- package/dist/modules/storage/types.js.map +0 -1
- package/dist/modules/types.d.ts.map +0 -1
- package/dist/modules/types.js.map +0 -1
- package/dist/modules/utils/base58check.d.ts.map +0 -1
- package/dist/modules/utils/base58check.js.map +0 -1
- package/dist/modules/utils/build_dir.d.ts.map +0 -1
- package/dist/modules/utils/build_dir.js.map +0 -1
- package/dist/modules/utils/chain_logs.d.ts.map +0 -1
- package/dist/modules/utils/chain_logs.js.map +0 -1
- package/dist/modules/utils/errors.d.ts.map +0 -1
- package/dist/modules/utils/errors.js.map +0 -1
- package/dist/modules/utils/sanitize_key.d.ts.map +0 -1
- package/dist/modules/utils/sanitize_key.js.map +0 -1
- package/dist/modules/validate_profiles.d.ts.map +0 -1
- package/dist/modules/validate_profiles.js.map +0 -1
- package/dist/pm2.d.ts.map +0 -1
- package/dist/pm2.js.map +0 -1
- package/dist/scripts/analyze-credit.d.ts.map +0 -1
- package/dist/scripts/analyze-credit.js.map +0 -1
- package/dist/scripts/analyze-git.d.ts.map +0 -1
- package/dist/scripts/analyze-git.js.map +0 -1
- package/dist/scripts/analyze-orders.d.ts.map +0 -1
- package/dist/scripts/analyze-orders.js.map +0 -1
- package/dist/scripts/chart_command.d.ts.map +0 -1
- package/dist/scripts/chart_command.js.map +0 -1
- package/dist/scripts/diagnose-kibana-candles.d.ts.map +0 -1
- package/dist/scripts/diagnose-kibana-candles.js.map +0 -1
- package/dist/scripts/diagnose-pool-history.d.ts.map +0 -1
- package/dist/scripts/diagnose-pool-history.js.map +0 -1
- package/dist/scripts/divergence-calc.d.ts.map +0 -1
- package/dist/scripts/divergence-calc.js.map +0 -1
- package/dist/scripts/dw.d.ts.map +0 -1
- package/dist/scripts/dw.js.map +0 -1
- package/dist/scripts/generate_lp_chart.d.ts.map +0 -1
- package/dist/scripts/generate_lp_chart.js.map +0 -1
- package/dist/scripts/generate_mainnet_corpus_report.d.ts.map +0 -1
- package/dist/scripts/generate_mainnet_corpus_report.js.map +0 -1
- package/dist/scripts/native_release_gates.d.ts.map +0 -1
- package/dist/scripts/native_release_gates.js.map +0 -1
- package/dist/scripts/print_grid.d.ts.map +0 -1
- package/dist/scripts/print_grid.js.map +0 -1
- package/dist/scripts/run-tests.d.ts.map +0 -1
- package/dist/scripts/run-tests.js.map +0 -1
- package/dist/scripts/runner.d.ts.map +0 -1
- package/dist/scripts/runner.js.map +0 -1
- package/dist/scripts/sync-version.d.ts.map +0 -1
- package/dist/scripts/sync-version.js.map +0 -1
- package/dist/scripts/test-credit-renewal.d.ts.map +0 -1
- package/dist/scripts/test-credit-renewal.js.map +0 -1
- package/dist/scripts/tv.d.ts.map +0 -1
- package/dist/scripts/tv.js.map +0 -1
- package/dist/scripts/update.d.ts.map +0 -1
- package/dist/scripts/update.js.map +0 -1
- package/dist/scripts/update_dist_freshness.d.ts.map +0 -1
- package/dist/scripts/update_dist_freshness.js.map +0 -1
- package/dist/scripts/validate_bots.d.ts.map +0 -1
- package/dist/scripts/validate_bots.js.map +0 -1
- package/dist/scripts/verify-browser-bundle.d.ts.map +0 -1
- package/dist/scripts/verify-browser-bundle.js.map +0 -1
- package/dist/unlock.d.ts.map +0 -1
- package/dist/unlock.js.map +0 -1
|
@@ -1,1335 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
'use strict';
|
|
3
|
-
|
|
4
|
-
import fs from 'node:fs';
|
|
5
|
-
import { pathToFileURL } from 'node:url';
|
|
6
|
-
import { resolveAccountRef } from './account_resolver.js';
|
|
7
|
-
import {
|
|
8
|
-
BTS_ID,
|
|
9
|
-
assetPrec as getPrec,
|
|
10
|
-
assetSymbol,
|
|
11
|
-
fetchAllFills,
|
|
12
|
-
resolveAssetPrecisions,
|
|
13
|
-
toReal,
|
|
14
|
-
FillRecord,
|
|
15
|
-
} from './fills_source.js';
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* TRADE PROFITABILITY ANALYZER
|
|
19
|
-
*
|
|
20
|
-
* Fetches fill_order operations for a BitShares account from Kibana
|
|
21
|
-
* within a specified time range, then analyzes profitability using
|
|
22
|
-
* FIFO or sequential (LIFO) inventory tracking per asset pair.
|
|
23
|
-
*
|
|
24
|
-
* Usage:
|
|
25
|
-
* node dist/analysis/trade_profitability.js 1.2.3 --start 2025-01-01 --end 2025-06-01
|
|
26
|
-
* node dist/analysis/trade_profitability.js 1.2.3 --hours 720
|
|
27
|
-
* node dist/analysis/trade_profitability.js 1.2.3 --start 2025-01-01T00:00:00Z --end 2025-06-01T00:00:00Z
|
|
28
|
-
* node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --asset 1.3.113
|
|
29
|
-
* node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --csv trades.csv
|
|
30
|
-
* node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --json results.json
|
|
31
|
-
* node dist/analysis/trade_profitability.js "account-name" --hours 168
|
|
32
|
-
* node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --trades
|
|
33
|
-
* node dist/analysis/trade_profitability.js 1.2.3 --hours 168 --match-mode fifo
|
|
34
|
-
*/
|
|
35
|
-
|
|
36
|
-
// ─── Constants ────────────────────────────────────────────────────────────────
|
|
37
|
-
|
|
38
|
-
let BLOCKCHAIN_FEE_PER_FILL = 0.09652; // BTS — flat blockchain operation fee (not market fee); override with --fee-per-order
|
|
39
|
-
|
|
40
|
-
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
41
|
-
|
|
42
|
-
interface TradeFill {
|
|
43
|
-
time: string;
|
|
44
|
-
orderId: string;
|
|
45
|
-
direction: 'buy' | 'sell';
|
|
46
|
-
baseAsset: string;
|
|
47
|
-
quoteAsset: string;
|
|
48
|
-
baseAmount: number;
|
|
49
|
-
quoteAmount: number;
|
|
50
|
-
price: number;
|
|
51
|
-
isMaker: boolean;
|
|
52
|
-
sequence: number;
|
|
53
|
-
marketFeeReal: number;
|
|
54
|
-
marketFeeAsset: string;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
interface InventoryLot {
|
|
58
|
-
amount: number;
|
|
59
|
-
grossPrice: number;
|
|
60
|
-
effPrice: number;
|
|
61
|
-
time: string;
|
|
62
|
-
entryOrderId: string;
|
|
63
|
-
entryIsMaker: boolean;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
interface RealizedPnl {
|
|
67
|
-
sellPrice: number;
|
|
68
|
-
buyPrice: number;
|
|
69
|
-
amount: number;
|
|
70
|
-
pnl: number;
|
|
71
|
-
pnlPct: number;
|
|
72
|
-
effPrice: number;
|
|
73
|
-
marketFeeEntry: number;
|
|
74
|
-
marketFeeExit: number;
|
|
75
|
-
feeBts: number;
|
|
76
|
-
pnlNet: number;
|
|
77
|
-
pnlNetPct: number;
|
|
78
|
-
entryTime: string;
|
|
79
|
-
exitTime: string;
|
|
80
|
-
entryOrderId: string;
|
|
81
|
-
exitOrderId: string;
|
|
82
|
-
entryIsMaker: boolean;
|
|
83
|
-
exitIsMaker: boolean;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
interface PairAnalysis {
|
|
87
|
-
baseAsset: string;
|
|
88
|
-
quoteAsset: string;
|
|
89
|
-
buys: TradeFill[];
|
|
90
|
-
sells: TradeFill[];
|
|
91
|
-
realizedPnls: RealizedPnl[];
|
|
92
|
-
totalBuyBase: number;
|
|
93
|
-
totalSellBase: number;
|
|
94
|
-
totalBuyQuote: number;
|
|
95
|
-
totalSellQuote: number;
|
|
96
|
-
unmatchedSellBase: number;
|
|
97
|
-
totalRealizedPnl: number;
|
|
98
|
-
totalMarketFees: number;
|
|
99
|
-
totalBlockchainFees: number;
|
|
100
|
-
totalRealizedPnlNet: number;
|
|
101
|
-
netPosition: number;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
// ─── CLI ──────────────────────────────────────────────────────────────────────
|
|
105
|
-
|
|
106
|
-
function printHelp() {
|
|
107
|
-
console.log(`\
|
|
108
|
-
Usage: node dist/analysis/trade_profitability.js <accountId> [options]
|
|
109
|
-
|
|
110
|
-
Analyzes filled orders for a BitShares account, computing realized PnL
|
|
111
|
-
via FIFO or sequential (LIFO) inventory tracking.
|
|
112
|
-
|
|
113
|
-
Arguments:
|
|
114
|
-
accountId BitShares account ID (1.2.x) or name (auto-resolved in the background)
|
|
115
|
-
|
|
116
|
-
Options:
|
|
117
|
-
--start <iso> Start time (ISO 8601, e.g. 2025-01-01 or 2025-01-01T00:00:00Z)
|
|
118
|
-
--end <iso> End time (ISO 8601)
|
|
119
|
-
--hours <n> Lookback hours from now (alternative to --start/--end)
|
|
120
|
-
--asset <assetId> Filter to one base asset (e.g. 1.3.113 for bitUSD)
|
|
121
|
-
--refresh-account Force re-resolution and update the stored accountId
|
|
122
|
-
--csv <file> Export trade list as CSV
|
|
123
|
-
--json <file> Export full analysis as JSON
|
|
124
|
-
--trades Show per-order PnL detail (hidden by default)
|
|
125
|
-
--match-mode <mode> Matching mode: sequential (default, LIFO) or fifo
|
|
126
|
-
--fee-per-order <bts> Blockchain fee per limit_order_create op in BTS (default: 0.09652)
|
|
127
|
-
--verbose Print extra debug info
|
|
128
|
-
--help, -h Show this help
|
|
129
|
-
|
|
130
|
-
Examples:
|
|
131
|
-
node dist/analysis/trade_profitability.js 1.2.123456 --hours 720
|
|
132
|
-
node dist/analysis/trade_profitability.js 1.2.123456 --start 2025-01-01 --end 2025-06-01
|
|
133
|
-
node dist/analysis/trade_profitability.js "my-bot-account" --hours 168
|
|
134
|
-
node dist/analysis/trade_profitability.js 1.2.123456 --hours 720 --asset 1.3.113 --csv trades.csv
|
|
135
|
-
node dist/analysis/trade_profitability.js 1.2.123456 --hours 720 --match-mode sequential`);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
function parseArgs() {
|
|
139
|
-
const args = process.argv.slice(2);
|
|
140
|
-
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
|
141
|
-
printHelp();
|
|
142
|
-
process.exit(0);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
const opts: any = {
|
|
146
|
-
accountId: args[0],
|
|
147
|
-
hours: null,
|
|
148
|
-
start: null,
|
|
149
|
-
end: null,
|
|
150
|
-
asset: null,
|
|
151
|
-
refreshAccount: false,
|
|
152
|
-
csv: null,
|
|
153
|
-
json: null,
|
|
154
|
-
matchMode: 'sequential',
|
|
155
|
-
showPnlDetail: false,
|
|
156
|
-
verbose: false,
|
|
157
|
-
feePerOrder: null as number | null,
|
|
158
|
-
};
|
|
159
|
-
|
|
160
|
-
for (let i = 1; i < args.length; i++) {
|
|
161
|
-
switch (args[i]) {
|
|
162
|
-
case '--hours': opts.hours = parseInt(args[++i], 10); break;
|
|
163
|
-
case '--start': opts.start = args[++i]; break;
|
|
164
|
-
case '--end': opts.end = args[++i]; break;
|
|
165
|
-
case '--asset': opts.asset = args[++i]; break;
|
|
166
|
-
case '--refresh-account': opts.refreshAccount = true; break;
|
|
167
|
-
case '--csv': opts.csv = args[++i]; break;
|
|
168
|
-
case '--json': opts.json = args[++i]; break;
|
|
169
|
-
case '--trades': opts.showPnlDetail = true; break;
|
|
170
|
-
case '--fee-per-order': opts.feePerOrder = parseFloat(args[++i]); break;
|
|
171
|
-
case '--match-mode': {
|
|
172
|
-
const m = args[++i];
|
|
173
|
-
if (m !== 'sequential' && m !== 'fifo') {
|
|
174
|
-
console.error(`Invalid --match-mode: ${m} (expected: sequential | fifo)`);
|
|
175
|
-
process.exit(1);
|
|
176
|
-
}
|
|
177
|
-
opts.matchMode = m;
|
|
178
|
-
break;
|
|
179
|
-
}
|
|
180
|
-
case '--verbose': opts.verbose = true; break;
|
|
181
|
-
default:
|
|
182
|
-
console.error(`Unknown option: ${args[i]}`);
|
|
183
|
-
process.exit(1);
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
if (!opts.hours && !opts.start) {
|
|
188
|
-
opts.hours = 168; // default: 7 days
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
return opts;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
// ─── Fill Classification ─────────────────────────────────────────────────────
|
|
195
|
-
|
|
196
|
-
/**
|
|
197
|
-
* A fill needs strictly positive, finite amounts on both legs. A zero base
|
|
198
|
-
* amount would produce an infinite price (quoteAmount / 0) that poisons
|
|
199
|
-
* downstream inventory lots and PnL aggregates.
|
|
200
|
-
*/
|
|
201
|
-
function isValidFillAmounts(baseAmount: number, quoteAmount: number): boolean {
|
|
202
|
-
return Number.isFinite(baseAmount) && Number.isFinite(quoteAmount)
|
|
203
|
-
&& baseAmount > 0 && quoteAmount > 0;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
function classifyFills(fills: FillRecord[], filterAsset: string | null): { trades: TradeFill[]; pairs: Set<string> } {
|
|
207
|
-
const trades: TradeFill[] = [];
|
|
208
|
-
const pairs = new Set<string>();
|
|
209
|
-
let skipped = 0;
|
|
210
|
-
|
|
211
|
-
for (const f of fills) {
|
|
212
|
-
const pAsset = f.pays.asset_id;
|
|
213
|
-
const rAsset = f.receives.asset_id;
|
|
214
|
-
let direction: 'buy' | 'sell';
|
|
215
|
-
let baseAsset: string;
|
|
216
|
-
let quoteAsset: string;
|
|
217
|
-
let baseAmount: number;
|
|
218
|
-
let quoteAmount: number;
|
|
219
|
-
let price: number;
|
|
220
|
-
let marketFeeReal: number;
|
|
221
|
-
let marketFeeAsset: string;
|
|
222
|
-
|
|
223
|
-
const feePrec = getPrec(f.fee.asset_id);
|
|
224
|
-
if (feePrec === undefined || isNaN(f.fee.amount)) { skipped++; continue; }
|
|
225
|
-
const feeReal = f.fee.amount / Math.pow(10, feePrec);
|
|
226
|
-
|
|
227
|
-
if (pAsset === BTS_ID && rAsset !== BTS_ID) {
|
|
228
|
-
direction = 'buy';
|
|
229
|
-
baseAsset = rAsset;
|
|
230
|
-
quoteAsset = BTS_ID;
|
|
231
|
-
baseAmount = toReal(f.receives.amount, rAsset);
|
|
232
|
-
quoteAmount = toReal(f.pays.amount, BTS_ID);
|
|
233
|
-
if (!isValidFillAmounts(baseAmount, quoteAmount)) { skipped++; continue; }
|
|
234
|
-
price = quoteAmount / baseAmount;
|
|
235
|
-
marketFeeReal = feeReal;
|
|
236
|
-
marketFeeAsset = f.fee.asset_id;
|
|
237
|
-
} else if (rAsset === BTS_ID && pAsset !== BTS_ID) {
|
|
238
|
-
direction = 'sell';
|
|
239
|
-
baseAsset = pAsset;
|
|
240
|
-
quoteAsset = BTS_ID;
|
|
241
|
-
baseAmount = toReal(f.pays.amount, pAsset);
|
|
242
|
-
quoteAmount = toReal(f.receives.amount, BTS_ID);
|
|
243
|
-
if (!isValidFillAmounts(baseAmount, quoteAmount)) { skipped++; continue; }
|
|
244
|
-
price = quoteAmount / baseAmount;
|
|
245
|
-
marketFeeReal = feeReal;
|
|
246
|
-
marketFeeAsset = f.fee.asset_id;
|
|
247
|
-
} else {
|
|
248
|
-
// Non-BTS cross-pair: use consistent ordering (lower asset ID = base)
|
|
249
|
-
const baseForCheck = pAsset < rAsset ? pAsset : rAsset;
|
|
250
|
-
const quoteForCheck = pAsset < rAsset ? rAsset : pAsset;
|
|
251
|
-
// Skip if either asset precision is unknown
|
|
252
|
-
if (getPrec(baseForCheck) === undefined || getPrec(quoteForCheck) === undefined) { skipped++; continue; }
|
|
253
|
-
const isSell = pAsset < rAsset;
|
|
254
|
-
direction = isSell ? 'sell' : 'buy';
|
|
255
|
-
baseAsset = isSell ? pAsset : rAsset;
|
|
256
|
-
quoteAsset = isSell ? rAsset : pAsset;
|
|
257
|
-
baseAmount = toReal(isSell ? f.pays.amount : f.receives.amount, baseAsset);
|
|
258
|
-
quoteAmount = toReal(isSell ? f.receives.amount : f.pays.amount, quoteAsset);
|
|
259
|
-
if (!isValidFillAmounts(baseAmount, quoteAmount)) { skipped++; continue; }
|
|
260
|
-
price = quoteAmount / baseAmount;
|
|
261
|
-
marketFeeReal = feeReal;
|
|
262
|
-
marketFeeAsset = f.fee.asset_id;
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
if (filterAsset && baseAsset !== filterAsset) continue;
|
|
266
|
-
|
|
267
|
-
// Validate market fee asset: fee is always deducted from receives
|
|
268
|
-
// (base for buys, quote for sells). Warn if unexpected.
|
|
269
|
-
if (marketFeeReal > 0 && marketFeeAsset !== '' && marketFeeAsset !== rAsset) {
|
|
270
|
-
console.warn(` [warn] Fill ${f.orderId}: fee asset ${marketFeeAsset} ≠ receives asset ${rAsset}. Market fee PnL may be incorrect.`);
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
const pairKey = `${baseAsset}:${quoteAsset}`;
|
|
274
|
-
pairs.add(pairKey);
|
|
275
|
-
|
|
276
|
-
trades.push({
|
|
277
|
-
time: f.time,
|
|
278
|
-
orderId: f.orderId,
|
|
279
|
-
direction,
|
|
280
|
-
baseAsset,
|
|
281
|
-
quoteAsset,
|
|
282
|
-
baseAmount,
|
|
283
|
-
quoteAmount,
|
|
284
|
-
price,
|
|
285
|
-
isMaker: f.isMaker,
|
|
286
|
-
sequence: f.blockNum * 1e6 + f.opNum,
|
|
287
|
-
marketFeeReal,
|
|
288
|
-
marketFeeAsset,
|
|
289
|
-
});
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
if (skipped > 0) {
|
|
293
|
-
console.warn(` [warn] ${skipped} fill(s) skipped due to unknown asset precision.`);
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
return { trades, pairs };
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
// ─── PnL Calculation (FIFO / Sequential) ─────────────────────────────────────
|
|
300
|
-
|
|
301
|
-
function analyzePair(trades: TradeFill[], matchMode: 'fifo' | 'sequential' = 'sequential'): PairAnalysis {
|
|
302
|
-
const buys = trades.filter(t => t.direction === 'buy').sort((a, b) => a.sequence - b.sequence);
|
|
303
|
-
const sells = trades.filter(t => t.direction === 'sell').sort((a, b) => a.sequence - b.sequence);
|
|
304
|
-
|
|
305
|
-
const totalBuyBase = buys.reduce((s, t) => s + t.baseAmount, 0);
|
|
306
|
-
const totalSellBase = sells.reduce((s, t) => s + t.baseAmount, 0);
|
|
307
|
-
const totalBuyQuote = buys.reduce((s, t) => s + t.quoteAmount, 0);
|
|
308
|
-
const totalSellQuote = sells.reduce((s, t) => s + t.quoteAmount, 0);
|
|
309
|
-
|
|
310
|
-
// Merge all trades chronologically.
|
|
311
|
-
// FIFO: buys add to queue, sells consume oldest lots (queue front).
|
|
312
|
-
// Sequential: buys add to queue, sells consume newest lots (queue back / LIFO).
|
|
313
|
-
const all = [...trades].sort((a, b) => a.sequence - b.sequence);
|
|
314
|
-
const inventory: InventoryLot[] = [];
|
|
315
|
-
const realizedPnls: RealizedPnl[] = [];
|
|
316
|
-
let unmatchedSellBase = 0;
|
|
317
|
-
|
|
318
|
-
for (const trade of all) {
|
|
319
|
-
const grossPrice = trade.price;
|
|
320
|
-
|
|
321
|
-
if (trade.direction === 'buy') {
|
|
322
|
-
// Enter lot with net amount (gross receives minus market fee on receives)
|
|
323
|
-
const lotAmount = trade.baseAmount - trade.marketFeeReal;
|
|
324
|
-
if (lotAmount < 1e-12) continue;
|
|
325
|
-
const lotEffPrice = trade.quoteAmount / lotAmount;
|
|
326
|
-
inventory.push({
|
|
327
|
-
amount: lotAmount,
|
|
328
|
-
grossPrice: grossPrice,
|
|
329
|
-
effPrice: lotEffPrice,
|
|
330
|
-
time: trade.time,
|
|
331
|
-
entryOrderId: trade.orderId,
|
|
332
|
-
entryIsMaker: trade.isMaker,
|
|
333
|
-
});
|
|
334
|
-
} else {
|
|
335
|
-
let remaining = trade.baseAmount;
|
|
336
|
-
|
|
337
|
-
while (remaining > 0.00000001 && inventory.length > 0) {
|
|
338
|
-
const lotIndex = matchMode === 'sequential' ? inventory.length - 1 : 0;
|
|
339
|
-
const lot = inventory[lotIndex];
|
|
340
|
-
const matched = Math.min(remaining, lot.amount);
|
|
341
|
-
|
|
342
|
-
// Gross PnL using gross prices (before market fee deduction)
|
|
343
|
-
const grossPnl = (grossPrice - lot.grossPrice) * matched;
|
|
344
|
-
const grossPnlPct = lot.grossPrice > 0 ? ((grossPrice - lot.grossPrice) / lot.grossPrice) * 100 : 0;
|
|
345
|
-
|
|
346
|
-
realizedPnls.push({
|
|
347
|
-
sellPrice: grossPrice,
|
|
348
|
-
buyPrice: lot.grossPrice,
|
|
349
|
-
amount: matched,
|
|
350
|
-
pnl: grossPnl,
|
|
351
|
-
pnlPct: grossPnlPct,
|
|
352
|
-
effPrice: lot.effPrice,
|
|
353
|
-
marketFeeEntry: 0,
|
|
354
|
-
marketFeeExit: 0,
|
|
355
|
-
feeBts: 0,
|
|
356
|
-
pnlNet: grossPnl,
|
|
357
|
-
pnlNetPct: grossPnlPct,
|
|
358
|
-
entryTime: lot.time,
|
|
359
|
-
exitTime: trade.time,
|
|
360
|
-
entryOrderId: lot.entryOrderId,
|
|
361
|
-
exitOrderId: trade.orderId,
|
|
362
|
-
entryIsMaker: lot.entryIsMaker,
|
|
363
|
-
exitIsMaker: trade.isMaker,
|
|
364
|
-
});
|
|
365
|
-
|
|
366
|
-
lot.amount -= matched;
|
|
367
|
-
remaining -= matched;
|
|
368
|
-
|
|
369
|
-
if (lot.amount < 0.00000001) {
|
|
370
|
-
if (matchMode === 'sequential') {
|
|
371
|
-
inventory.pop();
|
|
372
|
-
} else {
|
|
373
|
-
inventory.shift();
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
|
|
378
|
-
if (remaining > 0.00000001) {
|
|
379
|
-
unmatchedSellBase += remaining;
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
// ─── Market fee allocation (aggregated per order) ──────────────────────
|
|
385
|
-
// A limit order may be filled across multiple fill_order_operations with
|
|
386
|
-
// the same orderId. Aggregate all fills' market fees per order, then
|
|
387
|
-
// allocate pro-rata using the fill's net acquired amount as denominator.
|
|
388
|
-
// (Market fee is paid on acquisition; the portion tied to unsold inventory
|
|
389
|
-
// is not yet realised.)
|
|
390
|
-
const entryOrderFees = new Map<string, { feeInQuote: number; totalAcquired: number }>();
|
|
391
|
-
const exitOrderFees = new Map<string, { feeInQuote: number; totalDisposed: number }>();
|
|
392
|
-
|
|
393
|
-
for (const t of buys) {
|
|
394
|
-
const e = entryOrderFees.get(t.orderId) || { feeInQuote: 0, totalAcquired: 0 };
|
|
395
|
-
if (t.marketFeeReal > 0) {
|
|
396
|
-
// Buy-side fee is in base → convert to quote using effective price
|
|
397
|
-
const netBase = t.baseAmount - t.marketFeeReal;
|
|
398
|
-
e.feeInQuote += netBase > 0 ? t.marketFeeReal * (t.quoteAmount / netBase) : 0;
|
|
399
|
-
}
|
|
400
|
-
e.totalAcquired += t.baseAmount - t.marketFeeReal;
|
|
401
|
-
entryOrderFees.set(t.orderId, e);
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
for (const t of sells) {
|
|
405
|
-
const e = exitOrderFees.get(t.orderId) || { feeInQuote: 0, totalDisposed: 0 };
|
|
406
|
-
if (t.marketFeeReal > 0)
|
|
407
|
-
e.feeInQuote += t.marketFeeReal; // Sell-side fee is already in quote
|
|
408
|
-
e.totalDisposed += t.baseAmount;
|
|
409
|
-
exitOrderFees.set(t.orderId, e);
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
for (const r of realizedPnls) {
|
|
413
|
-
const eObj = entryOrderFees.get(r.entryOrderId);
|
|
414
|
-
if (eObj && eObj.totalAcquired > 0)
|
|
415
|
-
r.marketFeeEntry = eObj.feeInQuote * (r.amount / eObj.totalAcquired);
|
|
416
|
-
|
|
417
|
-
const xObj = exitOrderFees.get(r.exitOrderId);
|
|
418
|
-
if (xObj && xObj.totalDisposed > 0)
|
|
419
|
-
r.marketFeeExit = xObj.feeInQuote * (r.amount / xObj.totalDisposed);
|
|
420
|
-
|
|
421
|
-
r.pnlNet = r.pnl - r.marketFeeEntry - r.marketFeeExit;
|
|
422
|
-
r.pnlNetPct = r.buyPrice > 0 ? (r.pnlNet / (r.buyPrice * r.amount)) * 100 : 0;
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
// ─── Blockchain fee allocation ─────────────────────────────────────────
|
|
426
|
-
const buyOrderIds = new Set(buys.map(t => t.orderId));
|
|
427
|
-
const sellOrderIds = new Set(sells.map(t => t.orderId));
|
|
428
|
-
const entryTotalMatched = new Map<string, number>();
|
|
429
|
-
const exitTotalMatched = new Map<string, number>();
|
|
430
|
-
for (const r of realizedPnls) {
|
|
431
|
-
entryTotalMatched.set(r.entryOrderId, (entryTotalMatched.get(r.entryOrderId) || 0) + r.amount);
|
|
432
|
-
exitTotalMatched.set(r.exitOrderId, (exitTotalMatched.get(r.exitOrderId) || 0) + r.amount);
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
const totalBlockchainFees = (buyOrderIds.size + sellOrderIds.size) * BLOCKCHAIN_FEE_PER_FILL;
|
|
436
|
-
for (const r of realizedPnls) {
|
|
437
|
-
const eTotal = entryTotalMatched.get(r.entryOrderId) || 1;
|
|
438
|
-
const xTotal = exitTotalMatched.get(r.exitOrderId) || 1;
|
|
439
|
-
r.feeBts = BLOCKCHAIN_FEE_PER_FILL * (r.amount / eTotal) + BLOCKCHAIN_FEE_PER_FILL * (r.amount / xTotal);
|
|
440
|
-
r.pnlNet -= r.feeBts;
|
|
441
|
-
const costBasis = r.effPrice * r.amount;
|
|
442
|
-
r.pnlNetPct = costBasis > 0 ? (r.pnlNet / costBasis) * 100 : 0;
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
const totalBuyBaseNet = buys.reduce((s, t) => s + t.baseAmount - t.marketFeeReal, 0);
|
|
446
|
-
const totalRealizedPnl = realizedPnls.reduce((s, r) => s + r.pnl, 0);
|
|
447
|
-
const totalMarketFees = realizedPnls.reduce((s, r) => s + r.marketFeeEntry + r.marketFeeExit, 0);
|
|
448
|
-
const totalRealizedPnlNet = realizedPnls.reduce((s, r) => s + r.pnlNet, 0);
|
|
449
|
-
const netPosition = totalBuyBaseNet - totalSellBase;
|
|
450
|
-
const baseAsset = trades[0]?.baseAsset ?? '';
|
|
451
|
-
const quoteAsset = trades[0]?.quoteAsset ?? '';
|
|
452
|
-
|
|
453
|
-
return {
|
|
454
|
-
baseAsset,
|
|
455
|
-
quoteAsset,
|
|
456
|
-
buys,
|
|
457
|
-
sells,
|
|
458
|
-
realizedPnls,
|
|
459
|
-
totalBuyBase,
|
|
460
|
-
totalSellBase,
|
|
461
|
-
totalBuyQuote,
|
|
462
|
-
totalSellQuote,
|
|
463
|
-
unmatchedSellBase,
|
|
464
|
-
totalRealizedPnl,
|
|
465
|
-
totalMarketFees,
|
|
466
|
-
totalBlockchainFees,
|
|
467
|
-
totalRealizedPnlNet,
|
|
468
|
-
netPosition,
|
|
469
|
-
};
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
// ─── Output Helpers ──────────────────────────────────────────────────────────
|
|
473
|
-
|
|
474
|
-
function fmt(n: number, decimals = 4): string {
|
|
475
|
-
if (!Number.isFinite(n)) return 'NaN';
|
|
476
|
-
return n.toLocaleString('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
function fmtPct(n: number): string {
|
|
480
|
-
if (!Number.isFinite(n)) return 'NaN%';
|
|
481
|
-
return (n >= 0 ? '+' : '') + n.toFixed(2) + '%';
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
function fmtAsset(id: string): string {
|
|
485
|
-
return assetSymbol(id);
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
function printSummary(pairs: PairAnalysis[], _accountId: string, _start: string, _end: string, _matchMode: 'fifo' | 'sequential' = 'sequential') {
|
|
489
|
-
console.log('');
|
|
490
|
-
|
|
491
|
-
for (const pair of pairs) {
|
|
492
|
-
const pairLabel = `${fmtAsset(pair.baseAsset)}/${fmtAsset(pair.quoteAsset)}`;
|
|
493
|
-
const totalBought = pair.totalBuyBase;
|
|
494
|
-
const totalSold = pair.totalSellBase;
|
|
495
|
-
const avgBuy = pair.totalBuyBase > 0 ? pair.totalBuyQuote / pair.totalBuyBase : 0;
|
|
496
|
-
const avgSell = pair.totalSellBase > 0 ? pair.totalSellQuote / pair.totalSellBase : 0;
|
|
497
|
-
|
|
498
|
-
console.log(` ── ${pairLabel}`);
|
|
499
|
-
console.log(` Buys: ${fmt(totalBought, 4)} @ ${fmt(avgBuy, 6)} = ${fmt(pair.totalBuyQuote, 4)} ${fmtAsset(pair.quoteAsset)}`);
|
|
500
|
-
console.log(` Sells: ${fmt(totalSold, 4)} @ ${fmt(avgSell, 6)} = ${fmt(pair.totalSellQuote, 4)} ${fmtAsset(pair.quoteAsset)}`);
|
|
501
|
-
console.log(` Net traded: ${fmt(pair.netPosition, 4)} ${fmtAsset(pair.baseAsset)} (window flow)`);
|
|
502
|
-
console.log(` Trades: ${pair.realizedPnls.length} matched lots, ${pair.buys.length} buys, ${pair.sells.length} sells`);
|
|
503
|
-
if (pair.unmatchedSellBase > 0.0001) {
|
|
504
|
-
console.log(` Unmatched: ${fmt(pair.unmatchedSellBase, 4)} ${fmtAsset(pair.baseAsset)} (sold without prior buy in window — expected if inventory predates window)`);
|
|
505
|
-
}
|
|
506
|
-
console.log(` Gross PnL: ${fmtAsset(pair.quoteAsset)} ${fmt(pair.totalRealizedPnl, 4)}`);
|
|
507
|
-
const mktFee = pair.totalMarketFees;
|
|
508
|
-
const blkFee = pair.totalBlockchainFees;
|
|
509
|
-
if (mktFee > 0.0001) {
|
|
510
|
-
console.log(` Market fees: ${fmtAsset(pair.quoteAsset)} ${fmt(-mktFee, 4)}`);
|
|
511
|
-
}
|
|
512
|
-
if (blkFee > 0.0001) {
|
|
513
|
-
console.log(` Blockchain: BTS ${fmt(-blkFee, 4)}`);
|
|
514
|
-
}
|
|
515
|
-
console.log(` Net PnL: ${fmtAsset(pair.quoteAsset)} ${fmt(pair.totalRealizedPnlNet, 4)}`);
|
|
516
|
-
if (pair.quoteAsset !== BTS_ID) {
|
|
517
|
-
console.log(` ⚠ Non-BTS quote — PnL is in ${fmtAsset(pair.quoteAsset)}, not BTS`);
|
|
518
|
-
}
|
|
519
|
-
console.log('');
|
|
520
|
-
}
|
|
521
|
-
|
|
522
|
-
// Grand totals grouped by quote asset
|
|
523
|
-
const quoteGroups = new Map<string, PairAnalysis[]>();
|
|
524
|
-
for (const p of pairs) {
|
|
525
|
-
const q = p.quoteAsset;
|
|
526
|
-
if (!quoteGroups.has(q)) quoteGroups.set(q, []);
|
|
527
|
-
quoteGroups.get(q)!.push(p);
|
|
528
|
-
}
|
|
529
|
-
if (pairs.length > 1 && quoteGroups.size > 0) {
|
|
530
|
-
for (const [quoteAsset, group] of quoteGroups) {
|
|
531
|
-
const groupPnl = group.reduce((s, p) => s + p.totalRealizedPnl, 0);
|
|
532
|
-
const groupMktFees = group.reduce((s, p) => s + p.totalMarketFees, 0);
|
|
533
|
-
const groupBlkFees = group.reduce((s, p) => s + p.totalBlockchainFees, 0);
|
|
534
|
-
const groupNet = group.reduce((s, p) => s + p.totalRealizedPnlNet, 0);
|
|
535
|
-
const groupVol = group.reduce((s, p) => s + p.totalBuyQuote + p.totalSellQuote, 0);
|
|
536
|
-
const qSymbol = fmtAsset(quoteAsset);
|
|
537
|
-
console.log(` ── TOTAL (${qSymbol}) — ${group.length} pair(s)`);
|
|
538
|
-
console.log(` Gross PnL: ${fmtAsset(quoteAsset)} ${fmt(groupPnl, 4)}`);
|
|
539
|
-
if (groupMktFees > 0.0001) {
|
|
540
|
-
console.log(` Market fees: ${fmtAsset(quoteAsset)} ${fmt(-groupMktFees, 4)}`);
|
|
541
|
-
}
|
|
542
|
-
if (groupBlkFees > 0.0001) {
|
|
543
|
-
console.log(` Blockchain: BTS ${fmt(-groupBlkFees, 4)}`);
|
|
544
|
-
}
|
|
545
|
-
console.log(` Net PnL: ${fmtAsset(quoteAsset)} ${fmt(groupNet, 4)}`);
|
|
546
|
-
console.log(` Volume: ${fmt(groupVol, 4)} ${qSymbol}`);
|
|
547
|
-
console.log('');
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
console.log(` Note: PnL uses gross prices. Net PnL deducts market fees (charged by`);
|
|
551
|
-
console.log(` asset issuer on receives, both issuer and network portions) and`);
|
|
552
|
-
console.log(` blockchain operation fees (BTS per limit_order_create). Market`);
|
|
553
|
-
console.log(` fees are converted to quote asset. Buy lots are entered at net`);
|
|
554
|
-
console.log(` receives (gross minus buy-side market fee) so inventory matching`);
|
|
555
|
-
console.log(` reflects what the account actually held. If inventory predates the`);
|
|
556
|
-
console.log(` window or crosses asset pairs, the matched lots may not reflect`);
|
|
557
|
-
console.log(` true trade economics.`);
|
|
558
|
-
console.log('');
|
|
559
|
-
}
|
|
560
|
-
|
|
561
|
-
function printPnlDetail(pairs: PairAnalysis[]) {
|
|
562
|
-
for (const pair of pairs) {
|
|
563
|
-
if (pair.realizedPnls.length === 0) continue;
|
|
564
|
-
|
|
565
|
-
const pairLabel = `${fmtAsset(pair.baseAsset)}/${fmtAsset(pair.quoteAsset)}`;
|
|
566
|
-
console.log('');
|
|
567
|
-
console.log(` ── ${pairLabel} — Realized PnL Detail`);
|
|
568
|
-
console.log('');
|
|
569
|
-
|
|
570
|
-
const hdr = ' # Buy Price EffBuy Sell Price Amount PnL PnL% MktFee OpFeeBTS Net PnL Net% Legs Entry Time Exit Time';
|
|
571
|
-
console.log(hdr);
|
|
572
|
-
console.log(' ' + '─'.repeat(hdr.length - 1));
|
|
573
|
-
|
|
574
|
-
for (let i = 0; i < pair.realizedPnls.length; i++) {
|
|
575
|
-
const r = pair.realizedPnls[i];
|
|
576
|
-
const idx = String(i + 1).padStart(2);
|
|
577
|
-
const bp = fmt(r.buyPrice, 8).padStart(11);
|
|
578
|
-
const ep = fmt(r.effPrice, 8).padStart(11);
|
|
579
|
-
const sp = fmt(r.sellPrice, 8).padStart(11);
|
|
580
|
-
const amt = fmt(r.amount, 4).padStart(9);
|
|
581
|
-
const pnlStr = fmt(r.pnl, 6).padStart(9);
|
|
582
|
-
const pctStr = fmtPct(r.pnlPct).padStart(8);
|
|
583
|
-
const mktFeeStr = fmt(r.marketFeeEntry + r.marketFeeExit, 4).padStart(8);
|
|
584
|
-
const feeStr = fmt(r.feeBts, 4).padStart(8);
|
|
585
|
-
const netStr = fmt(r.pnlNet, 6).padStart(10);
|
|
586
|
-
const netPctStr = fmtPct(r.pnlNetPct).padStart(8);
|
|
587
|
-
const mk = (r.entryIsMaker ? 'M' : 'T') + '/' + (r.exitIsMaker ? 'M' : 'T') + ' ';
|
|
588
|
-
const et = (r.entryTime || '').slice(0, 22).padEnd(22);
|
|
589
|
-
const xt = (r.exitTime || '').slice(0, 22).padEnd(22);
|
|
590
|
-
console.log(` ${idx} ${bp} ${ep} ${sp} ${amt} ${pnlStr} ${pctStr} ${mktFeeStr} ${feeStr} ${netStr} ${netPctStr} ${mk} ${et} ${xt}`);
|
|
591
|
-
}
|
|
592
|
-
console.log('');
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
// ─── Performance Metrics ──────────────────────────────────────────────────────
|
|
597
|
-
|
|
598
|
-
interface WindowRange {
|
|
599
|
-
/** The analysis window actually queried — drives annualisation. */
|
|
600
|
-
startMs: number;
|
|
601
|
-
endMs: number;
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
interface TradingMetrics {
|
|
605
|
-
totalLots: number;
|
|
606
|
-
winRate: number;
|
|
607
|
-
profitFactor: number;
|
|
608
|
-
avgWin: number;
|
|
609
|
-
avgLoss: number;
|
|
610
|
-
avgWinLossRatio: number;
|
|
611
|
-
expectancyBts: number;
|
|
612
|
-
expectancyPct: number;
|
|
613
|
-
expectancyR: number;
|
|
614
|
-
netExpectancyBts: number;
|
|
615
|
-
// Risk-adjusted ratios annualised from the analysis window (see
|
|
616
|
-
// --hours/--start/--end). Binned 1d for windows >= 3 days, else 1h; every
|
|
617
|
-
// period in the window is zero-filled so flat periods count as 0 PnL and
|
|
618
|
-
// the window scales cleanly to a year. Only whole periods are scored: a
|
|
619
|
-
// trailing partial period is excluded from ratios AND projection alike,
|
|
620
|
-
// so both share the same denominator.
|
|
621
|
-
sharpeAnn: number; // NaN when undefined (no dispersion / < 2 periods)
|
|
622
|
-
sortinoAnn: number; // Infinity when the window has no losing periods
|
|
623
|
-
sharpeAnnSE: number; // standard error of sharpeAnn (estimation uncertainty)
|
|
624
|
-
periodLabel: string; // '1h' | '1d'
|
|
625
|
-
periodCount: number; // whole periods scored, including zero-PnL ones
|
|
626
|
-
periodSpanDays: number; // queried window length
|
|
627
|
-
scoredSpanDays: number; // whole-period span actually scored (nPeriods × bin)
|
|
628
|
-
annualFactor: number; // sqrt(periods per year)
|
|
629
|
-
projectedNetPnlPerDay: number;
|
|
630
|
-
projectedNetPnlAnn: number;
|
|
631
|
-
maxConsecWins: number;
|
|
632
|
-
maxConsecLosses: number;
|
|
633
|
-
avgHoldHours: number;
|
|
634
|
-
limitOrderRatio: number;
|
|
635
|
-
bestTradePct: number;
|
|
636
|
-
worstTradePct: number;
|
|
637
|
-
mddPct: number;
|
|
638
|
-
mddAbsBts: number;
|
|
639
|
-
mddHadStablePeak: boolean;
|
|
640
|
-
isOngoingRecovery: boolean;
|
|
641
|
-
currentDrawdownDays: number;
|
|
642
|
-
medianPnlPct: number;
|
|
643
|
-
p25PnlPct: number;
|
|
644
|
-
p75PnlPct: number;
|
|
645
|
-
|
|
646
|
-
feeDragPct: number;
|
|
647
|
-
maxRecoveryDays: number;
|
|
648
|
-
sellOrdersFilled: number;
|
|
649
|
-
fillsPerOrderMean: number;
|
|
650
|
-
fillsPerOrderMedian: number;
|
|
651
|
-
fillsPerOrderMax: number;
|
|
652
|
-
oneShotOrderRatio: number;
|
|
653
|
-
fillsPerDay: number;
|
|
654
|
-
avgVolumePerDay: number;
|
|
655
|
-
medianR: number;
|
|
656
|
-
pctRGreater1: number;
|
|
657
|
-
pctRGreater2: number;
|
|
658
|
-
pctRLessNeg1: number;
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
function percentile(sorted: number[], p: number): number {
|
|
662
|
-
const n = sorted.length;
|
|
663
|
-
if (n === 0) return 0;
|
|
664
|
-
if (n === 1) return sorted[0];
|
|
665
|
-
const k = (p / 100) * (n - 1);
|
|
666
|
-
const f = Math.floor(k);
|
|
667
|
-
const c = Math.ceil(k);
|
|
668
|
-
if (f === c) return sorted[f];
|
|
669
|
-
return sorted[f] * (c - k) + sorted[c] * (k - f);
|
|
670
|
-
}
|
|
671
|
-
|
|
672
|
-
function computeMetrics(pair: PairAnalysis, window?: WindowRange): TradingMetrics {
|
|
673
|
-
const pnls = pair.realizedPnls;
|
|
674
|
-
const total = pnls.length;
|
|
675
|
-
if (total === 0) {
|
|
676
|
-
return {
|
|
677
|
-
totalLots: 0, winRate: 0, profitFactor: 0,
|
|
678
|
-
avgWin: 0, avgLoss: 0, avgWinLossRatio: 0,
|
|
679
|
-
expectancyBts: 0, expectancyPct: 0, expectancyR: 0,
|
|
680
|
-
netExpectancyBts: 0,
|
|
681
|
-
sharpeAnn: NaN, sortinoAnn: NaN, sharpeAnnSE: NaN,
|
|
682
|
-
periodLabel: '—', periodCount: 0, periodSpanDays: 0, scoredSpanDays: 0,
|
|
683
|
-
annualFactor: 0,
|
|
684
|
-
projectedNetPnlPerDay: 0, projectedNetPnlAnn: 0,
|
|
685
|
-
maxConsecWins: 0, maxConsecLosses: 0,
|
|
686
|
-
avgHoldHours: 0, limitOrderRatio: 0,
|
|
687
|
-
bestTradePct: 0, worstTradePct: 0,
|
|
688
|
-
mddPct: 0,
|
|
689
|
-
mddAbsBts: 0,
|
|
690
|
-
mddHadStablePeak: false,
|
|
691
|
-
isOngoingRecovery: false,
|
|
692
|
-
currentDrawdownDays: 0,
|
|
693
|
-
medianPnlPct: 0, p25PnlPct: 0, p75PnlPct: 0,
|
|
694
|
-
feeDragPct: 0, maxRecoveryDays: 0,
|
|
695
|
-
medianR: 0, pctRGreater1: 0, pctRGreater2: 0, pctRLessNeg1: 0,
|
|
696
|
-
sellOrdersFilled: 0, fillsPerOrderMean: 0, fillsPerOrderMedian: 0,
|
|
697
|
-
fillsPerOrderMax: 0, oneShotOrderRatio: 0, fillsPerDay: 0, avgVolumePerDay: 0,
|
|
698
|
-
};
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
const wins = pnls.filter(r => r.pnl > 0);
|
|
702
|
-
const losses = pnls.filter(r => r.pnl < 0);
|
|
703
|
-
const winRate = wins.length / total;
|
|
704
|
-
const makerEntryCount = pnls.filter(r => r.entryIsMaker).length;
|
|
705
|
-
const makerExitCount = pnls.filter(r => r.exitIsMaker).length;
|
|
706
|
-
const totalMakerLegs = makerEntryCount + makerExitCount;
|
|
707
|
-
|
|
708
|
-
const grossProfit = wins.reduce((s, r) => s + r.pnl, 0);
|
|
709
|
-
const grossLoss = Math.abs(losses.reduce((s, r) => s + r.pnl, 0));
|
|
710
|
-
const profitFactor = grossLoss > 0 ? grossProfit / grossLoss : grossProfit > 0 ? Infinity : 0;
|
|
711
|
-
const totalFeeDrag = pair.totalMarketFees + pair.totalBlockchainFees;
|
|
712
|
-
const feeDragPct = grossProfit > 0 ? (totalFeeDrag / grossProfit) * 100 : 0;
|
|
713
|
-
|
|
714
|
-
const avgWin = wins.length > 0 ? grossProfit / wins.length : 0;
|
|
715
|
-
const avgLoss = losses.length > 0 ? losses.reduce((s, r) => s + r.pnl, 0) / losses.length : 0;
|
|
716
|
-
|
|
717
|
-
const avgWinPct = wins.length > 0 ? wins.reduce((s, r) => s + r.pnlPct, 0) / wins.length : 0;
|
|
718
|
-
const avgLossPct = losses.length > 0 ? losses.reduce((s, r) => s + r.pnlPct, 0) / losses.length : 0;
|
|
719
|
-
|
|
720
|
-
const avgWinLossRatio = avgLoss !== 0 ? avgWin / Math.abs(avgLoss) : avgWin > 0 ? Infinity : 0;
|
|
721
|
-
|
|
722
|
-
const expectancyBts = (winRate * avgWin) + ((1 - winRate) * avgLoss);
|
|
723
|
-
const expectancyPct = (winRate * avgWinPct) + ((1 - winRate) * avgLossPct);
|
|
724
|
-
const rMultiple = Math.abs(avgLoss);
|
|
725
|
-
const expectancyR = rMultiple > 0
|
|
726
|
-
? winRate * (avgWin / rMultiple) - (1 - winRate)
|
|
727
|
-
: Infinity;
|
|
728
|
-
|
|
729
|
-
const netExpectancyBts = pair.totalRealizedPnlNet / total;
|
|
730
|
-
|
|
731
|
-
// ─── Risk-adjusted ratios (window-aware annualisation) ────────────────
|
|
732
|
-
// Bin the window's net PnL into calendar periods and annualise with the
|
|
733
|
-
// matching periods-per-year. Every period in the window is represented
|
|
734
|
-
// (zero-filled): flat periods must count as 0 PnL, otherwise a bot that
|
|
735
|
-
// trades a few days a week is scored as if it traded every day, and the
|
|
736
|
-
// window cannot be scaled honestly to a year.
|
|
737
|
-
const HOUR_MS = 3600_000;
|
|
738
|
-
const DAY_MS = 86_400_000;
|
|
739
|
-
const times = pnls.map(r => Date.parse(r.exitTime)).filter(t => Number.isFinite(t));
|
|
740
|
-
const firstMs = window?.startMs ?? (times.length > 0 ? Math.min(...times) : 0);
|
|
741
|
-
const lastMs = window?.endMs ?? (times.length > 0 ? Math.max(...times) : firstMs + DAY_MS);
|
|
742
|
-
const spanMs = Math.max(lastMs - firstMs, window ? HOUR_MS : DAY_MS);
|
|
743
|
-
const periodSpanDays = spanMs / DAY_MS;
|
|
744
|
-
// Daily buckets need a handful of observations before a daily std means
|
|
745
|
-
// anything; shorter windows fall back to hourly bins so they still
|
|
746
|
-
// annualise instead of dividing by a one-sample std.
|
|
747
|
-
const useHourly = periodSpanDays < 3;
|
|
748
|
-
const periodMs = useHourly ? HOUR_MS : DAY_MS;
|
|
749
|
-
const periodsPerYear = useHourly ? 8760 : 365;
|
|
750
|
-
const periodLabel = useHourly ? '1h' : '1d';
|
|
751
|
-
|
|
752
|
-
// Score only whole periods: a trailing partial period (window not an exact
|
|
753
|
-
// multiple of the bin) would otherwise be a deflated observation. It is
|
|
754
|
-
// excluded from ratios, projection AND activity rates alike, so every
|
|
755
|
-
// window-derived metric shares one basis. Bins are aligned to the window
|
|
756
|
-
// start, so an exact-multiple window scores everything.
|
|
757
|
-
const nPeriods = Math.max(1, Math.floor(spanMs / periodMs));
|
|
758
|
-
const scoredSpanDays = nPeriods * periodMs / DAY_MS;
|
|
759
|
-
const scoredEndMs = firstMs + nPeriods * periodMs;
|
|
760
|
-
const exactWindow = spanMs === nPeriods * periodMs;
|
|
761
|
-
// A fill belongs to the scored window if it falls inside the whole
|
|
762
|
-
// periods. On an exact-multiple window the end boundary is inclusive (the
|
|
763
|
-
// ES range query includes `lte`); with a partial tail that boundary fill
|
|
764
|
-
// is trailing and excluded along with the rest of the tail.
|
|
765
|
-
const inScoredWindow = (t: number) =>
|
|
766
|
-
Number.isFinite(t) && t >= firstMs
|
|
767
|
-
&& (t < scoredEndMs || (exactWindow && t === scoredEndMs));
|
|
768
|
-
const periodPnl = new Array<number>(nPeriods).fill(0);
|
|
769
|
-
let scoredFillCount = 0;
|
|
770
|
-
for (const r of pnls) {
|
|
771
|
-
const t = Date.parse(r.exitTime);
|
|
772
|
-
if (!inScoredWindow(t)) continue;
|
|
773
|
-
let idx = Math.floor((t - firstMs) / periodMs);
|
|
774
|
-
if (idx === nPeriods) idx = nPeriods - 1; // inclusive end boundary
|
|
775
|
-
periodPnl[idx] += r.pnlNet;
|
|
776
|
-
scoredFillCount++;
|
|
777
|
-
}
|
|
778
|
-
|
|
779
|
-
const meanPeriod = periodPnl.reduce((s, v) => s + v, 0) / nPeriods;
|
|
780
|
-
// Sample variance (n-1): the window is a sample, not the whole population.
|
|
781
|
-
const periodVar = nPeriods > 1
|
|
782
|
-
? periodPnl.reduce((s, v) => s + (v - meanPeriod) ** 2, 0) / (nPeriods - 1)
|
|
783
|
-
: 0;
|
|
784
|
-
const periodStd = Math.sqrt(periodVar);
|
|
785
|
-
const annualFactor = Math.sqrt(periodsPerYear);
|
|
786
|
-
const sharpeAnn = periodStd > 0 ? (meanPeriod / periodStd) * annualFactor : NaN;
|
|
787
|
-
|
|
788
|
-
// Estimation uncertainty of the annualised Sharpe (Lo 2002, i.i.d. returns).
|
|
789
|
-
const srPerPeriod = periodStd > 0 ? meanPeriod / periodStd : NaN;
|
|
790
|
-
const sharpeAnnSE = nPeriods > 1 && Number.isFinite(srPerPeriod)
|
|
791
|
-
? Math.sqrt((1 + 0.5 * srPerPeriod * srPerPeriod) / nPeriods) * annualFactor
|
|
792
|
-
: NaN;
|
|
793
|
-
|
|
794
|
-
// Target downside deviation (MAR = 0), sample denominator (n-1) to match
|
|
795
|
-
// the Sharpe convention above — the two ratios stay internally
|
|
796
|
-
// comparable (many textbook Sortinos divide by N; we deliberately
|
|
797
|
-
// don't mix conventions). With no losing periods Sortino is undefined —
|
|
798
|
-
// reporting 0 would read as "terrible", the opposite of truth.
|
|
799
|
-
const downsideVar = nPeriods > 1
|
|
800
|
-
? periodPnl.reduce((s, v) => s + (v < 0 ? v * v : 0), 0) / (nPeriods - 1)
|
|
801
|
-
: 0;
|
|
802
|
-
const downsideStd = Math.sqrt(downsideVar);
|
|
803
|
-
const sortinoAnn = nPeriods < 2
|
|
804
|
-
? NaN
|
|
805
|
-
: (downsideStd > 0
|
|
806
|
-
? (meanPeriod / downsideStd) * annualFactor
|
|
807
|
-
: (meanPeriod > 0 ? Infinity : NaN));
|
|
808
|
-
|
|
809
|
-
// "This window repeated all year" — linear projection of the scored
|
|
810
|
-
// window's net PnL. Uses the same whole-period basis as the ratios
|
|
811
|
-
// above (not the raw window total), so Sharpe and projection can never
|
|
812
|
-
// disagree about what the window contains.
|
|
813
|
-
const scoredPnl = periodPnl.reduce((s, v) => s + v, 0);
|
|
814
|
-
const projectedNetPnlPerDay = scoredPnl / scoredSpanDays;
|
|
815
|
-
const projectedNetPnlAnn = projectedNetPnlPerDay * 365;
|
|
816
|
-
|
|
817
|
-
// Fills-per-order distribution (grouped by sell order)
|
|
818
|
-
const fillCounts: number[] = [];
|
|
819
|
-
const orderMap = new Map<string, number>();
|
|
820
|
-
for (const r of pnls) {
|
|
821
|
-
orderMap.set(r.exitOrderId, (orderMap.get(r.exitOrderId) || 0) + 1);
|
|
822
|
-
}
|
|
823
|
-
for (const c of orderMap.values()) fillCounts.push(c);
|
|
824
|
-
const sellOrdersFilled = orderMap.size;
|
|
825
|
-
const fillsPerOrderMean = sellOrdersFilled > 0
|
|
826
|
-
? fillCounts.reduce((s, v) => s + v, 0) / sellOrdersFilled
|
|
827
|
-
: 0;
|
|
828
|
-
const fillsPerOrderMax = sellOrdersFilled > 0
|
|
829
|
-
? fillCounts.reduce((a, b) => Math.max(a, b), 0)
|
|
830
|
-
: 0;
|
|
831
|
-
const sortedCounts = [...fillCounts].sort((a, b) => a - b);
|
|
832
|
-
const fillsPerOrderMedian = sellOrdersFilled > 0 ? percentile(sortedCounts, 50) : 0;
|
|
833
|
-
const oneShotOrderRatio = sellOrdersFilled > 0
|
|
834
|
-
? fillCounts.filter(c => c === 1).length / sellOrdersFilled
|
|
835
|
-
: 0;
|
|
836
|
-
// Activity rates share the scored whole-period basis: numerator and
|
|
837
|
-
// denominator both cover exactly the lots/fills the ratios scored. A fill
|
|
838
|
-
// with an unparseable timestamp has no period, so it is excluded here too.
|
|
839
|
-
const scoredNotional = [...pair.buys, ...pair.sells]
|
|
840
|
-
.reduce((s, f) => s + (inScoredWindow(Date.parse(f.time)) ? f.quoteAmount : 0), 0);
|
|
841
|
-
const fillsPerDay = scoredSpanDays > 0 ? scoredFillCount / scoredSpanDays : 0;
|
|
842
|
-
const avgVolumePerDay = scoredSpanDays > 0 ? scoredNotional / scoredSpanDays : 0;
|
|
843
|
-
|
|
844
|
-
// Avg hold duration
|
|
845
|
-
let totalHours = 0;
|
|
846
|
-
let hourCount = 0;
|
|
847
|
-
for (const r of pnls) {
|
|
848
|
-
const entry = new Date(r.entryTime).getTime();
|
|
849
|
-
const exit = new Date(r.exitTime).getTime();
|
|
850
|
-
if (!isNaN(entry) && !isNaN(exit) && exit > entry) {
|
|
851
|
-
totalHours += (exit - entry) / 3600000;
|
|
852
|
-
hourCount++;
|
|
853
|
-
}
|
|
854
|
-
}
|
|
855
|
-
const avgHoldHours = hourCount > 0 ? totalHours / hourCount : 0;
|
|
856
|
-
|
|
857
|
-
// Max consecutive wins / losses (aggregated by exit order)
|
|
858
|
-
const orderPnls = new Map<string, { pnl: number; time: string }>();
|
|
859
|
-
for (const r of pnls) {
|
|
860
|
-
const existing = orderPnls.get(r.exitOrderId);
|
|
861
|
-
if (existing) {
|
|
862
|
-
existing.pnl += r.pnl;
|
|
863
|
-
} else {
|
|
864
|
-
orderPnls.set(r.exitOrderId, { pnl: r.pnl, time: r.exitTime });
|
|
865
|
-
}
|
|
866
|
-
}
|
|
867
|
-
const orderResults = [...orderPnls.values()].sort((a, b) =>
|
|
868
|
-
new Date(a.time).getTime() - new Date(b.time).getTime()
|
|
869
|
-
);
|
|
870
|
-
let consecW = 0, consecL = 0;
|
|
871
|
-
let maxW = 0, maxL = 0;
|
|
872
|
-
for (const { pnl } of orderResults) {
|
|
873
|
-
if (pnl > 0) { consecW++; consecL = 0; maxW = Math.max(maxW, consecW); }
|
|
874
|
-
else if (pnl < 0) { consecL++; consecW = 0; maxL = Math.max(maxL, consecL); }
|
|
875
|
-
else { consecW = 0; consecL = 0; }
|
|
876
|
-
}
|
|
877
|
-
|
|
878
|
-
// ─── Max Drawdown + Recovery Time ───────────────────────────────────
|
|
879
|
-
const STABILITY_TRADES = 3;
|
|
880
|
-
const MIN_TRADES_FOR_PEAK = 10; // backstop for monotonic equity curves
|
|
881
|
-
const chronological = [...pnls].sort((a, b) =>
|
|
882
|
-
new Date(a.exitTime).getTime() - new Date(b.exitTime).getTime()
|
|
883
|
-
);
|
|
884
|
-
let equity = 0, peak = 0, mddPct = 0, mddAbsBts = 0;
|
|
885
|
-
let maxRecoveryDays = 0;
|
|
886
|
-
let isOngoingRecovery = false;
|
|
887
|
-
let currentDrawdownDays = 0;
|
|
888
|
-
let drawdownStartTime = 0;
|
|
889
|
-
let troughTime = 0;
|
|
890
|
-
let currentTroughEquity = Infinity;
|
|
891
|
-
let hadStablePeak = false;
|
|
892
|
-
let tradesSincePeakSet = 0;
|
|
893
|
-
let hasPrePeakEquity = false;
|
|
894
|
-
let prePeakMinEquity = 0;
|
|
895
|
-
let totalTradesProcessed = 0;
|
|
896
|
-
|
|
897
|
-
for (const r of chronological) {
|
|
898
|
-
totalTradesProcessed++;
|
|
899
|
-
equity += r.pnlNet;
|
|
900
|
-
if (equity > peak) {
|
|
901
|
-
if (troughTime > 0 && hadStablePeak) {
|
|
902
|
-
const recoveryDays = (new Date(r.exitTime).getTime() - troughTime) / 86400000;
|
|
903
|
-
if (recoveryDays > maxRecoveryDays) maxRecoveryDays = recoveryDays;
|
|
904
|
-
}
|
|
905
|
-
peak = equity;
|
|
906
|
-
tradesSincePeakSet = 0;
|
|
907
|
-
currentTroughEquity = Infinity;
|
|
908
|
-
troughTime = 0;
|
|
909
|
-
drawdownStartTime = 0;
|
|
910
|
-
} else {
|
|
911
|
-
tradesSincePeakSet++;
|
|
912
|
-
if (tradesSincePeakSet >= STABILITY_TRADES) {
|
|
913
|
-
hadStablePeak = true;
|
|
914
|
-
}
|
|
915
|
-
}
|
|
916
|
-
if (!hadStablePeak && totalTradesProcessed >= MIN_TRADES_FOR_PEAK) {
|
|
917
|
-
hadStablePeak = true;
|
|
918
|
-
}
|
|
919
|
-
|
|
920
|
-
if (hadStablePeak && equity < peak && peak > 0) {
|
|
921
|
-
if (drawdownStartTime === 0) drawdownStartTime = new Date(r.exitTime).getTime();
|
|
922
|
-
if (equity < currentTroughEquity) {
|
|
923
|
-
currentTroughEquity = equity;
|
|
924
|
-
troughTime = new Date(r.exitTime).getTime();
|
|
925
|
-
}
|
|
926
|
-
const dd = (equity - peak) / peak;
|
|
927
|
-
if (dd < mddPct) mddPct = dd;
|
|
928
|
-
const ddAbs = peak - equity;
|
|
929
|
-
if (ddAbs > mddAbsBts) mddAbsBts = ddAbs;
|
|
930
|
-
}
|
|
931
|
-
|
|
932
|
-
if (peak > 0 && !hadStablePeak) {
|
|
933
|
-
if (!hasPrePeakEquity || equity < prePeakMinEquity) {
|
|
934
|
-
prePeakMinEquity = equity;
|
|
935
|
-
hasPrePeakEquity = true;
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
}
|
|
939
|
-
|
|
940
|
-
if (drawdownStartTime > 0 && hadStablePeak) {
|
|
941
|
-
const lastTime = new Date(chronological[chronological.length - 1].exitTime).getTime();
|
|
942
|
-
currentDrawdownDays = (lastTime - drawdownStartTime) / 86400000;
|
|
943
|
-
isOngoingRecovery = true;
|
|
944
|
-
if (currentDrawdownDays > maxRecoveryDays) {
|
|
945
|
-
maxRecoveryDays = currentDrawdownDays;
|
|
946
|
-
}
|
|
947
|
-
}
|
|
948
|
-
|
|
949
|
-
if (hadStablePeak) {
|
|
950
|
-
mddPct *= 100;
|
|
951
|
-
} else {
|
|
952
|
-
mddPct = hasPrePeakEquity ? prePeakMinEquity : 0;
|
|
953
|
-
mddAbsBts = 0;
|
|
954
|
-
}
|
|
955
|
-
|
|
956
|
-
// Payoff distribution stats
|
|
957
|
-
const pnlPcts = [...pnls.map(r => r.pnlPct)].sort((a, b) => a - b);
|
|
958
|
-
const medianPnlPct = percentile(pnlPcts, 50);
|
|
959
|
-
const p25PnlPct = percentile(pnlPcts, 25);
|
|
960
|
-
const p75PnlPct = percentile(pnlPcts, 75);
|
|
961
|
-
const absAvgLoss = Math.abs(avgLoss);
|
|
962
|
-
let rValues: number[] = [];
|
|
963
|
-
if (absAvgLoss > 0) {
|
|
964
|
-
rValues = pnls.map(r => r.pnl / absAvgLoss).sort((a, b) => a - b);
|
|
965
|
-
}
|
|
966
|
-
const medianR = rValues.length > 0 ? percentile(rValues, 50) : 0;
|
|
967
|
-
const pctRGreater1 = rValues.length > 0 ? rValues.filter(r => r > 1).length / rValues.length : 0;
|
|
968
|
-
const pctRGreater2 = rValues.length > 0 ? rValues.filter(r => r > 2).length / rValues.length : 0;
|
|
969
|
-
const pctRLessNeg1 = rValues.length > 0 ? rValues.filter(r => r < -1).length / rValues.length : 0;
|
|
970
|
-
|
|
971
|
-
const bestTradePct = pnlPcts.length > 0 ? pnlPcts[pnlPcts.length - 1] : 0;
|
|
972
|
-
const worstTradePct = pnlPcts.length > 0 ? pnlPcts[0] : 0;
|
|
973
|
-
|
|
974
|
-
return {
|
|
975
|
-
totalLots: total,
|
|
976
|
-
winRate,
|
|
977
|
-
profitFactor,
|
|
978
|
-
avgWin,
|
|
979
|
-
avgLoss,
|
|
980
|
-
avgWinLossRatio,
|
|
981
|
-
expectancyBts,
|
|
982
|
-
expectancyPct,
|
|
983
|
-
expectancyR,
|
|
984
|
-
netExpectancyBts,
|
|
985
|
-
sharpeAnn,
|
|
986
|
-
sortinoAnn,
|
|
987
|
-
sharpeAnnSE,
|
|
988
|
-
periodLabel,
|
|
989
|
-
periodCount: nPeriods,
|
|
990
|
-
periodSpanDays,
|
|
991
|
-
scoredSpanDays,
|
|
992
|
-
annualFactor,
|
|
993
|
-
projectedNetPnlPerDay,
|
|
994
|
-
projectedNetPnlAnn,
|
|
995
|
-
feeDragPct,
|
|
996
|
-
maxConsecWins: maxW,
|
|
997
|
-
maxConsecLosses: maxL,
|
|
998
|
-
avgHoldHours,
|
|
999
|
-
limitOrderRatio: total > 0 ? totalMakerLegs / (total * 2) : 0,
|
|
1000
|
-
bestTradePct,
|
|
1001
|
-
worstTradePct,
|
|
1002
|
-
mddPct,
|
|
1003
|
-
mddAbsBts,
|
|
1004
|
-
mddHadStablePeak: hadStablePeak,
|
|
1005
|
-
isOngoingRecovery,
|
|
1006
|
-
currentDrawdownDays,
|
|
1007
|
-
maxRecoveryDays,
|
|
1008
|
-
medianPnlPct,
|
|
1009
|
-
p25PnlPct,
|
|
1010
|
-
p75PnlPct,
|
|
1011
|
-
medianR,
|
|
1012
|
-
pctRGreater1,
|
|
1013
|
-
pctRGreater2,
|
|
1014
|
-
pctRLessNeg1,
|
|
1015
|
-
sellOrdersFilled,
|
|
1016
|
-
fillsPerOrderMean,
|
|
1017
|
-
fillsPerOrderMedian,
|
|
1018
|
-
fillsPerOrderMax,
|
|
1019
|
-
oneShotOrderRatio,
|
|
1020
|
-
fillsPerDay,
|
|
1021
|
-
avgVolumePerDay,
|
|
1022
|
-
};
|
|
1023
|
-
}
|
|
1024
|
-
|
|
1025
|
-
function printMetrics(pairs: PairAnalysis[], window?: WindowRange) {
|
|
1026
|
-
for (const pair of pairs) {
|
|
1027
|
-
if (pair.realizedPnls.length === 0) continue;
|
|
1028
|
-
|
|
1029
|
-
const m = computeMetrics(pair, window);
|
|
1030
|
-
const pairLabel = `${fmtAsset(pair.baseAsset)}/${fmtAsset(pair.quoteAsset)}`;
|
|
1031
|
-
|
|
1032
|
-
console.log('');
|
|
1033
|
-
console.log(` ── ${pairLabel} — Performance Metrics`);
|
|
1034
|
-
console.log('');
|
|
1035
|
-
// Edge
|
|
1036
|
-
console.log(` Win Rate: ${(m.winRate * 100).toFixed(1)}%`);
|
|
1037
|
-
console.log(` Profit Factor: ${m.profitFactor === Infinity ? '∞' : m.profitFactor.toFixed(2)}`);
|
|
1038
|
-
const mktFeeStr = pair.totalMarketFees > 0.0001 ? ` (market ${fmt(pair.totalMarketFees, 4)})` : '';
|
|
1039
|
-
const blkFeeStr = pair.totalBlockchainFees > 0.0001 ? ` (op ${fmt(pair.totalBlockchainFees, 4)} BTS)` : '';
|
|
1040
|
-
console.log(` Fee Drag: ${m.feeDragPct > 0 ? m.feeDragPct.toFixed(2) + '% of gross profit' + mktFeeStr + blkFeeStr : '—'}`);
|
|
1041
|
-
console.log(` Avg Win / Avg Loss: ${m.avgWinLossRatio === Infinity ? '∞' : m.avgWinLossRatio.toFixed(2)}`);
|
|
1042
|
-
const qSymbol = fmtAsset(pair.quoteAsset);
|
|
1043
|
-
console.log(` Expectancy (gross): ${fmt(m.expectancyBts, 4)} ${qSymbol} (${fmtPct(m.expectancyPct)}) per trade`);
|
|
1044
|
-
const rDisplay = m.expectancyR === Infinity ? '∞' : m.expectancyR.toFixed(3) + 'R';
|
|
1045
|
-
console.log(` Expectancy (R): ${rDisplay}`);
|
|
1046
|
-
console.log(` Expectancy (net): ${fmt(m.netExpectancyBts, 4)} ${qSymbol} per trade`);
|
|
1047
|
-
console.log('');
|
|
1048
|
-
// Edge quality
|
|
1049
|
-
console.log(` Median R: ${m.medianR.toFixed(2)}`);
|
|
1050
|
-
console.log(` Trades > 1R / > 2R: ${(m.pctRGreater1 * 100).toFixed(1)}% / ${(m.pctRGreater2 * 100).toFixed(1)}%`);
|
|
1051
|
-
console.log(` Trades < -1R: ${(m.pctRLessNeg1 * 100).toFixed(1)}%`);
|
|
1052
|
-
console.log('');
|
|
1053
|
-
// PnL distribution
|
|
1054
|
-
console.log(` Median PnL: ${fmtPct(m.medianPnlPct)}`);
|
|
1055
|
-
console.log(` P25 / P75: ${fmtPct(m.p25PnlPct)} / ${fmtPct(m.p75PnlPct)}`);
|
|
1056
|
-
console.log(` Best / Worst Trade: ${fmtPct(m.bestTradePct)} / ${fmtPct(m.worstTradePct)}`);
|
|
1057
|
-
console.log('');
|
|
1058
|
-
// Risk-adjusted — annualised from the analysis window, zero-filled bins
|
|
1059
|
-
const ratioStr = (v: number) => Number.isFinite(v) ? v.toFixed(2) : (v === Infinity ? '∞' : 'n/a');
|
|
1060
|
-
const seStr = Number.isFinite(m.sharpeAnnSE) ? ` ± ${m.sharpeAnnSE.toFixed(2)}` : '';
|
|
1061
|
-
const confidence = m.periodSpanDays < 30 ? 'low confidence' : 'ok';
|
|
1062
|
-
console.log(` Sharpe (ann): ${ratioStr(m.sharpeAnn)}${seStr} [${m.periodLabel} bins, n=${m.periodCount}, ${confidence}]`);
|
|
1063
|
-
const sortinoNote = m.sortinoAnn === Infinity ? ' (no losing periods)' : '';
|
|
1064
|
-
console.log(` Sortino (ann): ${ratioStr(m.sortinoAnn)}${sortinoNote}`);
|
|
1065
|
-
if (m.periodLabel === '1h') {
|
|
1066
|
-
console.log(` ⚠ window < 3 days: hourly bins over an unrepresentative sample — treat the annualised ratios as indicative only and never rank them against 1d-binned runs`);
|
|
1067
|
-
}
|
|
1068
|
-
const spanStr = m.scoredSpanDays < m.periodSpanDays - 1e-9
|
|
1069
|
-
? `${m.scoredSpanDays.toFixed(1)}d scored of ${m.periodSpanDays.toFixed(1)}d window`
|
|
1070
|
-
: `${m.periodSpanDays.toFixed(1)}d`;
|
|
1071
|
-
console.log(` Projected net PnL: ${fmt(m.projectedNetPnlAnn, 2)} ${qSymbol}/yr (${fmt(m.projectedNetPnlPerDay, 2)}/day over ${spanStr})`);
|
|
1072
|
-
console.log('');
|
|
1073
|
-
// Tail risk
|
|
1074
|
-
if (m.mddHadStablePeak) {
|
|
1075
|
-
console.log(` Max Drawdown: ${fmt(m.mddAbsBts, 4)} ${qSymbol} (${fmtPct(m.mddPct)} of peak cumulative profit)`);
|
|
1076
|
-
} else {
|
|
1077
|
-
console.log(` Min Equity: ${fmt(m.mddPct, 4)} ${fmtAsset(pair.quoteAsset)}`);
|
|
1078
|
-
}
|
|
1079
|
-
const recLabel = m.maxRecoveryDays > 0 ? m.maxRecoveryDays.toFixed(1) + ' days' + (m.isOngoingRecovery ? ' (ongoing)' : '') : '—';
|
|
1080
|
-
console.log(` Max Recovery Time: ${recLabel}`);
|
|
1081
|
-
if (m.currentDrawdownDays > 0) {
|
|
1082
|
-
console.log(` Current Drawdown: ${m.currentDrawdownDays.toFixed(1)} days (active)`);
|
|
1083
|
-
}
|
|
1084
|
-
console.log('');
|
|
1085
|
-
// Behavioral
|
|
1086
|
-
console.log(` Max Consecutive W/L: ${m.maxConsecWins} / ${m.maxConsecLosses}`);
|
|
1087
|
-
const holdDisplay = m.avgHoldHours > 0 ? m.avgHoldHours.toFixed(1) : '—';
|
|
1088
|
-
console.log(` Avg hold time: ${holdDisplay} hours`);
|
|
1089
|
-
console.log(` Maker / Taker: ${(m.limitOrderRatio * 100).toFixed(1)}% / ${((1 - m.limitOrderRatio) * 100).toFixed(1)}%`);
|
|
1090
|
-
console.log('');
|
|
1091
|
-
// Activity
|
|
1092
|
-
console.log(` Sell orders filled: ${m.sellOrdersFilled}`);
|
|
1093
|
-
console.log(` Partial fills/order: ${m.fillsPerOrderMean.toFixed(2)} mean, ${m.fillsPerOrderMedian.toFixed(1)} med, ${m.fillsPerOrderMax} max`);
|
|
1094
|
-
console.log(` One-shot orders: ${(m.oneShotOrderRatio * 100).toFixed(0)}%`);
|
|
1095
|
-
console.log(` Fills/day: ${m.fillsPerDay.toFixed(2)}`);
|
|
1096
|
-
console.log(` Avg vol/day: ${fmt(m.avgVolumePerDay, 2)} ${fmtAsset(pair.quoteAsset)}`);
|
|
1097
|
-
console.log('');
|
|
1098
|
-
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
// Grand totals grouped by quote asset
|
|
1102
|
-
const quoteGroups = new Map<string, PairAnalysis[]>();
|
|
1103
|
-
for (const p of pairs) {
|
|
1104
|
-
const q = p.quoteAsset;
|
|
1105
|
-
if (!quoteGroups.has(q)) quoteGroups.set(q, []);
|
|
1106
|
-
quoteGroups.get(q)!.push(p);
|
|
1107
|
-
}
|
|
1108
|
-
if (pairs.length > 1 && quoteGroups.size > 0) {
|
|
1109
|
-
for (const [quoteAsset, group] of quoteGroups) {
|
|
1110
|
-
const totalLots = group.reduce((s, p) => s + p.realizedPnls.length, 0);
|
|
1111
|
-
const totalNet = group.reduce((s, p) => s + p.totalRealizedPnlNet, 0);
|
|
1112
|
-
const totalMktFees = group.reduce((s, p) => s + p.totalMarketFees, 0);
|
|
1113
|
-
const totalBlkFees = group.reduce((s, p) => s + p.totalBlockchainFees, 0);
|
|
1114
|
-
const qSymbol = fmtAsset(quoteAsset);
|
|
1115
|
-
console.log(` ── TOTAL (${qSymbol}) — ${group.length} pair(s)`);
|
|
1116
|
-
console.log(` Lots: ${totalLots}`);
|
|
1117
|
-
const feeParts: string[] = [];
|
|
1118
|
-
if (totalMktFees > 0.0001) feeParts.push(`market ${fmt(totalMktFees, 4)} ${qSymbol}`);
|
|
1119
|
-
if (totalBlkFees > 0.0001) feeParts.push(`op ${fmt(totalBlkFees, 4)} BTS`);
|
|
1120
|
-
const feeSuffix = feeParts.length > 0 ? ` (${feeParts.join(', ')})` : '';
|
|
1121
|
-
console.log(` Net PnL: ${fmtAsset(quoteAsset)} ${fmt(totalNet, 4)}${feeSuffix}`);
|
|
1122
|
-
console.log('');
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
|
|
1127
|
-
// ─── CSV Export ──────────────────────────────────────────────────────────────
|
|
1128
|
-
|
|
1129
|
-
function exportCsv(pairs: PairAnalysis[], filePath: string) {
|
|
1130
|
-
const esc = (v: any) => { const s = String(v); return /[,"\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; };
|
|
1131
|
-
const lines = ['time,orderId,direction,baseAsset,quoteAsset,baseAmount,quoteAmount,price,isMaker,marketFeeReal,marketFeeAsset'];
|
|
1132
|
-
|
|
1133
|
-
for (const pair of pairs) {
|
|
1134
|
-
for (const t of [...pair.buys, ...pair.sells].sort((a, b) => a.sequence - b.sequence)) {
|
|
1135
|
-
lines.push([
|
|
1136
|
-
esc(t.time),
|
|
1137
|
-
esc(t.orderId),
|
|
1138
|
-
esc(t.direction),
|
|
1139
|
-
esc(t.baseAsset),
|
|
1140
|
-
esc(t.quoteAsset),
|
|
1141
|
-
t.baseAmount,
|
|
1142
|
-
t.quoteAmount,
|
|
1143
|
-
t.price,
|
|
1144
|
-
t.isMaker ? '1' : '0',
|
|
1145
|
-
t.marketFeeReal,
|
|
1146
|
-
esc(t.marketFeeAsset),
|
|
1147
|
-
].join(','));
|
|
1148
|
-
}
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
fs.writeFileSync(filePath, lines.join('\n'), 'utf-8');
|
|
1152
|
-
console.log(` Trades exported to ${filePath}`);
|
|
1153
|
-
}
|
|
1154
|
-
|
|
1155
|
-
// ─── JSON Export ─────────────────────────────────────────────────────────────
|
|
1156
|
-
|
|
1157
|
-
function exportJson(accountId: string, start: string, end: string, pairs: PairAnalysis[], filePath: string) {
|
|
1158
|
-
const data = {
|
|
1159
|
-
accountId,
|
|
1160
|
-
period: { start, end },
|
|
1161
|
-
pairs: pairs.map(p => ({
|
|
1162
|
-
baseAsset: p.baseAsset,
|
|
1163
|
-
quoteAsset: p.quoteAsset,
|
|
1164
|
-
summary: {
|
|
1165
|
-
totalBuyBase: p.totalBuyBase,
|
|
1166
|
-
totalSellBase: p.totalSellBase,
|
|
1167
|
-
totalBuyQuote: p.totalBuyQuote,
|
|
1168
|
-
totalSellQuote: p.totalSellQuote,
|
|
1169
|
-
netPosition: p.netPosition,
|
|
1170
|
-
totalRealizedPnl: p.totalRealizedPnl,
|
|
1171
|
-
totalMarketFees: p.totalMarketFees,
|
|
1172
|
-
totalBlockchainFees: p.totalBlockchainFees,
|
|
1173
|
-
totalRealizedPnlNet: p.totalRealizedPnlNet,
|
|
1174
|
-
},
|
|
1175
|
-
realizedPnls: p.realizedPnls.map(r => ({
|
|
1176
|
-
...r,
|
|
1177
|
-
marketFeeEntry: r.marketFeeEntry,
|
|
1178
|
-
marketFeeExit: r.marketFeeExit,
|
|
1179
|
-
feeBts: r.feeBts,
|
|
1180
|
-
pnlNet: r.pnlNet,
|
|
1181
|
-
pnlNetPct: r.pnlNetPct,
|
|
1182
|
-
})),
|
|
1183
|
-
totalBuys: p.buys.length,
|
|
1184
|
-
totalSells: p.sells.length,
|
|
1185
|
-
})),
|
|
1186
|
-
};
|
|
1187
|
-
fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
|
|
1188
|
-
console.log(` Full analysis exported to ${filePath}`);
|
|
1189
|
-
}
|
|
1190
|
-
|
|
1191
|
-
// ─── Main ────────────────────────────────────────────────────────────────────
|
|
1192
|
-
|
|
1193
|
-
/**
|
|
1194
|
-
* Normalize a user-supplied time bound into an ES-compatible ISO string.
|
|
1195
|
-
*
|
|
1196
|
-
* Parsing goes through `new Date()` so offset-bearing ISO strings
|
|
1197
|
-
* (e.g. 2026-07-07T12:00:00+02:00) are honored instead of being corrupted by a
|
|
1198
|
-
* blind 'Z' append (+02:00Z). A date-only --end expands to the end of that UTC
|
|
1199
|
-
* day (T23:59:59.999Z) — treating it as midnight silently dropped the final day.
|
|
1200
|
-
*/
|
|
1201
|
-
function normalizeTimeBound(raw: string, isEnd: boolean): string {
|
|
1202
|
-
const parsed = new Date(raw);
|
|
1203
|
-
if (isNaN(parsed.getTime())) {
|
|
1204
|
-
throw new Error(`Invalid ${isEnd ? '--end' : '--start'} time: ${raw}`);
|
|
1205
|
-
}
|
|
1206
|
-
let ms = parsed.getTime();
|
|
1207
|
-
if (isEnd && /^\d{4}-\d{2}-\d{2}$/.test(raw.trim())) {
|
|
1208
|
-
ms += 24 * 3600 * 1000 - 1;
|
|
1209
|
-
}
|
|
1210
|
-
return new Date(ms).toISOString();
|
|
1211
|
-
}
|
|
1212
|
-
|
|
1213
|
-
async function run() {
|
|
1214
|
-
const opts = parseArgs();
|
|
1215
|
-
let accountId = opts.accountId;
|
|
1216
|
-
|
|
1217
|
-
if (!/^1\.2\.\d+$/.test(String(accountId))) {
|
|
1218
|
-
// The Kibana query below filters on the 1.2.x account_id field, so a
|
|
1219
|
-
// name must always resolve first (a raw name would silently return
|
|
1220
|
-
// zero fills). Shared resolver: reuses a stored accountId from
|
|
1221
|
-
// profiles/bots.json when one matches the name and stamps the result
|
|
1222
|
-
// back onto the bot entry on a fresh lookup.
|
|
1223
|
-
const resolved = await resolveAccountRef(accountId, { refresh: opts.refreshAccount });
|
|
1224
|
-
if (!resolved.accountId) {
|
|
1225
|
-
console.error(` Could not resolve "${accountId}" to an account ID`);
|
|
1226
|
-
process.exit(1);
|
|
1227
|
-
}
|
|
1228
|
-
accountId = resolved.accountId;
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
|
-
// Build time range
|
|
1232
|
-
const now = new Date();
|
|
1233
|
-
let gte: string, lte: string;
|
|
1234
|
-
|
|
1235
|
-
if (opts.start && opts.end) {
|
|
1236
|
-
gte = normalizeTimeBound(opts.start, false);
|
|
1237
|
-
lte = normalizeTimeBound(opts.end, true);
|
|
1238
|
-
} else if (opts.start) {
|
|
1239
|
-
gte = normalizeTimeBound(opts.start, false);
|
|
1240
|
-
lte = now.toISOString();
|
|
1241
|
-
} else {
|
|
1242
|
-
const hours = opts.hours || 168;
|
|
1243
|
-
const start = new Date(now.getTime() - hours * 3600 * 1000);
|
|
1244
|
-
gte = start.toISOString();
|
|
1245
|
-
lte = now.toISOString();
|
|
1246
|
-
}
|
|
1247
|
-
|
|
1248
|
-
const KIBANA_CFG = { timeout: 60000 };
|
|
1249
|
-
|
|
1250
|
-
const fills = await fetchAllFills(KIBANA_CFG, accountId, gte, lte);
|
|
1251
|
-
|
|
1252
|
-
if (fills.length === 0) {
|
|
1253
|
-
console.log(' No fills found in the specified time range.');
|
|
1254
|
-
process.exit(0);
|
|
1255
|
-
}
|
|
1256
|
-
|
|
1257
|
-
// Resolve unknown asset precisions from blockchain
|
|
1258
|
-
await resolveAssetPrecisions(fills);
|
|
1259
|
-
|
|
1260
|
-
// Classify fills
|
|
1261
|
-
const { trades, pairs } = classifyFills(fills, opts.asset);
|
|
1262
|
-
|
|
1263
|
-
if (trades.length === 0) {
|
|
1264
|
-
console.log(' No trades could be classified (check asset filter or time range).');
|
|
1265
|
-
process.exit(0);
|
|
1266
|
-
}
|
|
1267
|
-
|
|
1268
|
-
console.log(`Account: ${accountId}`);
|
|
1269
|
-
console.log(`Period: ${gte.slice(0, 10)} → ${lte.slice(0, 10)}`);
|
|
1270
|
-
console.log(`Pairs: ${pairs.size}, ${trades.length} classified trades`);
|
|
1271
|
-
const hasCrossPair = [...pairs].some(p => p.split(':')[1] !== BTS_ID);
|
|
1272
|
-
if (hasCrossPair) {
|
|
1273
|
-
console.log(` Note: cross-pair trades (non-BTS quote) are included but PnL is in the pair's quote asset.`);
|
|
1274
|
-
}
|
|
1275
|
-
console.log('');
|
|
1276
|
-
|
|
1277
|
-
// Override blockchain fee from CLI if provided. Explicit --fee-per-order 0
|
|
1278
|
-
// is valid (free-fee account) and must not be dropped by a falsy check.
|
|
1279
|
-
if (opts.feePerOrder != null) {
|
|
1280
|
-
if (!Number.isFinite(opts.feePerOrder) || opts.feePerOrder < 0) {
|
|
1281
|
-
console.error(`Invalid --fee-per-order: ${opts.feePerOrder}`);
|
|
1282
|
-
process.exit(1);
|
|
1283
|
-
}
|
|
1284
|
-
BLOCKCHAIN_FEE_PER_FILL = opts.feePerOrder;
|
|
1285
|
-
}
|
|
1286
|
-
|
|
1287
|
-
// Analyze each pair
|
|
1288
|
-
const pairMap = new Map<string, TradeFill[]>();
|
|
1289
|
-
for (const t of trades) {
|
|
1290
|
-
const pairKey = `${t.baseAsset}:${t.quoteAsset}`;
|
|
1291
|
-
if (!pairMap.has(pairKey)) pairMap.set(pairKey, []);
|
|
1292
|
-
pairMap.get(pairKey)!.push(t);
|
|
1293
|
-
}
|
|
1294
|
-
|
|
1295
|
-
const analyses: PairAnalysis[] = [];
|
|
1296
|
-
for (const [key, pairTrades] of pairMap) {
|
|
1297
|
-
const analysis = analyzePair(pairTrades, opts.matchMode);
|
|
1298
|
-
analyses.push(analysis);
|
|
1299
|
-
|
|
1300
|
-
if (opts.verbose) {
|
|
1301
|
-
const [base, quote] = key.split(':');
|
|
1302
|
-
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} matched lots`);
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
|
|
1306
|
-
// Sort pairs by volume (total quote)
|
|
1307
|
-
analyses.sort((a, b) => (b.totalBuyQuote + b.totalSellQuote) - (a.totalBuyQuote + a.totalSellQuote));
|
|
1308
|
-
|
|
1309
|
-
// Output: summaries → grand total → per-match detail
|
|
1310
|
-
printSummary(analyses, accountId, gte, lte, opts.matchMode);
|
|
1311
|
-
|
|
1312
|
-
if (opts.showPnlDetail) {
|
|
1313
|
-
printPnlDetail(analyses);
|
|
1314
|
-
}
|
|
1315
|
-
|
|
1316
|
-
printMetrics(analyses, { startMs: Date.parse(gte), endMs: Date.parse(lte) });
|
|
1317
|
-
|
|
1318
|
-
if (opts.csv) {
|
|
1319
|
-
exportCsv(analyses, opts.csv);
|
|
1320
|
-
}
|
|
1321
|
-
|
|
1322
|
-
if (opts.json) {
|
|
1323
|
-
exportJson(accountId, gte, lte, analyses, opts.json);
|
|
1324
|
-
}
|
|
1325
|
-
}
|
|
1326
|
-
|
|
1327
|
-
export { analyzePair, classifyFills, computeMetrics, TradeFill, FillRecord, RealizedPnl, PairAnalysis, TradingMetrics };
|
|
1328
|
-
|
|
1329
|
-
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
1330
|
-
run().then(() => process.exit(0)).catch(e => {
|
|
1331
|
-
console.error('\n[fatal]', e.message);
|
|
1332
|
-
if (process.env.DEBUG) console.error(e.stack);
|
|
1333
|
-
process.exit(1);
|
|
1334
|
-
});
|
|
1335
|
-
}
|